mcp-use 1.34.2 → 1.34.3

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 (41) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/{chunk-QNMWBM3V.js → chunk-4GUL52TF.js} +1 -1
  3. package/dist/{chunk-3L7F47SI.js → chunk-BJIP3NFE.js} +4 -4
  4. package/dist/{chunk-Z3NHDOLS.js → chunk-CQPVGLM4.js} +1 -1
  5. package/dist/{chunk-P2JIVJY6.js → chunk-CXHJETCQ.js} +4 -4
  6. package/dist/{chunk-VJAQ2A7N.js → chunk-GTLSCTCO.js} +1 -1
  7. package/dist/{chunk-EJOL74UE.js → chunk-J67NWN5H.js} +1 -1
  8. package/dist/{chunk-6DJM56C3.js → chunk-KWYZMUVB.js} +2 -2
  9. package/dist/chunk-KX7P6L43.js +171 -0
  10. package/dist/{chunk-VT4KQHJI.js → chunk-MCYFETK3.js} +2 -2
  11. package/dist/{chunk-DENFIIV2.js → chunk-NJPLVA2I.js} +1 -1
  12. package/dist/chunk-NQYSWKWJ.js +2609 -0
  13. package/dist/{chunk-OYFQOSSW.js → chunk-NYIMA6MZ.js} +1 -1
  14. package/dist/chunk-PJB2MFKZ.js +954 -0
  15. package/dist/chunk-PSD6ATRG.js +562 -0
  16. package/dist/{chunk-T3QVQIYU.js → chunk-QLKY4PK3.js} +5 -5
  17. package/dist/chunk-SUVUANZ3.js +594 -0
  18. package/dist/chunk-XHP35F4S.js +204 -0
  19. package/dist/chunk-ZLHL3BY6.js +2690 -0
  20. package/dist/{client-24ODJASB.js → client-VKWZPQCL.js} +4 -4
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +6 -6
  23. package/dist/src/agents/index.cjs +1 -1
  24. package/dist/src/agents/index.js +4 -4
  25. package/dist/src/browser-agent.cjs +1 -1
  26. package/dist/src/browser-agent.js +2 -2
  27. package/dist/src/browser.cjs +1 -1
  28. package/dist/src/browser.js +4 -4
  29. package/dist/src/client.cjs +1 -1
  30. package/dist/src/client.js +4 -4
  31. package/dist/src/react/index.cjs +1 -1
  32. package/dist/src/react/index.js +4 -4
  33. package/dist/src/server/index.cjs +1 -1
  34. package/dist/src/server/index.js +7 -7
  35. package/dist/src/version.d.ts +1 -1
  36. package/dist/{stdio-CG6YESIU.js → stdio-37X7ETM7.js} +3 -3
  37. package/dist/{stdio-KZLWEEYB.js → stdio-CSGVA5IJ.js} +2 -2
  38. package/dist/stdio-FUBSRH66.js +13 -0
  39. package/dist/{tool-execution-helpers-GVP22F32.js → tool-execution-helpers-4LIAFMYM.js} +2 -2
  40. package/dist/tool-execution-helpers-HPVG5WVB.js +27 -0
  41. package/package.json +3 -3
@@ -0,0 +1,954 @@
1
+ import {
2
+ telFetch
3
+ } from "./chunk-BXZHMYMM.js";
4
+ import {
5
+ generateUUID
6
+ } from "./chunk-MTHLLDCX.js";
7
+ import {
8
+ logger
9
+ } from "./chunk-QWQYAQCK.js";
10
+ import {
11
+ __name,
12
+ __require
13
+ } from "./chunk-3GQAWCBQ.js";
14
+
15
+ // src/version.ts
16
+ var VERSION = "1.34.3";
17
+ function getPackageVersion() {
18
+ return VERSION;
19
+ }
20
+ __name(getPackageVersion, "getPackageVersion");
21
+
22
+ // src/telemetry/events.ts
23
+ import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps";
24
+ var BaseTelemetryEvent = class {
25
+ static {
26
+ __name(this, "BaseTelemetryEvent");
27
+ }
28
+ };
29
+ var MCPAgentExecutionEvent = class extends BaseTelemetryEvent {
30
+ constructor(data) {
31
+ super();
32
+ this.data = data;
33
+ }
34
+ static {
35
+ __name(this, "MCPAgentExecutionEvent");
36
+ }
37
+ get name() {
38
+ return "mcp_agent_execution";
39
+ }
40
+ get properties() {
41
+ return {
42
+ // Core execution info
43
+ execution_method: this.data.executionMethod,
44
+ query: this.data.query,
45
+ query_length: this.data.query.length,
46
+ success: this.data.success,
47
+ // Agent configuration
48
+ model_provider: this.data.modelProvider,
49
+ model_name: this.data.modelName,
50
+ server_count: this.data.serverCount,
51
+ server_identifiers: this.data.serverIdentifiers,
52
+ total_tools_available: this.data.totalToolsAvailable,
53
+ tools_available_names: this.data.toolsAvailableNames,
54
+ max_steps_configured: this.data.maxStepsConfigured,
55
+ memory_enabled: this.data.memoryEnabled,
56
+ use_server_manager: this.data.useServerManager,
57
+ // Execution parameters (always include, even if null)
58
+ max_steps_used: this.data.maxStepsUsed,
59
+ manage_connector: this.data.manageConnector,
60
+ external_history_used: this.data.externalHistoryUsed,
61
+ // Execution results (always include, even if null)
62
+ steps_taken: this.data.stepsTaken ?? null,
63
+ tools_used_count: this.data.toolsUsedCount ?? null,
64
+ tools_used_names: this.data.toolsUsedNames ?? null,
65
+ response: this.data.response ?? null,
66
+ response_length: this.data.response ? this.data.response.length : null,
67
+ execution_time_ms: this.data.executionTimeMs ?? null,
68
+ error_type: this.data.errorType ?? null,
69
+ conversation_history_length: this.data.conversationHistoryLength ?? null
70
+ };
71
+ }
72
+ };
73
+ function createServerRunEventData(server, transport) {
74
+ const toolRegistrations = Array.from(server.registrations.tools.values());
75
+ const promptRegistrations = Array.from(server.registrations.prompts.values());
76
+ const resourceRegistrations = Array.from(
77
+ server.registrations.resources.values()
78
+ );
79
+ const templateRegistrations = Array.from(
80
+ server.registrations.resourceTemplates.values()
81
+ );
82
+ const allResources = resourceRegistrations.map((r) => ({
83
+ name: r.config.name,
84
+ title: r.config.title ?? null,
85
+ description: r.config.description ?? null,
86
+ uri: r.config.uri ?? null,
87
+ mime_type: r.config.mimeType ?? null
88
+ }));
89
+ const appsSdkResources = allResources.filter(
90
+ (r) => r.mime_type === "text/html+skybridge"
91
+ );
92
+ const mcpUiResources = allResources.filter(
93
+ (r) => r.mime_type === "text/uri-list" || r.mime_type === "text/html"
94
+ );
95
+ const mcpAppsResources = allResources.filter(
96
+ (r) => r.mime_type === RESOURCE_MIME_TYPE
97
+ );
98
+ return {
99
+ transport,
100
+ toolsNumber: server.registeredTools.length,
101
+ resourcesNumber: server.registeredResources.length,
102
+ promptsNumber: server.registeredPrompts.length,
103
+ auth: !!server.oauthProvider,
104
+ name: server.config.name,
105
+ description: server.config.description ?? null,
106
+ baseUrl: server.serverBaseUrl ?? null,
107
+ toolNames: server.registeredTools.length > 0 ? server.registeredTools : null,
108
+ resourceNames: server.registeredResources.length > 0 ? server.registeredResources : null,
109
+ promptNames: server.registeredPrompts.length > 0 ? server.registeredPrompts : null,
110
+ tools: toolRegistrations.length > 0 ? toolRegistrations.map((r) => ({
111
+ name: r.config.name,
112
+ title: r.config.title ?? null,
113
+ description: r.config.description ?? null,
114
+ input_schema: r.config.schema ? JSON.stringify(r.config.schema) : null,
115
+ output_schema: r.config.outputSchema ? JSON.stringify(r.config.outputSchema) : null
116
+ })) : null,
117
+ resources: allResources.length > 0 ? allResources : null,
118
+ prompts: promptRegistrations.length > 0 ? promptRegistrations.map((r) => ({
119
+ name: r.config.name,
120
+ title: r.config.title ?? null,
121
+ description: r.config.description ?? null,
122
+ args: r.config.args ? JSON.stringify(r.config.args) : null
123
+ })) : null,
124
+ templates: templateRegistrations.length > 0 ? templateRegistrations.map((r) => ({
125
+ name: r.config.name,
126
+ title: r.config.title ?? null,
127
+ description: r.config.description ?? null
128
+ })) : null,
129
+ capabilities: {
130
+ logging: true,
131
+ resources: { subscribe: true, listChanged: true }
132
+ },
133
+ appsSdkResources: appsSdkResources.length > 0 ? appsSdkResources : null,
134
+ appsSdkResourcesNumber: appsSdkResources.length,
135
+ mcpUiResources: mcpUiResources.length > 0 ? mcpUiResources : null,
136
+ mcpUiResourcesNumber: mcpUiResources.length,
137
+ mcpAppsResources: mcpAppsResources.length > 0 ? mcpAppsResources : null,
138
+ mcpAppsResourcesNumber: mcpAppsResources.length
139
+ };
140
+ }
141
+ __name(createServerRunEventData, "createServerRunEventData");
142
+ var ServerRunEvent = class extends BaseTelemetryEvent {
143
+ constructor(data) {
144
+ super();
145
+ this.data = data;
146
+ }
147
+ static {
148
+ __name(this, "ServerRunEvent");
149
+ }
150
+ get name() {
151
+ return "server_run";
152
+ }
153
+ get properties() {
154
+ return {
155
+ transport: this.data.transport,
156
+ tools_number: this.data.toolsNumber,
157
+ resources_number: this.data.resourcesNumber,
158
+ prompts_number: this.data.promptsNumber,
159
+ auth: this.data.auth,
160
+ name: this.data.name,
161
+ description: this.data.description ?? null,
162
+ base_url: this.data.baseUrl ?? null,
163
+ tool_names: this.data.toolNames ?? null,
164
+ resource_names: this.data.resourceNames ?? null,
165
+ prompt_names: this.data.promptNames ?? null,
166
+ tools: this.data.tools ?? null,
167
+ resources: this.data.resources ?? null,
168
+ prompts: this.data.prompts ?? null,
169
+ templates: this.data.templates ?? null,
170
+ capabilities: this.data.capabilities ? JSON.stringify(this.data.capabilities) : null,
171
+ apps_sdk_resources: this.data.appsSdkResources ? JSON.stringify(this.data.appsSdkResources) : null,
172
+ apps_sdk_resources_number: this.data.appsSdkResourcesNumber ?? 0,
173
+ mcp_ui_resources: this.data.mcpUiResources ? JSON.stringify(this.data.mcpUiResources) : null,
174
+ mcp_ui_resources_number: this.data.mcpUiResourcesNumber ?? 0,
175
+ mcp_apps_resources: this.data.mcpAppsResources ? JSON.stringify(this.data.mcpAppsResources) : null,
176
+ mcp_apps_resources_number: this.data.mcpAppsResourcesNumber ?? 0
177
+ };
178
+ }
179
+ };
180
+ var ServerInitializeEvent = class extends BaseTelemetryEvent {
181
+ constructor(data) {
182
+ super();
183
+ this.data = data;
184
+ }
185
+ static {
186
+ __name(this, "ServerInitializeEvent");
187
+ }
188
+ get name() {
189
+ return "server_initialize_call";
190
+ }
191
+ get properties() {
192
+ return {
193
+ protocol_version: this.data.protocolVersion,
194
+ client_info: JSON.stringify(this.data.clientInfo),
195
+ client_capabilities: JSON.stringify(this.data.clientCapabilities),
196
+ session_id: this.data.sessionId ?? null
197
+ };
198
+ }
199
+ };
200
+ var ServerToolCallEvent = class extends BaseTelemetryEvent {
201
+ constructor(data) {
202
+ super();
203
+ this.data = data;
204
+ }
205
+ static {
206
+ __name(this, "ServerToolCallEvent");
207
+ }
208
+ get name() {
209
+ return "server_tool_call";
210
+ }
211
+ get properties() {
212
+ return {
213
+ tool_name: this.data.toolName,
214
+ length_input_argument: this.data.lengthInputArgument,
215
+ success: this.data.success,
216
+ error_type: this.data.errorType ?? null,
217
+ execution_time_ms: this.data.executionTimeMs ?? null
218
+ };
219
+ }
220
+ };
221
+ var ServerResourceCallEvent = class extends BaseTelemetryEvent {
222
+ constructor(data) {
223
+ super();
224
+ this.data = data;
225
+ }
226
+ static {
227
+ __name(this, "ServerResourceCallEvent");
228
+ }
229
+ get name() {
230
+ return "server_resource_call";
231
+ }
232
+ get properties() {
233
+ return {
234
+ name: this.data.name,
235
+ description: this.data.description,
236
+ contents: this.data.contents,
237
+ success: this.data.success,
238
+ error_type: this.data.errorType ?? null
239
+ };
240
+ }
241
+ };
242
+ var ServerPromptCallEvent = class extends BaseTelemetryEvent {
243
+ constructor(data) {
244
+ super();
245
+ this.data = data;
246
+ }
247
+ static {
248
+ __name(this, "ServerPromptCallEvent");
249
+ }
250
+ get name() {
251
+ return "server_prompt_call";
252
+ }
253
+ get properties() {
254
+ return {
255
+ name: this.data.name,
256
+ description: this.data.description,
257
+ success: this.data.success,
258
+ error_type: this.data.errorType ?? null
259
+ };
260
+ }
261
+ };
262
+ var ServerContextEvent = class extends BaseTelemetryEvent {
263
+ constructor(data) {
264
+ super();
265
+ this.data = data;
266
+ }
267
+ static {
268
+ __name(this, "ServerContextEvent");
269
+ }
270
+ get name() {
271
+ return `server_context_${this.data.contextType}`;
272
+ }
273
+ get properties() {
274
+ return {
275
+ context_type: this.data.contextType,
276
+ notification_type: this.data.notificationType ?? null
277
+ };
278
+ }
279
+ };
280
+ var MCPClientInitEvent = class extends BaseTelemetryEvent {
281
+ constructor(data) {
282
+ super();
283
+ this.data = data;
284
+ }
285
+ static {
286
+ __name(this, "MCPClientInitEvent");
287
+ }
288
+ get name() {
289
+ return "mcpclient_init";
290
+ }
291
+ get properties() {
292
+ return {
293
+ code_mode: this.data.codeMode,
294
+ sandbox: this.data.sandbox,
295
+ all_callbacks: this.data.allCallbacks,
296
+ verify: this.data.verify,
297
+ servers: this.data.servers,
298
+ num_servers: this.data.numServers,
299
+ is_browser: this.data.isBrowser
300
+ };
301
+ }
302
+ };
303
+ var ConnectorInitEvent = class extends BaseTelemetryEvent {
304
+ constructor(data) {
305
+ super();
306
+ this.data = data;
307
+ }
308
+ static {
309
+ __name(this, "ConnectorInitEvent");
310
+ }
311
+ get name() {
312
+ return "connector_init";
313
+ }
314
+ get properties() {
315
+ return {
316
+ connector_type: this.data.connectorType,
317
+ server_command: this.data.serverCommand ?? null,
318
+ server_args: this.data.serverArgs ?? null,
319
+ server_url: this.data.serverUrl ?? null,
320
+ public_identifier: this.data.publicIdentifier ?? null
321
+ };
322
+ }
323
+ };
324
+ var ClientAddServerEvent = class extends BaseTelemetryEvent {
325
+ constructor(data) {
326
+ super();
327
+ this.data = data;
328
+ }
329
+ static {
330
+ __name(this, "ClientAddServerEvent");
331
+ }
332
+ get name() {
333
+ return "client_add_server";
334
+ }
335
+ get properties() {
336
+ const { serverName, serverConfig } = this.data;
337
+ const url = serverConfig.url;
338
+ return {
339
+ server_name: serverName,
340
+ server_url_domain: url ? this._extractHostname(url) : null,
341
+ transport: serverConfig.transport ?? null,
342
+ has_auth: !!(serverConfig.authToken || serverConfig.authProvider)
343
+ };
344
+ }
345
+ _extractHostname(url) {
346
+ try {
347
+ return new URL(url).hostname;
348
+ } catch {
349
+ return null;
350
+ }
351
+ }
352
+ };
353
+ var ClientRemoveServerEvent = class extends BaseTelemetryEvent {
354
+ constructor(data) {
355
+ super();
356
+ this.data = data;
357
+ }
358
+ static {
359
+ __name(this, "ClientRemoveServerEvent");
360
+ }
361
+ get name() {
362
+ return "client_remove_server";
363
+ }
364
+ get properties() {
365
+ return {
366
+ server_name: this.data.serverName
367
+ };
368
+ }
369
+ };
370
+
371
+ // src/telemetry/utils.ts
372
+ function getModelProvider(llm) {
373
+ return llm._llm_type || llm.constructor.name.toLowerCase();
374
+ }
375
+ __name(getModelProvider, "getModelProvider");
376
+ function getModelName(llm) {
377
+ if ("_identifyingParams" in llm) {
378
+ const identifyingParams = llm._identifyingParams;
379
+ if (typeof identifyingParams === "object" && identifyingParams !== null) {
380
+ for (const key of [
381
+ "model",
382
+ "modelName",
383
+ "model_name",
384
+ "modelId",
385
+ "model_id",
386
+ "deploymentName",
387
+ "deployment_name"
388
+ ]) {
389
+ if (key in identifyingParams) {
390
+ return String(identifyingParams[key]);
391
+ }
392
+ }
393
+ }
394
+ }
395
+ return llm.model || llm.modelName || llm.constructor.name;
396
+ }
397
+ __name(getModelName, "getModelName");
398
+ function extractModelInfo(llm) {
399
+ return [getModelProvider(llm), getModelName(llm)];
400
+ }
401
+ __name(extractModelInfo, "extractModelInfo");
402
+
403
+ // src/telemetry/telemetry-node.ts
404
+ function secureRandomString() {
405
+ try {
406
+ const crypto = __require("crypto");
407
+ return crypto.randomBytes(8).toString("hex");
408
+ } catch (e) {
409
+ return Math.random().toString(36).substring(2, 15);
410
+ }
411
+ }
412
+ __name(secureRandomString, "secureRandomString");
413
+ function detectRuntimeEnvironment() {
414
+ try {
415
+ if (typeof globalThis.Bun !== "undefined") {
416
+ return "bun";
417
+ }
418
+ if (typeof globalThis.Deno !== "undefined") {
419
+ return "deno";
420
+ }
421
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
422
+ return "cloudflare-workers";
423
+ }
424
+ if (typeof globalThis.EdgeRuntime !== "undefined") {
425
+ return "edge";
426
+ }
427
+ if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined") {
428
+ return "node";
429
+ }
430
+ return "unknown";
431
+ } catch {
432
+ return "unknown";
433
+ }
434
+ }
435
+ __name(detectRuntimeEnvironment, "detectRuntimeEnvironment");
436
+ function getStorageCapability(env) {
437
+ switch (env) {
438
+ case "node":
439
+ case "bun":
440
+ return "filesystem";
441
+ case "deno":
442
+ return "session-only";
443
+ default:
444
+ return "session-only";
445
+ }
446
+ }
447
+ __name(getStorageCapability, "getStorageCapability");
448
+ var cachedEnvironment = null;
449
+ function getRuntimeEnvironment() {
450
+ if (cachedEnvironment === null) {
451
+ cachedEnvironment = detectRuntimeEnvironment();
452
+ }
453
+ return cachedEnvironment;
454
+ }
455
+ __name(getRuntimeEnvironment, "getRuntimeEnvironment");
456
+ var ScarfEventLogger = class {
457
+ static {
458
+ __name(this, "ScarfEventLogger");
459
+ }
460
+ endpoint;
461
+ timeout;
462
+ constructor(endpoint, timeout = 3e3) {
463
+ this.endpoint = endpoint;
464
+ this.timeout = timeout;
465
+ }
466
+ async logEvent(properties) {
467
+ try {
468
+ const controller = new AbortController();
469
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
470
+ const response = await fetch(this.endpoint, {
471
+ method: "POST",
472
+ headers: {
473
+ "Content-Type": "application/json"
474
+ },
475
+ body: JSON.stringify(properties),
476
+ signal: controller.signal
477
+ });
478
+ clearTimeout(timeoutId);
479
+ if (!response.ok) {
480
+ throw new Error(`HTTP error! status: ${response.status}`);
481
+ }
482
+ } catch (error) {
483
+ logger.debug(`Failed to send Scarf event: ${error}`);
484
+ }
485
+ }
486
+ };
487
+ var Telemetry = class _Telemetry {
488
+ static {
489
+ __name(this, "Telemetry");
490
+ }
491
+ static instance = null;
492
+ PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
493
+ HOST = "https://eu.i.posthog.com";
494
+ SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
495
+ UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
496
+ _currUserId = null;
497
+ _posthogNodeClient = null;
498
+ _posthogLoading = null;
499
+ _scarfClient = null;
500
+ _runtimeEnvironment;
501
+ _storageCapability;
502
+ _source;
503
+ // Node.js specific paths (lazily computed)
504
+ _userIdPath = null;
505
+ _versionDownloadPath = null;
506
+ constructor() {
507
+ this._runtimeEnvironment = getRuntimeEnvironment();
508
+ this._storageCapability = getStorageCapability(this._runtimeEnvironment);
509
+ this._source = typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE || this._runtimeEnvironment;
510
+ const telemetryDisabled = this._checkTelemetryDisabled();
511
+ const canSupportTelemetry = this._runtimeEnvironment !== "unknown";
512
+ if (telemetryDisabled) {
513
+ this._posthogNodeClient = null;
514
+ this._scarfClient = null;
515
+ logger.debug("Telemetry disabled via environment variable");
516
+ } else if (!canSupportTelemetry) {
517
+ this._posthogNodeClient = null;
518
+ this._scarfClient = null;
519
+ logger.debug(
520
+ `Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`
521
+ );
522
+ } else {
523
+ logger.debug(
524
+ "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
525
+ );
526
+ this._posthogLoading = this._initPostHogNode();
527
+ try {
528
+ this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
529
+ } catch (e) {
530
+ logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
531
+ this._scarfClient = null;
532
+ }
533
+ if (this._storageCapability === "filesystem" && this._scarfClient) {
534
+ setTimeout(() => {
535
+ this.trackPackageDownload({ triggered_by: "initialization" }).catch(
536
+ (e) => logger.debug(`Failed to track package download: ${e}`)
537
+ );
538
+ }, 0);
539
+ }
540
+ }
541
+ }
542
+ _checkTelemetryDisabled() {
543
+ if (typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false") {
544
+ return true;
545
+ }
546
+ return false;
547
+ }
548
+ async _initPostHogNode() {
549
+ try {
550
+ const { PostHog } = await import("posthog-node");
551
+ const isServerlessEnvironment = [
552
+ "cloudflare-workers",
553
+ "edge",
554
+ "deno"
555
+ ].includes(this._runtimeEnvironment);
556
+ const posthogOptions = {
557
+ host: this.HOST,
558
+ disableGeoip: false,
559
+ fetch: telFetch
560
+ };
561
+ if (isServerlessEnvironment) {
562
+ posthogOptions.flushAt = 1;
563
+ posthogOptions.flushInterval = 0;
564
+ }
565
+ this._posthogNodeClient = new PostHog(
566
+ this.PROJECT_API_KEY,
567
+ posthogOptions
568
+ );
569
+ logger.debug("PostHog Node.js client initialized");
570
+ } catch (e) {
571
+ logger.warn(`Failed to initialize PostHog Node.js telemetry: ${e}`);
572
+ this._posthogNodeClient = null;
573
+ }
574
+ }
575
+ /**
576
+ * Get the detected runtime environment
577
+ */
578
+ get runtimeEnvironment() {
579
+ return this._runtimeEnvironment;
580
+ }
581
+ /**
582
+ * Get the storage capability for this environment
583
+ */
584
+ get storageCapability() {
585
+ return this._storageCapability;
586
+ }
587
+ static getInstance() {
588
+ if (!_Telemetry.instance) {
589
+ _Telemetry.instance = new _Telemetry();
590
+ }
591
+ return _Telemetry.instance;
592
+ }
593
+ /**
594
+ * Set the source identifier for telemetry events.
595
+ * This allows tracking usage from different applications.
596
+ * @param source - The source identifier (e.g., "my-app", "cli", "vs-code-extension")
597
+ */
598
+ setSource(source) {
599
+ this._source = source;
600
+ logger.debug(`Telemetry source set to: ${source}`);
601
+ }
602
+ /**
603
+ * Get the current source identifier.
604
+ */
605
+ getSource() {
606
+ return this._source;
607
+ }
608
+ /**
609
+ * Check if telemetry is enabled.
610
+ */
611
+ get isEnabled() {
612
+ return this._posthogNodeClient !== null || this._scarfClient !== null;
613
+ }
614
+ get userId() {
615
+ if (this._currUserId) {
616
+ return this._currUserId;
617
+ }
618
+ try {
619
+ switch (this._storageCapability) {
620
+ case "filesystem":
621
+ this._currUserId = this._getUserIdFromFilesystem();
622
+ break;
623
+ case "session-only":
624
+ default:
625
+ try {
626
+ this._currUserId = `session-${generateUUID()}`;
627
+ } catch (uuidError) {
628
+ this._currUserId = `session-${Date.now()}-${secureRandomString()}`;
629
+ }
630
+ break;
631
+ }
632
+ } catch (e) {
633
+ this._currUserId = this.UNKNOWN_USER_ID;
634
+ }
635
+ return this._currUserId;
636
+ }
637
+ /**
638
+ * Get or create user ID from filesystem (Node.js/Bun)
639
+ * Falls back to session ID if filesystem operations fail
640
+ */
641
+ _getUserIdFromFilesystem() {
642
+ try {
643
+ let fs, os, path;
644
+ try {
645
+ fs = __require("fs");
646
+ os = __require("os");
647
+ path = __require("path");
648
+ } catch (requireError) {
649
+ try {
650
+ const sessionId = `session-${generateUUID()}`;
651
+ return sessionId;
652
+ } catch (uuidError) {
653
+ return `session-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
654
+ }
655
+ }
656
+ if (!this._userIdPath) {
657
+ this._userIdPath = path.join(
658
+ this._getCacheHome(os, path),
659
+ "mcp_use_3",
660
+ "telemetry_user_id"
661
+ );
662
+ }
663
+ const isFirstTime = !fs.existsSync(this._userIdPath);
664
+ if (isFirstTime) {
665
+ fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
666
+ let newUserId;
667
+ try {
668
+ newUserId = generateUUID();
669
+ } catch (uuidError) {
670
+ newUserId = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
671
+ }
672
+ fs.writeFileSync(this._userIdPath, newUserId);
673
+ return newUserId;
674
+ }
675
+ const userId = fs.readFileSync(this._userIdPath, "utf-8").trim();
676
+ return userId;
677
+ } catch (e) {
678
+ try {
679
+ return `session-${generateUUID()}`;
680
+ } catch (uuidError) {
681
+ return `session-${Date.now()}-${secureRandomString()}`;
682
+ }
683
+ }
684
+ }
685
+ _getCacheHome(os, path) {
686
+ const envVar = process.env.XDG_CACHE_HOME;
687
+ if (envVar && path.isAbsolute(envVar)) {
688
+ return envVar;
689
+ }
690
+ const platform = process.platform;
691
+ const homeDir = os.homedir();
692
+ if (platform === "win32") {
693
+ const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
694
+ if (appdata) {
695
+ return appdata;
696
+ }
697
+ return path.join(homeDir, "AppData", "Local");
698
+ } else if (platform === "darwin") {
699
+ return path.join(homeDir, "Library", "Caches");
700
+ } else {
701
+ return path.join(homeDir, ".cache");
702
+ }
703
+ }
704
+ async capture(event) {
705
+ if (this._posthogLoading) {
706
+ await this._posthogLoading;
707
+ }
708
+ if (!this._posthogNodeClient && !this._scarfClient) {
709
+ return;
710
+ }
711
+ const currentUserId = this.userId;
712
+ const properties = { ...event.properties };
713
+ properties.mcp_use_version = getPackageVersion();
714
+ properties.language = "typescript";
715
+ properties.source = this._source;
716
+ properties.runtime = this._runtimeEnvironment;
717
+ if (this._posthogNodeClient) {
718
+ try {
719
+ this._posthogNodeClient.capture({
720
+ distinctId: currentUserId,
721
+ event: event.name,
722
+ properties
723
+ });
724
+ } catch (e) {
725
+ logger.debug(`Failed to track PostHog Node event ${event.name}: ${e}`);
726
+ }
727
+ }
728
+ if (this._scarfClient) {
729
+ try {
730
+ const scarfProperties = {
731
+ ...properties,
732
+ user_id: currentUserId,
733
+ event: event.name
734
+ };
735
+ await this._scarfClient.logEvent(scarfProperties);
736
+ } catch (e) {
737
+ logger.debug(`Failed to track Scarf event ${event.name}: ${e}`);
738
+ }
739
+ }
740
+ }
741
+ // ============================================================================
742
+ // Package Download Tracking (Node.js only)
743
+ // ============================================================================
744
+ /**
745
+ * Track package download event.
746
+ * This is a public wrapper that safely accesses userId.
747
+ */
748
+ async trackPackageDownload(properties) {
749
+ return this._trackPackageDownloadInternal(this.userId, properties);
750
+ }
751
+ /**
752
+ * Internal method to track package download with explicit userId.
753
+ */
754
+ async _trackPackageDownloadInternal(userId, properties) {
755
+ if (!this._scarfClient) {
756
+ return;
757
+ }
758
+ if (this._storageCapability !== "filesystem") {
759
+ return;
760
+ }
761
+ try {
762
+ const fs = __require("fs");
763
+ const path = __require("path");
764
+ const os = __require("os");
765
+ if (!this._versionDownloadPath) {
766
+ this._versionDownloadPath = path.join(
767
+ this._getCacheHome(os, path),
768
+ "mcp_use",
769
+ "download_version"
770
+ );
771
+ }
772
+ const currentVersion = getPackageVersion();
773
+ let shouldTrack = false;
774
+ let firstDownload = false;
775
+ if (!fs.existsSync(this._versionDownloadPath)) {
776
+ shouldTrack = true;
777
+ firstDownload = true;
778
+ fs.mkdirSync(path.dirname(this._versionDownloadPath), {
779
+ recursive: true
780
+ });
781
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
782
+ } else {
783
+ const savedVersion = fs.readFileSync(this._versionDownloadPath, "utf-8").trim();
784
+ if (currentVersion > savedVersion) {
785
+ shouldTrack = true;
786
+ firstDownload = false;
787
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
788
+ }
789
+ }
790
+ if (shouldTrack) {
791
+ logger.debug(
792
+ `Tracking package download event with properties: ${JSON.stringify(properties)}`
793
+ );
794
+ const eventProperties = { ...properties || {} };
795
+ eventProperties.mcp_use_version = currentVersion;
796
+ eventProperties.user_id = userId;
797
+ eventProperties.event = "package_download";
798
+ eventProperties.first_download = firstDownload;
799
+ eventProperties.language = "typescript";
800
+ eventProperties.source = this._source;
801
+ eventProperties.runtime = this._runtimeEnvironment;
802
+ await this._scarfClient.logEvent(eventProperties);
803
+ }
804
+ } catch (e) {
805
+ logger.debug(`Failed to track Scarf package_download event: ${e}`);
806
+ }
807
+ }
808
+ // ============================================================================
809
+ // Agent Events
810
+ // ============================================================================
811
+ async trackAgentExecution(data) {
812
+ if (!this.isEnabled) return;
813
+ const event = new MCPAgentExecutionEvent(data);
814
+ await this.capture(event);
815
+ }
816
+ // ============================================================================
817
+ // Server Events
818
+ // ============================================================================
819
+ /**
820
+ * Track server run event directly from an MCPServer instance.
821
+ */
822
+ async trackServerRunFromServer(server, transport) {
823
+ if (!this.isEnabled) return;
824
+ const data = createServerRunEventData(server, transport);
825
+ const event = new ServerRunEvent(data);
826
+ await this.capture(event);
827
+ }
828
+ async trackServerInitialize(data) {
829
+ if (!this.isEnabled) return;
830
+ const event = new ServerInitializeEvent(data);
831
+ await this.capture(event);
832
+ }
833
+ async trackServerToolCall(data) {
834
+ if (!this.isEnabled) return;
835
+ const event = new ServerToolCallEvent(data);
836
+ await this.capture(event);
837
+ }
838
+ async trackServerResourceCall(data) {
839
+ if (!this.isEnabled) return;
840
+ const event = new ServerResourceCallEvent(data);
841
+ await this.capture(event);
842
+ }
843
+ async trackServerPromptCall(data) {
844
+ if (!this.isEnabled) return;
845
+ const event = new ServerPromptCallEvent(data);
846
+ await this.capture(event);
847
+ }
848
+ async trackServerContext(data) {
849
+ if (!this.isEnabled) return;
850
+ const event = new ServerContextEvent(data);
851
+ await this.capture(event);
852
+ }
853
+ // ============================================================================
854
+ // Client Events
855
+ // ============================================================================
856
+ async trackMCPClientInit(data) {
857
+ if (!this.isEnabled) return;
858
+ const event = new MCPClientInitEvent(data);
859
+ await this.capture(event);
860
+ }
861
+ async trackConnectorInit(data) {
862
+ if (!this.isEnabled) return;
863
+ const event = new ConnectorInitEvent(data);
864
+ await this.capture(event);
865
+ }
866
+ async trackClientAddServer(serverName, serverConfig) {
867
+ if (!this.isEnabled) return;
868
+ const event = new ClientAddServerEvent({ serverName, serverConfig });
869
+ await this.capture(event);
870
+ }
871
+ async trackClientRemoveServer(serverName) {
872
+ if (!this.isEnabled) return;
873
+ const event = new ClientRemoveServerEvent({ serverName });
874
+ await this.capture(event);
875
+ }
876
+ // ============================================================================
877
+ // React Hook / Browser specific events (no-ops in Node.js)
878
+ // ============================================================================
879
+ async trackUseMcpConnection(data) {
880
+ }
881
+ async trackUseMcpToolCall(data) {
882
+ }
883
+ async trackUseMcpResourceRead(data) {
884
+ }
885
+ // ============================================================================
886
+ // Browser-specific Methods (no-ops in Node.js)
887
+ // ============================================================================
888
+ /**
889
+ * Identify the current user (browser only - no-op in Node.js)
890
+ */
891
+ identify(userId, properties) {
892
+ }
893
+ /**
894
+ * Reset the user identity (browser only - no-op in Node.js)
895
+ */
896
+ reset() {
897
+ this._currUserId = null;
898
+ }
899
+ // ============================================================================
900
+ // Node.js-specific Methods
901
+ // ============================================================================
902
+ /**
903
+ * Flush the telemetry queue (Node.js only)
904
+ */
905
+ flush() {
906
+ if (this._posthogNodeClient) {
907
+ try {
908
+ this._posthogNodeClient.flush();
909
+ logger.debug("PostHog client telemetry queue flushed");
910
+ } catch (e) {
911
+ logger.debug(`Failed to flush PostHog client: ${e}`);
912
+ }
913
+ }
914
+ }
915
+ /**
916
+ * Shutdown the telemetry client (Node.js only)
917
+ */
918
+ async shutdown() {
919
+ if (this._posthogNodeClient) {
920
+ try {
921
+ await this._posthogNodeClient.shutdown();
922
+ logger.debug("PostHog client shutdown successfully");
923
+ } catch (e) {
924
+ logger.debug(`Error shutting down PostHog client: ${e}`);
925
+ }
926
+ }
927
+ }
928
+ };
929
+ var Tel = Telemetry;
930
+ function setTelemetrySource(source) {
931
+ Tel.getInstance().setSource(source);
932
+ }
933
+ __name(setTelemetrySource, "setTelemetrySource");
934
+
935
+ export {
936
+ VERSION,
937
+ getPackageVersion,
938
+ extractModelInfo,
939
+ MCPAgentExecutionEvent,
940
+ createServerRunEventData,
941
+ ServerRunEvent,
942
+ ServerInitializeEvent,
943
+ ServerToolCallEvent,
944
+ ServerResourceCallEvent,
945
+ ServerPromptCallEvent,
946
+ ServerContextEvent,
947
+ MCPClientInitEvent,
948
+ ConnectorInitEvent,
949
+ ClientAddServerEvent,
950
+ ClientRemoveServerEvent,
951
+ Telemetry,
952
+ Tel,
953
+ setTelemetrySource
954
+ };