mcp-use 1.9.1-canary.1 → 1.10.0-canary.11

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 (145) hide show
  1. package/README.md +9 -6
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/{chunk-QREDNTLS.js → chunk-5S5DWSKI.js} +1 -1
  4. package/dist/{chunk-MUZ5WYE3.js → chunk-5UB2K5L6.js} +72 -14
  5. package/dist/{chunk-33U4IA4N.js → chunk-B5N3LQQU.js} +99 -5
  6. package/dist/{chunk-3R5PDYIN.js → chunk-J75I2C26.js} +39 -11
  7. package/dist/{chunk-U5BX3ISQ.js → chunk-KMTBWOVS.js} +22 -408
  8. package/dist/{chunk-D22NUQTL.js → chunk-LXYUQEEE.js} +235 -12
  9. package/dist/{chunk-ZQUCGISK.js → chunk-NNQUSDFU.js} +21 -5
  10. package/dist/chunk-PESKSVLQ.js +1129 -0
  11. package/dist/index.cjs +1190 -200
  12. package/dist/index.d.ts +6 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +63 -23
  15. package/dist/src/adapters/langchain_adapter.d.ts +1 -1
  16. package/dist/src/adapters/langchain_adapter.d.ts.map +1 -1
  17. package/dist/src/agents/index.cjs +2263 -1626
  18. package/dist/src/agents/index.js +4 -4
  19. package/dist/src/agents/mcp_agent.d.ts +5 -0
  20. package/dist/src/agents/mcp_agent.d.ts.map +1 -1
  21. package/dist/src/auth/browser-provider.d.ts +2 -2
  22. package/dist/src/auth/browser-provider.d.ts.map +1 -1
  23. package/dist/src/auth/callback.d.ts.map +1 -1
  24. package/dist/src/auth/index.cjs +39 -11
  25. package/dist/src/auth/index.js +1 -1
  26. package/dist/src/auth/types.d.ts +1 -1
  27. package/dist/src/auth/types.d.ts.map +1 -1
  28. package/dist/src/browser.cjs +2672 -1754
  29. package/dist/src/browser.d.ts +5 -1
  30. package/dist/src/browser.d.ts.map +1 -1
  31. package/dist/src/browser.js +18 -5
  32. package/dist/src/client/base.d.ts.map +1 -1
  33. package/dist/src/client/browser.d.ts +6 -0
  34. package/dist/src/client/browser.d.ts.map +1 -1
  35. package/dist/src/client/connectors/codeMode.d.ts +1 -1
  36. package/dist/src/client/connectors/codeMode.d.ts.map +1 -1
  37. package/dist/src/client/executors/base.d.ts +1 -1
  38. package/dist/src/client/executors/base.d.ts.map +1 -1
  39. package/dist/src/client/prompts.cjs +4 -1
  40. package/dist/src/client/prompts.js +3 -2
  41. package/dist/src/client.d.ts +7 -1
  42. package/dist/src/client.d.ts.map +1 -1
  43. package/dist/src/connectors/base.d.ts +56 -6
  44. package/dist/src/connectors/base.d.ts.map +1 -1
  45. package/dist/src/connectors/http.d.ts.map +1 -1
  46. package/dist/src/connectors/stdio.d.ts.map +1 -1
  47. package/dist/src/connectors/websocket.d.ts +1 -1
  48. package/dist/src/connectors/websocket.d.ts.map +1 -1
  49. package/dist/src/oauth-helper.d.ts.map +1 -1
  50. package/dist/src/react/WidgetControls.d.ts.map +1 -1
  51. package/dist/src/react/index.cjs +1357 -43
  52. package/dist/src/react/index.d.ts +4 -1
  53. package/dist/src/react/index.d.ts.map +1 -1
  54. package/dist/src/react/index.js +14 -5
  55. package/dist/src/react/types.d.ts +1 -1
  56. package/dist/src/react/types.d.ts.map +1 -1
  57. package/dist/src/react/useMcp.d.ts.map +1 -1
  58. package/dist/src/server/endpoints/mount-mcp.d.ts +4 -1
  59. package/dist/src/server/endpoints/mount-mcp.d.ts.map +1 -1
  60. package/dist/src/server/index.cjs +1923 -287
  61. package/dist/src/server/index.d.ts +3 -2
  62. package/dist/src/server/index.d.ts.map +1 -1
  63. package/dist/src/server/index.js +488 -245
  64. package/dist/src/server/mcp-server.d.ts +77 -27
  65. package/dist/src/server/mcp-server.d.ts.map +1 -1
  66. package/dist/src/server/oauth/middleware.d.ts.map +1 -1
  67. package/dist/src/server/oauth/providers/auth0.d.ts +1 -1
  68. package/dist/src/server/oauth/providers/auth0.d.ts.map +1 -1
  69. package/dist/src/server/oauth/providers/custom.d.ts +4 -2
  70. package/dist/src/server/oauth/providers/custom.d.ts.map +1 -1
  71. package/dist/src/server/oauth/providers/keycloak.d.ts +1 -1
  72. package/dist/src/server/oauth/providers/keycloak.d.ts.map +1 -1
  73. package/dist/src/server/oauth/providers/supabase.d.ts +1 -1
  74. package/dist/src/server/oauth/providers/supabase.d.ts.map +1 -1
  75. package/dist/src/server/oauth/providers/types.d.ts +9 -5
  76. package/dist/src/server/oauth/providers/types.d.ts.map +1 -1
  77. package/dist/src/server/oauth/providers.d.ts +27 -9
  78. package/dist/src/server/oauth/providers.d.ts.map +1 -1
  79. package/dist/src/server/oauth/setup.d.ts +5 -4
  80. package/dist/src/server/oauth/setup.d.ts.map +1 -1
  81. package/dist/src/server/oauth/utils.d.ts +3 -2
  82. package/dist/src/server/oauth/utils.d.ts.map +1 -1
  83. package/dist/src/server/prompts/conversion.d.ts +1 -1
  84. package/dist/src/server/prompts/conversion.d.ts.map +1 -1
  85. package/dist/src/server/prompts/index.d.ts +6 -5
  86. package/dist/src/server/prompts/index.d.ts.map +1 -1
  87. package/dist/src/server/resources/conversion.d.ts +1 -1
  88. package/dist/src/server/resources/conversion.d.ts.map +1 -1
  89. package/dist/src/server/resources/index.d.ts +44 -25
  90. package/dist/src/server/resources/index.d.ts.map +1 -1
  91. package/dist/src/server/resources/subscriptions.d.ts +1 -1
  92. package/dist/src/server/resources/subscriptions.d.ts.map +1 -1
  93. package/dist/src/server/sessions/session-manager.d.ts +11 -5
  94. package/dist/src/server/sessions/session-manager.d.ts.map +1 -1
  95. package/dist/src/server/tools/tool-execution-helpers.d.ts +31 -8
  96. package/dist/src/server/tools/tool-execution-helpers.d.ts.map +1 -1
  97. package/dist/src/server/tools/tool-registration.d.ts +21 -7
  98. package/dist/src/server/tools/tool-registration.d.ts.map +1 -1
  99. package/dist/src/server/types/common.d.ts +25 -9
  100. package/dist/src/server/types/common.d.ts.map +1 -1
  101. package/dist/src/server/types/index.d.ts +3 -3
  102. package/dist/src/server/types/index.d.ts.map +1 -1
  103. package/dist/src/server/types/prompt.d.ts +3 -2
  104. package/dist/src/server/types/prompt.d.ts.map +1 -1
  105. package/dist/src/server/types/resource.d.ts +60 -10
  106. package/dist/src/server/types/resource.d.ts.map +1 -1
  107. package/dist/src/server/types/tool-context.d.ts +116 -1
  108. package/dist/src/server/types/tool-context.d.ts.map +1 -1
  109. package/dist/src/server/types/tool.d.ts +43 -2
  110. package/dist/src/server/types/tool.d.ts.map +1 -1
  111. package/dist/src/server/types/widget.d.ts +11 -1
  112. package/dist/src/server/types/widget.d.ts.map +1 -1
  113. package/dist/src/server/utils/response-helpers.d.ts +17 -29
  114. package/dist/src/server/utils/response-helpers.d.ts.map +1 -1
  115. package/dist/src/server/widgets/index.d.ts +3 -3
  116. package/dist/src/server/widgets/index.d.ts.map +1 -1
  117. package/dist/src/server/widgets/mount-widgets-dev.d.ts.map +1 -1
  118. package/dist/src/server/widgets/ui-resource-registration.d.ts +13 -25
  119. package/dist/src/server/widgets/ui-resource-registration.d.ts.map +1 -1
  120. package/dist/src/server/widgets/widget-helpers.d.ts +11 -6
  121. package/dist/src/server/widgets/widget-helpers.d.ts.map +1 -1
  122. package/dist/src/server/widgets/widget-types.d.ts +3 -3
  123. package/dist/src/server/widgets/widget-types.d.ts.map +1 -1
  124. package/dist/src/session.d.ts +372 -2
  125. package/dist/src/session.d.ts.map +1 -1
  126. package/dist/src/task_managers/sse.d.ts +2 -2
  127. package/dist/src/task_managers/sse.d.ts.map +1 -1
  128. package/dist/src/task_managers/stdio.d.ts +2 -2
  129. package/dist/src/task_managers/stdio.d.ts.map +1 -1
  130. package/dist/src/task_managers/streamable_http.d.ts +2 -2
  131. package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
  132. package/dist/src/telemetry/events.d.ts +247 -0
  133. package/dist/src/telemetry/events.d.ts.map +1 -1
  134. package/dist/src/telemetry/index.d.ts +4 -4
  135. package/dist/src/telemetry/index.d.ts.map +1 -1
  136. package/dist/src/telemetry/telemetry.d.ts +122 -4
  137. package/dist/src/telemetry/telemetry.d.ts.map +1 -1
  138. package/dist/src/telemetry/utils.d.ts +1 -1
  139. package/dist/src/telemetry/utils.d.ts.map +1 -1
  140. package/dist/src/version.d.ts +8 -0
  141. package/dist/src/version.d.ts.map +1 -0
  142. package/dist/{tool-execution-helpers-BQJTPWPN.js → tool-execution-helpers-OOVLOJYH.js} +3 -2
  143. package/dist/tsup.config.d.ts.map +1 -1
  144. package/package.json +7 -5
  145. package/dist/chunk-MTHLLDCX.js +0 -97
@@ -31,12 +31,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  // src/react/index.ts
32
32
  var react_exports = {};
33
33
  __export(react_exports, {
34
+ BrowserTelemetry: () => Tel,
34
35
  ErrorBoundary: () => ErrorBoundary,
35
36
  Image: () => Image,
36
37
  McpUseProvider: () => McpUseProvider,
38
+ Tel: () => Tel,
39
+ Telemetry: () => Telemetry,
37
40
  ThemeProvider: () => ThemeProvider,
38
41
  WidgetControls: () => WidgetControls,
39
42
  onMcpAuthorization: () => onMcpAuthorization,
43
+ setBrowserTelemetrySource: () => setTelemetrySource,
44
+ setTelemetrySource: () => setTelemetrySource,
40
45
  useMcp: () => useMcp,
41
46
  useWidget: () => useWidget,
42
47
  useWidgetProps: () => useWidgetProps,
@@ -75,8 +80,8 @@ function sanitizeParam([k, v]) {
75
80
  __name(sanitizeParam, "sanitizeParam");
76
81
 
77
82
  // src/connectors/http.ts
78
- var import_client = require("@modelcontextprotocol/sdk/client/index.js");
79
- var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
83
+ var import_client = require("@mcp-use/modelcontextprotocol-sdk/client/index.js");
84
+ var import_streamableHttp = require("@mcp-use/modelcontextprotocol-sdk/client/streamableHttp.js");
80
85
 
81
86
  // src/logging.ts
82
87
  async function getNodeModules() {
@@ -350,7 +355,7 @@ if (isNodeJSEnvironment()) {
350
355
  var logger = Logger.get();
351
356
 
352
357
  // src/task_managers/sse.ts
353
- var import_sse = require("@modelcontextprotocol/sdk/client/sse.js");
358
+ var import_sse = require("@mcp-use/modelcontextprotocol-sdk/client/sse.js");
354
359
 
355
360
  // src/task_managers/base.ts
356
361
  var ConnectionManager = class {
@@ -513,7 +518,1006 @@ var SseConnectionManager = class extends ConnectionManager {
513
518
  };
514
519
 
515
520
  // src/connectors/base.ts
516
- var import_types = require("@modelcontextprotocol/sdk/types.js");
521
+ var import_types = require("@mcp-use/modelcontextprotocol-sdk/types.js");
522
+
523
+ // src/telemetry/events.ts
524
+ var BaseTelemetryEvent = class {
525
+ static {
526
+ __name(this, "BaseTelemetryEvent");
527
+ }
528
+ };
529
+ var MCPAgentExecutionEvent = class extends BaseTelemetryEvent {
530
+ constructor(data) {
531
+ super();
532
+ this.data = data;
533
+ }
534
+ static {
535
+ __name(this, "MCPAgentExecutionEvent");
536
+ }
537
+ get name() {
538
+ return "mcp_agent_execution";
539
+ }
540
+ get properties() {
541
+ return {
542
+ // Core execution info
543
+ execution_method: this.data.executionMethod,
544
+ query: this.data.query,
545
+ query_length: this.data.query.length,
546
+ success: this.data.success,
547
+ // Agent configuration
548
+ model_provider: this.data.modelProvider,
549
+ model_name: this.data.modelName,
550
+ server_count: this.data.serverCount,
551
+ server_identifiers: this.data.serverIdentifiers,
552
+ total_tools_available: this.data.totalToolsAvailable,
553
+ tools_available_names: this.data.toolsAvailableNames,
554
+ max_steps_configured: this.data.maxStepsConfigured,
555
+ memory_enabled: this.data.memoryEnabled,
556
+ use_server_manager: this.data.useServerManager,
557
+ // Execution parameters (always include, even if null)
558
+ max_steps_used: this.data.maxStepsUsed,
559
+ manage_connector: this.data.manageConnector,
560
+ external_history_used: this.data.externalHistoryUsed,
561
+ // Execution results (always include, even if null)
562
+ steps_taken: this.data.stepsTaken ?? null,
563
+ tools_used_count: this.data.toolsUsedCount ?? null,
564
+ tools_used_names: this.data.toolsUsedNames ?? null,
565
+ response: this.data.response ?? null,
566
+ response_length: this.data.response ? this.data.response.length : null,
567
+ execution_time_ms: this.data.executionTimeMs ?? null,
568
+ error_type: this.data.errorType ?? null,
569
+ conversation_history_length: this.data.conversationHistoryLength ?? null
570
+ };
571
+ }
572
+ };
573
+ function createServerRunEventData(server, transport) {
574
+ const toolRegistrations = Array.from(server.registrations.tools.values());
575
+ const promptRegistrations = Array.from(server.registrations.prompts.values());
576
+ const resourceRegistrations = Array.from(
577
+ server.registrations.resources.values()
578
+ );
579
+ const templateRegistrations = Array.from(
580
+ server.registrations.resourceTemplates.values()
581
+ );
582
+ const allResources = resourceRegistrations.map((r) => ({
583
+ name: r.config.name,
584
+ title: r.config.title ?? null,
585
+ description: r.config.description ?? null,
586
+ uri: r.config.uri ?? null,
587
+ mime_type: r.config.mimeType ?? null
588
+ }));
589
+ const appsSdkResources = allResources.filter(
590
+ (r) => r.mime_type === "text/html+skybridge"
591
+ );
592
+ const mcpUiResources = allResources.filter(
593
+ (r) => r.mime_type === "text/uri-list" || r.mime_type === "text/html"
594
+ );
595
+ const mcpAppsResources = allResources.filter(
596
+ (r) => r.mime_type === "text/html+mcp"
597
+ );
598
+ return {
599
+ transport,
600
+ toolsNumber: server.registeredTools.length,
601
+ resourcesNumber: server.registeredResources.length,
602
+ promptsNumber: server.registeredPrompts.length,
603
+ auth: !!server.oauthProvider,
604
+ name: server.config.name,
605
+ description: server.config.description ?? null,
606
+ baseUrl: server.serverBaseUrl ?? null,
607
+ toolNames: server.registeredTools.length > 0 ? server.registeredTools : null,
608
+ resourceNames: server.registeredResources.length > 0 ? server.registeredResources : null,
609
+ promptNames: server.registeredPrompts.length > 0 ? server.registeredPrompts : null,
610
+ tools: toolRegistrations.length > 0 ? toolRegistrations.map((r) => ({
611
+ name: r.config.name,
612
+ title: r.config.title ?? null,
613
+ description: r.config.description ?? null,
614
+ input_schema: r.config.schema ? JSON.stringify(r.config.schema) : null,
615
+ output_schema: r.config.outputSchema ? JSON.stringify(r.config.outputSchema) : null
616
+ })) : null,
617
+ resources: allResources.length > 0 ? allResources : null,
618
+ prompts: promptRegistrations.length > 0 ? promptRegistrations.map((r) => ({
619
+ name: r.config.name,
620
+ title: r.config.title ?? null,
621
+ description: r.config.description ?? null,
622
+ args: r.config.args ? JSON.stringify(r.config.args) : null
623
+ })) : null,
624
+ templates: templateRegistrations.length > 0 ? templateRegistrations.map((r) => ({
625
+ name: r.config.name,
626
+ title: r.config.title ?? null,
627
+ description: r.config.description ?? null
628
+ })) : null,
629
+ capabilities: {
630
+ logging: true,
631
+ resources: { subscribe: true, listChanged: true }
632
+ },
633
+ appsSdkResources: appsSdkResources.length > 0 ? appsSdkResources : null,
634
+ appsSdkResourcesNumber: appsSdkResources.length,
635
+ mcpUiResources: mcpUiResources.length > 0 ? mcpUiResources : null,
636
+ mcpUiResourcesNumber: mcpUiResources.length,
637
+ mcpAppsResources: mcpAppsResources.length > 0 ? mcpAppsResources : null,
638
+ mcpAppsResourcesNumber: mcpAppsResources.length
639
+ };
640
+ }
641
+ __name(createServerRunEventData, "createServerRunEventData");
642
+ var ServerRunEvent = class extends BaseTelemetryEvent {
643
+ constructor(data) {
644
+ super();
645
+ this.data = data;
646
+ }
647
+ static {
648
+ __name(this, "ServerRunEvent");
649
+ }
650
+ get name() {
651
+ return "server_run";
652
+ }
653
+ get properties() {
654
+ return {
655
+ transport: this.data.transport,
656
+ tools_number: this.data.toolsNumber,
657
+ resources_number: this.data.resourcesNumber,
658
+ prompts_number: this.data.promptsNumber,
659
+ auth: this.data.auth,
660
+ name: this.data.name,
661
+ description: this.data.description ?? null,
662
+ base_url: this.data.baseUrl ?? null,
663
+ tool_names: this.data.toolNames ?? null,
664
+ resource_names: this.data.resourceNames ?? null,
665
+ prompt_names: this.data.promptNames ?? null,
666
+ tools: this.data.tools ?? null,
667
+ resources: this.data.resources ?? null,
668
+ prompts: this.data.prompts ?? null,
669
+ templates: this.data.templates ?? null,
670
+ capabilities: this.data.capabilities ? JSON.stringify(this.data.capabilities) : null,
671
+ apps_sdk_resources: this.data.appsSdkResources ? JSON.stringify(this.data.appsSdkResources) : null,
672
+ apps_sdk_resources_number: this.data.appsSdkResourcesNumber ?? 0,
673
+ mcp_ui_resources: this.data.mcpUiResources ? JSON.stringify(this.data.mcpUiResources) : null,
674
+ mcp_ui_resources_number: this.data.mcpUiResourcesNumber ?? 0,
675
+ mcp_apps_resources: this.data.mcpAppsResources ? JSON.stringify(this.data.mcpAppsResources) : null,
676
+ mcp_apps_resources_number: this.data.mcpAppsResourcesNumber ?? 0
677
+ };
678
+ }
679
+ };
680
+ var ServerInitializeEvent = class extends BaseTelemetryEvent {
681
+ constructor(data) {
682
+ super();
683
+ this.data = data;
684
+ }
685
+ static {
686
+ __name(this, "ServerInitializeEvent");
687
+ }
688
+ get name() {
689
+ return "server_initialize_call";
690
+ }
691
+ get properties() {
692
+ return {
693
+ protocol_version: this.data.protocolVersion,
694
+ client_info: JSON.stringify(this.data.clientInfo),
695
+ client_capabilities: JSON.stringify(this.data.clientCapabilities),
696
+ session_id: this.data.sessionId ?? null
697
+ };
698
+ }
699
+ };
700
+ var ServerToolCallEvent = class extends BaseTelemetryEvent {
701
+ constructor(data) {
702
+ super();
703
+ this.data = data;
704
+ }
705
+ static {
706
+ __name(this, "ServerToolCallEvent");
707
+ }
708
+ get name() {
709
+ return "server_tool_call";
710
+ }
711
+ get properties() {
712
+ return {
713
+ tool_name: this.data.toolName,
714
+ length_input_argument: this.data.lengthInputArgument,
715
+ success: this.data.success,
716
+ error_type: this.data.errorType ?? null,
717
+ execution_time_ms: this.data.executionTimeMs ?? null
718
+ };
719
+ }
720
+ };
721
+ var ServerResourceCallEvent = class extends BaseTelemetryEvent {
722
+ constructor(data) {
723
+ super();
724
+ this.data = data;
725
+ }
726
+ static {
727
+ __name(this, "ServerResourceCallEvent");
728
+ }
729
+ get name() {
730
+ return "server_resource_call";
731
+ }
732
+ get properties() {
733
+ return {
734
+ name: this.data.name,
735
+ description: this.data.description,
736
+ contents: this.data.contents,
737
+ success: this.data.success,
738
+ error_type: this.data.errorType ?? null
739
+ };
740
+ }
741
+ };
742
+ var ServerPromptCallEvent = class extends BaseTelemetryEvent {
743
+ constructor(data) {
744
+ super();
745
+ this.data = data;
746
+ }
747
+ static {
748
+ __name(this, "ServerPromptCallEvent");
749
+ }
750
+ get name() {
751
+ return "server_prompt_call";
752
+ }
753
+ get properties() {
754
+ return {
755
+ name: this.data.name,
756
+ description: this.data.description,
757
+ success: this.data.success,
758
+ error_type: this.data.errorType ?? null
759
+ };
760
+ }
761
+ };
762
+ var ServerContextEvent = class extends BaseTelemetryEvent {
763
+ constructor(data) {
764
+ super();
765
+ this.data = data;
766
+ }
767
+ static {
768
+ __name(this, "ServerContextEvent");
769
+ }
770
+ get name() {
771
+ return `server_context_${this.data.contextType}`;
772
+ }
773
+ get properties() {
774
+ return {
775
+ context_type: this.data.contextType,
776
+ notification_type: this.data.notificationType ?? null
777
+ };
778
+ }
779
+ };
780
+ var MCPClientInitEvent = class extends BaseTelemetryEvent {
781
+ constructor(data) {
782
+ super();
783
+ this.data = data;
784
+ }
785
+ static {
786
+ __name(this, "MCPClientInitEvent");
787
+ }
788
+ get name() {
789
+ return "mcpclient_init";
790
+ }
791
+ get properties() {
792
+ return {
793
+ code_mode: this.data.codeMode,
794
+ sandbox: this.data.sandbox,
795
+ all_callbacks: this.data.allCallbacks,
796
+ verify: this.data.verify,
797
+ servers: this.data.servers,
798
+ num_servers: this.data.numServers,
799
+ is_browser: this.data.isBrowser
800
+ };
801
+ }
802
+ };
803
+ var ConnectorInitEvent = class extends BaseTelemetryEvent {
804
+ constructor(data) {
805
+ super();
806
+ this.data = data;
807
+ }
808
+ static {
809
+ __name(this, "ConnectorInitEvent");
810
+ }
811
+ get name() {
812
+ return "connector_init";
813
+ }
814
+ get properties() {
815
+ return {
816
+ connector_type: this.data.connectorType,
817
+ server_command: this.data.serverCommand ?? null,
818
+ server_args: this.data.serverArgs ?? null,
819
+ server_url: this.data.serverUrl ?? null,
820
+ public_identifier: this.data.publicIdentifier ?? null
821
+ };
822
+ }
823
+ };
824
+ var ClientAddServerEvent = class extends BaseTelemetryEvent {
825
+ constructor(data) {
826
+ super();
827
+ this.data = data;
828
+ }
829
+ static {
830
+ __name(this, "ClientAddServerEvent");
831
+ }
832
+ get name() {
833
+ return "client_add_server";
834
+ }
835
+ get properties() {
836
+ const { serverName, serverConfig } = this.data;
837
+ const url = serverConfig.url;
838
+ return {
839
+ server_name: serverName,
840
+ server_url_domain: url ? this._extractHostname(url) : null,
841
+ transport: serverConfig.transport ?? null,
842
+ has_auth: !!(serverConfig.authToken || serverConfig.authProvider)
843
+ };
844
+ }
845
+ _extractHostname(url) {
846
+ try {
847
+ return new URL(url).hostname;
848
+ } catch {
849
+ return null;
850
+ }
851
+ }
852
+ };
853
+ var ClientRemoveServerEvent = class extends BaseTelemetryEvent {
854
+ constructor(data) {
855
+ super();
856
+ this.data = data;
857
+ }
858
+ static {
859
+ __name(this, "ClientRemoveServerEvent");
860
+ }
861
+ get name() {
862
+ return "client_remove_server";
863
+ }
864
+ get properties() {
865
+ return {
866
+ server_name: this.data.serverName
867
+ };
868
+ }
869
+ };
870
+
871
+ // src/server/utils/runtime.ts
872
+ var isDeno = typeof globalThis.Deno !== "undefined";
873
+ function generateUUID() {
874
+ return globalThis.crypto.randomUUID();
875
+ }
876
+ __name(generateUUID, "generateUUID");
877
+
878
+ // src/version.ts
879
+ var VERSION = "1.10.0-canary.11";
880
+ function getPackageVersion() {
881
+ return VERSION;
882
+ }
883
+ __name(getPackageVersion, "getPackageVersion");
884
+
885
+ // src/telemetry/telemetry.ts
886
+ var USER_ID_STORAGE_KEY = "mcp_use_user_id";
887
+ function detectRuntimeEnvironment() {
888
+ try {
889
+ if (typeof globalThis.Bun !== "undefined") {
890
+ return "bun";
891
+ }
892
+ if (typeof globalThis.Deno !== "undefined") {
893
+ return "deno";
894
+ }
895
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
896
+ return "cloudflare-workers";
897
+ }
898
+ if (typeof globalThis.EdgeRuntime !== "undefined") {
899
+ return "edge";
900
+ }
901
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
902
+ return "browser";
903
+ }
904
+ if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined") {
905
+ return "node";
906
+ }
907
+ return "unknown";
908
+ } catch {
909
+ return "unknown";
910
+ }
911
+ }
912
+ __name(detectRuntimeEnvironment, "detectRuntimeEnvironment");
913
+ function getStorageCapability(env) {
914
+ switch (env) {
915
+ case "node":
916
+ case "bun":
917
+ return "filesystem";
918
+ case "browser":
919
+ try {
920
+ if (typeof localStorage !== "undefined") {
921
+ localStorage.setItem("__mcp_use_test__", "1");
922
+ localStorage.removeItem("__mcp_use_test__");
923
+ return "localStorage";
924
+ }
925
+ } catch {
926
+ }
927
+ return "session-only";
928
+ case "deno":
929
+ return "session-only";
930
+ default:
931
+ return "session-only";
932
+ }
933
+ }
934
+ __name(getStorageCapability, "getStorageCapability");
935
+ var cachedEnvironment = null;
936
+ function getRuntimeEnvironment() {
937
+ if (cachedEnvironment === null) {
938
+ cachedEnvironment = detectRuntimeEnvironment();
939
+ }
940
+ return cachedEnvironment;
941
+ }
942
+ __name(getRuntimeEnvironment, "getRuntimeEnvironment");
943
+ var ScarfEventLogger = class {
944
+ static {
945
+ __name(this, "ScarfEventLogger");
946
+ }
947
+ endpoint;
948
+ timeout;
949
+ constructor(endpoint, timeout = 3e3) {
950
+ this.endpoint = endpoint;
951
+ this.timeout = timeout;
952
+ }
953
+ async logEvent(properties) {
954
+ try {
955
+ const controller = new AbortController();
956
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
957
+ const response = await fetch(this.endpoint, {
958
+ method: "POST",
959
+ headers: {
960
+ "Content-Type": "application/json"
961
+ },
962
+ body: JSON.stringify(properties),
963
+ signal: controller.signal
964
+ });
965
+ clearTimeout(timeoutId);
966
+ if (!response.ok) {
967
+ throw new Error(`HTTP error! status: ${response.status}`);
968
+ }
969
+ } catch (error) {
970
+ logger.debug(`Failed to send Scarf event: ${error}`);
971
+ }
972
+ }
973
+ };
974
+ var Telemetry = class _Telemetry {
975
+ static {
976
+ __name(this, "Telemetry");
977
+ }
978
+ static instance = null;
979
+ PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
980
+ HOST = "https://eu.i.posthog.com";
981
+ SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
982
+ UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
983
+ _currUserId = null;
984
+ _posthogNodeClient = null;
985
+ _posthogBrowserClient = null;
986
+ _posthogLoading = null;
987
+ _scarfClient = null;
988
+ _runtimeEnvironment;
989
+ _storageCapability;
990
+ _source;
991
+ // Node.js specific paths (lazily computed)
992
+ _userIdPath = null;
993
+ _versionDownloadPath = null;
994
+ constructor() {
995
+ this._runtimeEnvironment = getRuntimeEnvironment();
996
+ this._storageCapability = getStorageCapability(this._runtimeEnvironment);
997
+ this._source = typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE || this._runtimeEnvironment;
998
+ const telemetryDisabled = this._checkTelemetryDisabled();
999
+ const canSupportTelemetry = this._runtimeEnvironment !== "unknown";
1000
+ if (telemetryDisabled) {
1001
+ this._posthogNodeClient = null;
1002
+ this._posthogBrowserClient = null;
1003
+ this._scarfClient = null;
1004
+ logger.debug("Telemetry disabled via environment/localStorage");
1005
+ } else if (!canSupportTelemetry) {
1006
+ this._posthogNodeClient = null;
1007
+ this._posthogBrowserClient = null;
1008
+ this._scarfClient = null;
1009
+ logger.debug(
1010
+ `Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`
1011
+ );
1012
+ } else {
1013
+ logger.info(
1014
+ "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
1015
+ );
1016
+ this._posthogLoading = this._initPostHog();
1017
+ try {
1018
+ this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
1019
+ } catch (e) {
1020
+ logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
1021
+ this._scarfClient = null;
1022
+ }
1023
+ }
1024
+ }
1025
+ _checkTelemetryDisabled() {
1026
+ if (typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false") {
1027
+ return true;
1028
+ }
1029
+ if (typeof localStorage !== "undefined" && localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY") === "false") {
1030
+ return true;
1031
+ }
1032
+ return false;
1033
+ }
1034
+ async _initPostHog() {
1035
+ const isBrowser = this._runtimeEnvironment === "browser";
1036
+ if (isBrowser) {
1037
+ await this._initPostHogBrowser();
1038
+ } else {
1039
+ await this._initPostHogNode();
1040
+ }
1041
+ }
1042
+ async _initPostHogBrowser() {
1043
+ try {
1044
+ const posthogModule = await import("posthog-js");
1045
+ const posthog = posthogModule.default || posthogModule.posthog;
1046
+ if (!posthog || typeof posthog.init !== "function") {
1047
+ throw new Error("posthog-js module did not export expected interface");
1048
+ }
1049
+ posthog.init(this.PROJECT_API_KEY, {
1050
+ api_host: this.HOST,
1051
+ persistence: "localStorage",
1052
+ autocapture: false,
1053
+ // We only want explicit captures
1054
+ capture_pageview: false,
1055
+ // We don't want automatic pageview tracking
1056
+ disable_session_recording: true,
1057
+ // No session recording
1058
+ loaded: /* @__PURE__ */ __name(() => {
1059
+ logger.debug("PostHog browser client initialized");
1060
+ }, "loaded")
1061
+ });
1062
+ this._posthogBrowserClient = posthog;
1063
+ } catch (e) {
1064
+ logger.warn(`Failed to initialize PostHog browser telemetry: ${e}`);
1065
+ this._posthogBrowserClient = null;
1066
+ }
1067
+ }
1068
+ async _initPostHogNode() {
1069
+ try {
1070
+ const { PostHog } = await import("posthog-node");
1071
+ const isServerlessEnvironment = [
1072
+ "cloudflare-workers",
1073
+ "edge",
1074
+ "deno"
1075
+ ].includes(this._runtimeEnvironment);
1076
+ const posthogOptions = {
1077
+ host: this.HOST,
1078
+ disableGeoip: false
1079
+ };
1080
+ if (isServerlessEnvironment) {
1081
+ posthogOptions.flushAt = 1;
1082
+ posthogOptions.flushInterval = 0;
1083
+ }
1084
+ this._posthogNodeClient = new PostHog(
1085
+ this.PROJECT_API_KEY,
1086
+ posthogOptions
1087
+ );
1088
+ logger.debug("PostHog Node.js client initialized");
1089
+ } catch (e) {
1090
+ logger.warn(`Failed to initialize PostHog Node.js telemetry: ${e}`);
1091
+ this._posthogNodeClient = null;
1092
+ }
1093
+ }
1094
+ /**
1095
+ * Get the detected runtime environment
1096
+ */
1097
+ get runtimeEnvironment() {
1098
+ return this._runtimeEnvironment;
1099
+ }
1100
+ /**
1101
+ * Get the storage capability for this environment
1102
+ */
1103
+ get storageCapability() {
1104
+ return this._storageCapability;
1105
+ }
1106
+ static getInstance() {
1107
+ if (!_Telemetry.instance) {
1108
+ _Telemetry.instance = new _Telemetry();
1109
+ }
1110
+ return _Telemetry.instance;
1111
+ }
1112
+ /**
1113
+ * Set the source identifier for telemetry events.
1114
+ * This allows tracking usage from different applications.
1115
+ * @param source - The source identifier (e.g., "my-app", "cli", "vs-code-extension")
1116
+ */
1117
+ setSource(source) {
1118
+ this._source = source;
1119
+ logger.debug(`Telemetry source set to: ${source}`);
1120
+ }
1121
+ /**
1122
+ * Get the current source identifier.
1123
+ */
1124
+ getSource() {
1125
+ return this._source;
1126
+ }
1127
+ /**
1128
+ * Check if telemetry is enabled.
1129
+ */
1130
+ get isEnabled() {
1131
+ return this._posthogNodeClient !== null || this._posthogBrowserClient !== null || this._scarfClient !== null;
1132
+ }
1133
+ get userId() {
1134
+ if (this._currUserId) {
1135
+ return this._currUserId;
1136
+ }
1137
+ try {
1138
+ switch (this._storageCapability) {
1139
+ case "filesystem":
1140
+ this._currUserId = this._getUserIdFromFilesystem();
1141
+ break;
1142
+ case "localStorage":
1143
+ this._currUserId = this._getUserIdFromLocalStorage();
1144
+ break;
1145
+ case "session-only":
1146
+ default:
1147
+ this._currUserId = `session-${generateUUID()}`;
1148
+ logger.debug(
1149
+ `Using session-based user ID (${this._runtimeEnvironment} environment)`
1150
+ );
1151
+ break;
1152
+ }
1153
+ if (this._storageCapability === "filesystem" && this._currUserId) {
1154
+ this._trackPackageDownloadInternal(this._currUserId, {
1155
+ triggered_by: "user_id_property"
1156
+ }).catch((e) => logger.debug(`Failed to track package download: ${e}`));
1157
+ }
1158
+ } catch (e) {
1159
+ logger.debug(`Failed to get/create user ID: ${e}`);
1160
+ this._currUserId = this.UNKNOWN_USER_ID;
1161
+ }
1162
+ return this._currUserId;
1163
+ }
1164
+ /**
1165
+ * Get or create user ID from filesystem (Node.js/Bun)
1166
+ */
1167
+ _getUserIdFromFilesystem() {
1168
+ const fs = require("fs");
1169
+ const os = require("os");
1170
+ const path = require("path");
1171
+ if (!this._userIdPath) {
1172
+ this._userIdPath = path.join(
1173
+ this._getCacheHome(os, path),
1174
+ "mcp_use_3",
1175
+ "telemetry_user_id"
1176
+ );
1177
+ }
1178
+ const isFirstTime = !fs.existsSync(this._userIdPath);
1179
+ if (isFirstTime) {
1180
+ logger.debug(`Creating user ID path: ${this._userIdPath}`);
1181
+ fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
1182
+ const newUserId = generateUUID();
1183
+ fs.writeFileSync(this._userIdPath, newUserId);
1184
+ logger.debug(`User ID path created: ${this._userIdPath}`);
1185
+ return newUserId;
1186
+ }
1187
+ return fs.readFileSync(this._userIdPath, "utf-8").trim();
1188
+ }
1189
+ /**
1190
+ * Get or create user ID from localStorage (Browser)
1191
+ */
1192
+ _getUserIdFromLocalStorage() {
1193
+ try {
1194
+ let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
1195
+ if (!userId) {
1196
+ userId = generateUUID();
1197
+ localStorage.setItem(USER_ID_STORAGE_KEY, userId);
1198
+ logger.debug(`Created new browser user ID`);
1199
+ }
1200
+ return userId;
1201
+ } catch (e) {
1202
+ logger.debug(`localStorage access failed: ${e}`);
1203
+ return `session-${generateUUID()}`;
1204
+ }
1205
+ }
1206
+ _getCacheHome(os, path) {
1207
+ const envVar = process.env.XDG_CACHE_HOME;
1208
+ if (envVar && path.isAbsolute(envVar)) {
1209
+ return envVar;
1210
+ }
1211
+ const platform = process.platform;
1212
+ const homeDir = os.homedir();
1213
+ if (platform === "win32") {
1214
+ const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
1215
+ if (appdata) {
1216
+ return appdata;
1217
+ }
1218
+ return path.join(homeDir, "AppData", "Local");
1219
+ } else if (platform === "darwin") {
1220
+ return path.join(homeDir, "Library", "Caches");
1221
+ } else {
1222
+ return path.join(homeDir, ".cache");
1223
+ }
1224
+ }
1225
+ async capture(event) {
1226
+ if (this._posthogLoading) {
1227
+ await this._posthogLoading;
1228
+ }
1229
+ if (!this._posthogNodeClient && !this._posthogBrowserClient && !this._scarfClient) {
1230
+ return;
1231
+ }
1232
+ const properties = { ...event.properties };
1233
+ properties.mcp_use_version = getPackageVersion();
1234
+ properties.language = "typescript";
1235
+ properties.source = this._source;
1236
+ properties.runtime = this._runtimeEnvironment;
1237
+ if (this._posthogNodeClient) {
1238
+ try {
1239
+ logger.debug(`CAPTURE: PostHog Node Event ${event.name}`);
1240
+ this._posthogNodeClient.capture({
1241
+ distinctId: this.userId,
1242
+ event: event.name,
1243
+ properties
1244
+ });
1245
+ } catch (e) {
1246
+ logger.debug(`Failed to track PostHog Node event ${event.name}: ${e}`);
1247
+ }
1248
+ }
1249
+ if (this._posthogBrowserClient) {
1250
+ try {
1251
+ logger.debug(`CAPTURE: PostHog Browser Event ${event.name}`);
1252
+ this._posthogBrowserClient.capture(event.name, {
1253
+ ...properties,
1254
+ distinct_id: this.userId
1255
+ });
1256
+ } catch (e) {
1257
+ logger.debug(
1258
+ `Failed to track PostHog Browser event ${event.name}: ${e}`
1259
+ );
1260
+ }
1261
+ }
1262
+ if (this._scarfClient) {
1263
+ try {
1264
+ const scarfProperties = {
1265
+ ...properties,
1266
+ user_id: this.userId,
1267
+ event: event.name
1268
+ };
1269
+ await this._scarfClient.logEvent(scarfProperties);
1270
+ } catch (e) {
1271
+ logger.debug(`Failed to track Scarf event ${event.name}: ${e}`);
1272
+ }
1273
+ }
1274
+ }
1275
+ // ============================================================================
1276
+ // Package Download Tracking (Node.js only)
1277
+ // ============================================================================
1278
+ /**
1279
+ * Track package download event.
1280
+ * This is a public wrapper that safely accesses userId.
1281
+ */
1282
+ async trackPackageDownload(properties) {
1283
+ return this._trackPackageDownloadInternal(this.userId, properties);
1284
+ }
1285
+ /**
1286
+ * Internal method to track package download with explicit userId.
1287
+ */
1288
+ async _trackPackageDownloadInternal(userId, properties) {
1289
+ if (!this._scarfClient) {
1290
+ return;
1291
+ }
1292
+ if (this._storageCapability !== "filesystem") {
1293
+ return;
1294
+ }
1295
+ try {
1296
+ const fs = require("fs");
1297
+ const path = require("path");
1298
+ const os = require("os");
1299
+ if (!this._versionDownloadPath) {
1300
+ this._versionDownloadPath = path.join(
1301
+ this._getCacheHome(os, path),
1302
+ "mcp_use",
1303
+ "download_version"
1304
+ );
1305
+ }
1306
+ const currentVersion = getPackageVersion();
1307
+ let shouldTrack = false;
1308
+ let firstDownload = false;
1309
+ if (!fs.existsSync(this._versionDownloadPath)) {
1310
+ shouldTrack = true;
1311
+ firstDownload = true;
1312
+ fs.mkdirSync(path.dirname(this._versionDownloadPath), {
1313
+ recursive: true
1314
+ });
1315
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
1316
+ } else {
1317
+ const savedVersion = fs.readFileSync(this._versionDownloadPath, "utf-8").trim();
1318
+ if (currentVersion > savedVersion) {
1319
+ shouldTrack = true;
1320
+ firstDownload = false;
1321
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
1322
+ }
1323
+ }
1324
+ if (shouldTrack) {
1325
+ logger.debug(
1326
+ `Tracking package download event with properties: ${JSON.stringify(properties)}`
1327
+ );
1328
+ const eventProperties = { ...properties || {} };
1329
+ eventProperties.mcp_use_version = currentVersion;
1330
+ eventProperties.user_id = userId;
1331
+ eventProperties.event = "package_download";
1332
+ eventProperties.first_download = firstDownload;
1333
+ eventProperties.language = "typescript";
1334
+ eventProperties.source = this._source;
1335
+ eventProperties.runtime = this._runtimeEnvironment;
1336
+ await this._scarfClient.logEvent(eventProperties);
1337
+ }
1338
+ } catch (e) {
1339
+ logger.debug(`Failed to track Scarf package_download event: ${e}`);
1340
+ }
1341
+ }
1342
+ // ============================================================================
1343
+ // Agent Events
1344
+ // ============================================================================
1345
+ async trackAgentExecution(data) {
1346
+ if (!this.isEnabled) return;
1347
+ const event = new MCPAgentExecutionEvent(data);
1348
+ await this.capture(event);
1349
+ }
1350
+ // ============================================================================
1351
+ // Server Events
1352
+ // ============================================================================
1353
+ /**
1354
+ * Track server run event directly from an MCPServer instance.
1355
+ */
1356
+ async trackServerRunFromServer(server, transport) {
1357
+ if (!this.isEnabled) return;
1358
+ const data = createServerRunEventData(server, transport);
1359
+ const event = new ServerRunEvent(data);
1360
+ await this.capture(event);
1361
+ }
1362
+ async trackServerInitialize(data) {
1363
+ if (!this.isEnabled) return;
1364
+ const event = new ServerInitializeEvent(data);
1365
+ await this.capture(event);
1366
+ }
1367
+ async trackServerToolCall(data) {
1368
+ if (!this.isEnabled) return;
1369
+ const event = new ServerToolCallEvent(data);
1370
+ await this.capture(event);
1371
+ }
1372
+ async trackServerResourceCall(data) {
1373
+ if (!this.isEnabled) return;
1374
+ const event = new ServerResourceCallEvent(data);
1375
+ await this.capture(event);
1376
+ }
1377
+ async trackServerPromptCall(data) {
1378
+ if (!this.isEnabled) return;
1379
+ const event = new ServerPromptCallEvent(data);
1380
+ await this.capture(event);
1381
+ }
1382
+ async trackServerContext(data) {
1383
+ if (!this.isEnabled) return;
1384
+ const event = new ServerContextEvent(data);
1385
+ await this.capture(event);
1386
+ }
1387
+ // ============================================================================
1388
+ // Client Events
1389
+ // ============================================================================
1390
+ async trackMCPClientInit(data) {
1391
+ if (!this.isEnabled) return;
1392
+ const event = new MCPClientInitEvent(data);
1393
+ await this.capture(event);
1394
+ }
1395
+ async trackConnectorInit(data) {
1396
+ if (!this.isEnabled) return;
1397
+ const event = new ConnectorInitEvent(data);
1398
+ await this.capture(event);
1399
+ }
1400
+ async trackClientAddServer(serverName, serverConfig) {
1401
+ if (!this.isEnabled) return;
1402
+ const event = new ClientAddServerEvent({ serverName, serverConfig });
1403
+ await this.capture(event);
1404
+ }
1405
+ async trackClientRemoveServer(serverName) {
1406
+ if (!this.isEnabled) return;
1407
+ const event = new ClientRemoveServerEvent({ serverName });
1408
+ await this.capture(event);
1409
+ }
1410
+ // ============================================================================
1411
+ // React Hook / Browser specific events
1412
+ // ============================================================================
1413
+ async trackUseMcpConnection(data) {
1414
+ if (!this.isEnabled) return;
1415
+ await this.capture({
1416
+ name: "usemcp_connection",
1417
+ properties: {
1418
+ url_domain: new URL(data.url).hostname,
1419
+ // Only domain for privacy
1420
+ transport_type: data.transportType,
1421
+ success: data.success,
1422
+ error_type: data.errorType ?? null,
1423
+ connection_time_ms: data.connectionTimeMs ?? null,
1424
+ has_oauth: data.hasOAuth,
1425
+ has_sampling: data.hasSampling,
1426
+ has_elicitation: data.hasElicitation
1427
+ }
1428
+ });
1429
+ }
1430
+ async trackUseMcpToolCall(data) {
1431
+ if (!this.isEnabled) return;
1432
+ await this.capture({
1433
+ name: "usemcp_tool_call",
1434
+ properties: {
1435
+ tool_name: data.toolName,
1436
+ success: data.success,
1437
+ error_type: data.errorType ?? null,
1438
+ execution_time_ms: data.executionTimeMs ?? null
1439
+ }
1440
+ });
1441
+ }
1442
+ async trackUseMcpResourceRead(data) {
1443
+ if (!this.isEnabled) return;
1444
+ await this.capture({
1445
+ name: "usemcp_resource_read",
1446
+ properties: {
1447
+ resource_uri_scheme: data.resourceUri.split(":")[0],
1448
+ // Only scheme for privacy
1449
+ success: data.success,
1450
+ error_type: data.errorType ?? null
1451
+ }
1452
+ });
1453
+ }
1454
+ // ============================================================================
1455
+ // Browser-specific Methods
1456
+ // ============================================================================
1457
+ /**
1458
+ * Identify the current user (useful for linking sessions)
1459
+ * Browser only - no-op in Node.js
1460
+ */
1461
+ identify(userId, properties) {
1462
+ if (this._posthogBrowserClient) {
1463
+ try {
1464
+ this._posthogBrowserClient.identify(userId, properties);
1465
+ } catch (e) {
1466
+ logger.debug(`Failed to identify user: ${e}`);
1467
+ }
1468
+ }
1469
+ }
1470
+ /**
1471
+ * Reset the user identity (useful for logout)
1472
+ * Browser only - no-op in Node.js
1473
+ */
1474
+ reset() {
1475
+ if (this._posthogBrowserClient) {
1476
+ try {
1477
+ this._posthogBrowserClient.reset();
1478
+ } catch (e) {
1479
+ logger.debug(`Failed to reset user: ${e}`);
1480
+ }
1481
+ }
1482
+ this._currUserId = null;
1483
+ }
1484
+ // ============================================================================
1485
+ // Node.js-specific Methods
1486
+ // ============================================================================
1487
+ /**
1488
+ * Flush the telemetry queue (Node.js only)
1489
+ */
1490
+ flush() {
1491
+ if (this._posthogNodeClient) {
1492
+ try {
1493
+ this._posthogNodeClient.flush();
1494
+ logger.debug("PostHog client telemetry queue flushed");
1495
+ } catch (e) {
1496
+ logger.debug(`Failed to flush PostHog client: ${e}`);
1497
+ }
1498
+ }
1499
+ }
1500
+ /**
1501
+ * Shutdown the telemetry client (Node.js only)
1502
+ */
1503
+ shutdown() {
1504
+ if (this._posthogNodeClient) {
1505
+ try {
1506
+ this._posthogNodeClient.shutdown();
1507
+ logger.debug("PostHog client shutdown successfully");
1508
+ } catch (e) {
1509
+ logger.debug(`Error shutting down PostHog client: ${e}`);
1510
+ }
1511
+ }
1512
+ }
1513
+ };
1514
+ var Tel = Telemetry;
1515
+ function setTelemetrySource(source) {
1516
+ Tel.getInstance().setSource(source);
1517
+ }
1518
+ __name(setTelemetrySource, "setTelemetrySource");
1519
+
1520
+ // src/connectors/base.ts
517
1521
  var BaseConnector = class {
518
1522
  static {
519
1523
  __name(this, "BaseConnector");
@@ -533,6 +1537,17 @@ var BaseConnector = class {
533
1537
  this.rootsCache = [...opts.roots];
534
1538
  }
535
1539
  }
1540
+ /**
1541
+ * Track connector initialization event
1542
+ * Should be called by subclasses after successful connection
1543
+ */
1544
+ trackConnectorInit(data) {
1545
+ const connectorType = this.constructor.name;
1546
+ Telemetry.getInstance().trackConnectorInit({
1547
+ connectorType,
1548
+ ...data
1549
+ }).catch((e) => logger.debug(`Failed to track connector init: ${e}`));
1550
+ }
536
1551
  /**
537
1552
  * Register a handler for server notifications
538
1553
  *
@@ -741,7 +1756,7 @@ var BaseConnector = class {
741
1756
  }
742
1757
  logger.debug("Caching server capabilities & tools");
743
1758
  const capabilities = this.client.getServerCapabilities();
744
- this.capabilitiesCache = capabilities;
1759
+ this.capabilitiesCache = capabilities || null;
745
1760
  const serverInfo = this.client.getServerVersion();
746
1761
  this.serverInfoCache = serverInfo || null;
747
1762
  const listToolsRes = await this.client.listTools(
@@ -763,7 +1778,7 @@ var BaseConnector = class {
763
1778
  }
764
1779
  /** Expose cached server capabilities. */
765
1780
  get serverCapabilities() {
766
- return this.capabilitiesCache;
1781
+ return this.capabilitiesCache || {};
767
1782
  }
768
1783
  /** Expose cached server info. */
769
1784
  get serverInfo() {
@@ -830,7 +1845,8 @@ var BaseConnector = class {
830
1845
  } while (cursor);
831
1846
  return { resources: allResources };
832
1847
  } catch (err) {
833
- if (err.code === -32601) {
1848
+ const error = err;
1849
+ if (error.code === -32601) {
834
1850
  logger.debug("Server advertised resources but method not found");
835
1851
  return { resources: [] };
836
1852
  }
@@ -897,7 +1913,8 @@ var BaseConnector = class {
897
1913
  logger.debug("Listing prompts");
898
1914
  return await this.client.listPrompts();
899
1915
  } catch (err) {
900
- if (err.code === -32601) {
1916
+ const error = err;
1917
+ if (error.code === -32601) {
901
1918
  logger.debug("Server advertised prompts but method not found");
902
1919
  return { prompts: [] };
903
1920
  }
@@ -1008,15 +2025,16 @@ var HttpConnector = class extends BaseConnector {
1008
2025
  let fallbackReason = "Unknown error";
1009
2026
  let is401Error = false;
1010
2027
  if (err instanceof import_streamableHttp.StreamableHTTPError) {
1011
- is401Error = err.code === 401;
1012
- if (err.code === 400 && err.message.includes("Missing session ID")) {
2028
+ const streamableErr = err;
2029
+ is401Error = streamableErr.code === 401;
2030
+ if (streamableErr.code === 400 && streamableErr.message.includes("Missing session ID")) {
1013
2031
  fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
1014
2032
  logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
1015
- } else if (err.code === 404 || err.code === 405) {
1016
- fallbackReason = `Server returned ${err.code} - server likely doesn't support streamable HTTP`;
2033
+ } else if (streamableErr.code === 404 || streamableErr.code === 405) {
2034
+ fallbackReason = `Server returned ${streamableErr.code} - server likely doesn't support streamable HTTP`;
1017
2035
  logger.debug(fallbackReason);
1018
2036
  } else {
1019
- fallbackReason = `Server returned ${err.code}: ${err.message}`;
2037
+ fallbackReason = `Server returned ${streamableErr.code}: ${streamableErr.message}`;
1020
2038
  logger.debug(fallbackReason);
1021
2039
  }
1022
2040
  } else if (err instanceof Error) {
@@ -1156,6 +2174,10 @@ var HttpConnector = class extends BaseConnector {
1156
2174
  logger.debug(
1157
2175
  `Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`
1158
2176
  );
2177
+ this.trackConnectorInit({
2178
+ serverUrl: this.baseUrl,
2179
+ publicIdentifier: `${this.baseUrl} (streamable-http)`
2180
+ });
1159
2181
  } catch (err) {
1160
2182
  await this.cleanupResources();
1161
2183
  throw err;
@@ -1203,6 +2225,10 @@ var HttpConnector = class extends BaseConnector {
1203
2225
  logger.debug(
1204
2226
  `Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`
1205
2227
  );
2228
+ this.trackConnectorInit({
2229
+ serverUrl: this.baseUrl,
2230
+ publicIdentifier: `${this.baseUrl} (sse)`
2231
+ });
1206
2232
  } catch (err) {
1207
2233
  await this.cleanupResources();
1208
2234
  throw err;
@@ -1223,13 +2249,6 @@ var HttpConnector = class extends BaseConnector {
1223
2249
  }
1224
2250
  };
1225
2251
 
1226
- // src/server/utils/runtime.ts
1227
- var isDeno = typeof globalThis.Deno !== "undefined";
1228
- function generateUUID() {
1229
- return globalThis.crypto.randomUUID();
1230
- }
1231
- __name(generateUUID, "generateUUID");
1232
-
1233
2252
  // src/task_managers/websocket.ts
1234
2253
  var import_ws = __toESM(require("ws"), 1);
1235
2254
  var WebSocketConnectionManager = class extends ConnectionManager {
@@ -1574,6 +2593,190 @@ var MCPSession = class {
1574
2593
  getRoots() {
1575
2594
  return this.connector.getRoots();
1576
2595
  }
2596
+ /**
2597
+ * Get the cached list of tools from the server.
2598
+ *
2599
+ * @returns Array of available tools
2600
+ *
2601
+ * @example
2602
+ * ```typescript
2603
+ * const tools = session.tools;
2604
+ * console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
2605
+ * ```
2606
+ */
2607
+ get tools() {
2608
+ return this.connector.tools;
2609
+ }
2610
+ /**
2611
+ * Get the server capabilities advertised during initialization.
2612
+ *
2613
+ * @returns Server capabilities object
2614
+ */
2615
+ get serverCapabilities() {
2616
+ return this.connector.serverCapabilities;
2617
+ }
2618
+ /**
2619
+ * Get the server information (name and version).
2620
+ *
2621
+ * @returns Server info object or null if not available
2622
+ */
2623
+ get serverInfo() {
2624
+ return this.connector.serverInfo;
2625
+ }
2626
+ /**
2627
+ * Call a tool on the server.
2628
+ *
2629
+ * @param name - Name of the tool to call
2630
+ * @param args - Arguments to pass to the tool
2631
+ * @param options - Optional request options (timeout, progress handlers, etc.)
2632
+ * @returns Result from the tool execution
2633
+ *
2634
+ * @example
2635
+ * ```typescript
2636
+ * const result = await session.callTool("add", { a: 5, b: 3 });
2637
+ * console.log(`Result: ${result.content[0].text}`);
2638
+ * ```
2639
+ */
2640
+ async callTool(name, args, options) {
2641
+ return this.connector.callTool(name, args, options);
2642
+ }
2643
+ /**
2644
+ * List resources from the server with optional pagination.
2645
+ *
2646
+ * @param cursor - Optional cursor for pagination
2647
+ * @param options - Request options
2648
+ * @returns Resource list with optional nextCursor for pagination
2649
+ *
2650
+ * @example
2651
+ * ```typescript
2652
+ * const result = await session.listResources();
2653
+ * console.log(`Found ${result.resources.length} resources`);
2654
+ * ```
2655
+ */
2656
+ async listResources(cursor, options) {
2657
+ return this.connector.listResources(cursor, options);
2658
+ }
2659
+ /**
2660
+ * List all resources from the server, automatically handling pagination.
2661
+ *
2662
+ * @param options - Request options
2663
+ * @returns Complete list of all resources
2664
+ *
2665
+ * @example
2666
+ * ```typescript
2667
+ * const result = await session.listAllResources();
2668
+ * console.log(`Total resources: ${result.resources.length}`);
2669
+ * ```
2670
+ */
2671
+ async listAllResources(options) {
2672
+ return this.connector.listAllResources(options);
2673
+ }
2674
+ /**
2675
+ * List resource templates from the server.
2676
+ *
2677
+ * @param options - Request options
2678
+ * @returns List of available resource templates
2679
+ *
2680
+ * @example
2681
+ * ```typescript
2682
+ * const result = await session.listResourceTemplates();
2683
+ * console.log(`Available templates: ${result.resourceTemplates.length}`);
2684
+ * ```
2685
+ */
2686
+ async listResourceTemplates(options) {
2687
+ return this.connector.listResourceTemplates(options);
2688
+ }
2689
+ /**
2690
+ * Read a resource by URI.
2691
+ *
2692
+ * @param uri - URI of the resource to read
2693
+ * @param options - Request options
2694
+ * @returns Resource content
2695
+ *
2696
+ * @example
2697
+ * ```typescript
2698
+ * const resource = await session.readResource("file:///path/to/file.txt");
2699
+ * console.log(resource.contents);
2700
+ * ```
2701
+ */
2702
+ async readResource(uri, options) {
2703
+ return this.connector.readResource(uri, options);
2704
+ }
2705
+ /**
2706
+ * Subscribe to resource updates.
2707
+ *
2708
+ * @param uri - URI of the resource to subscribe to
2709
+ * @param options - Request options
2710
+ *
2711
+ * @example
2712
+ * ```typescript
2713
+ * await session.subscribeToResource("file:///path/to/file.txt");
2714
+ * // Now you'll receive notifications when this resource changes
2715
+ * ```
2716
+ */
2717
+ async subscribeToResource(uri, options) {
2718
+ return this.connector.subscribeToResource(uri, options);
2719
+ }
2720
+ /**
2721
+ * Unsubscribe from resource updates.
2722
+ *
2723
+ * @param uri - URI of the resource to unsubscribe from
2724
+ * @param options - Request options
2725
+ *
2726
+ * @example
2727
+ * ```typescript
2728
+ * await session.unsubscribeFromResource("file:///path/to/file.txt");
2729
+ * ```
2730
+ */
2731
+ async unsubscribeFromResource(uri, options) {
2732
+ return this.connector.unsubscribeFromResource(uri, options);
2733
+ }
2734
+ /**
2735
+ * List available prompts from the server.
2736
+ *
2737
+ * @returns List of available prompts
2738
+ *
2739
+ * @example
2740
+ * ```typescript
2741
+ * const result = await session.listPrompts();
2742
+ * console.log(`Available prompts: ${result.prompts.length}`);
2743
+ * ```
2744
+ */
2745
+ async listPrompts() {
2746
+ return this.connector.listPrompts();
2747
+ }
2748
+ /**
2749
+ * Get a specific prompt with arguments.
2750
+ *
2751
+ * @param name - Name of the prompt to get
2752
+ * @param args - Arguments for the prompt
2753
+ * @returns Prompt result
2754
+ *
2755
+ * @example
2756
+ * ```typescript
2757
+ * const prompt = await session.getPrompt("greeting", { name: "Alice" });
2758
+ * console.log(prompt.messages);
2759
+ * ```
2760
+ */
2761
+ async getPrompt(name, args) {
2762
+ return this.connector.getPrompt(name, args);
2763
+ }
2764
+ /**
2765
+ * Send a raw request through the client.
2766
+ *
2767
+ * @param method - MCP method name
2768
+ * @param params - Request parameters
2769
+ * @param options - Request options
2770
+ * @returns Response from the server
2771
+ *
2772
+ * @example
2773
+ * ```typescript
2774
+ * const result = await session.request("custom/method", { key: "value" });
2775
+ * ```
2776
+ */
2777
+ async request(method, params = null, options) {
2778
+ return this.connector.request(method, params, options);
2779
+ }
1577
2780
  };
1578
2781
 
1579
2782
  // src/client/base.ts
@@ -1595,11 +2798,13 @@ var BaseMCPClient = class {
1595
2798
  addServer(name, serverConfig) {
1596
2799
  this.config.mcpServers = this.config.mcpServers || {};
1597
2800
  this.config.mcpServers[name] = serverConfig;
2801
+ Tel.getInstance().trackClientAddServer(name, serverConfig);
1598
2802
  }
1599
2803
  removeServer(name) {
1600
2804
  if (this.config.mcpServers?.[name]) {
1601
2805
  delete this.config.mcpServers[name];
1602
2806
  this.activeSessions = this.activeSessions.filter((n) => n !== name);
2807
+ Tel.getInstance().trackClientRemoveServer(name);
1603
2808
  }
1604
2809
  }
1605
2810
  getServerNames() {
@@ -1698,8 +2903,34 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
1698
2903
  static {
1699
2904
  __name(this, "BrowserMCPClient");
1700
2905
  }
2906
+ /**
2907
+ * Get the mcp-use package version.
2908
+ * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
2909
+ */
2910
+ static getPackageVersion() {
2911
+ return getPackageVersion();
2912
+ }
1701
2913
  constructor(config) {
1702
2914
  super(config);
2915
+ this._trackClientInit();
2916
+ }
2917
+ _trackClientInit() {
2918
+ const servers = Object.keys(this.config.mcpServers ?? {});
2919
+ Tel.getInstance().trackMCPClientInit({
2920
+ codeMode: false,
2921
+ // Browser client doesn't support code mode
2922
+ sandbox: false,
2923
+ // Sandbox not supported in browser
2924
+ allCallbacks: false,
2925
+ // Will be set per-server
2926
+ verify: false,
2927
+ servers,
2928
+ numServers: servers.length,
2929
+ isBrowser: true
2930
+ // Browser MCPClient
2931
+ }).catch(
2932
+ (e) => logger.debug(`Failed to track BrowserMCPClient init: ${e}`)
2933
+ );
1703
2934
  }
1704
2935
  static fromDict(cfg) {
1705
2936
  return new _BrowserMCPClient(cfg);
@@ -2110,8 +3341,20 @@ function useMcp(options) {
2110
3341
  }
2111
3342
  }
2112
3343
  connectingRef.current = false;
3344
+ if (url) {
3345
+ Tel.getInstance().trackUseMcpConnection({
3346
+ url,
3347
+ transportType,
3348
+ success: false,
3349
+ errorType: connectionError?.name || "UnknownError",
3350
+ hasOAuth: !!authProviderRef.current,
3351
+ hasSampling: !!samplingCallback,
3352
+ hasElicitation: !!onElicitation
3353
+ }).catch(() => {
3354
+ });
3355
+ }
2113
3356
  },
2114
- [addLog]
3357
+ [addLog, url, transportType, samplingCallback, onElicitation]
2115
3358
  );
2116
3359
  const connect = (0, import_react.useCallback)(async () => {
2117
3360
  if (!enabled || !url) {
@@ -2220,6 +3463,15 @@ function useMcp(options) {
2220
3463
  );
2221
3464
  setState("ready");
2222
3465
  successfulTransportRef.current = transportTypeParam;
3466
+ Tel.getInstance().trackUseMcpConnection({
3467
+ url,
3468
+ transportType: transportTypeParam,
3469
+ success: true,
3470
+ hasOAuth: !!authProviderRef.current,
3471
+ hasSampling: !!samplingCallback,
3472
+ hasElicitation: !!onElicitation
3473
+ }).catch(() => {
3474
+ });
2223
3475
  setTools(session.connector.tools || []);
2224
3476
  const resourcesResult = await session.connector.listAllResources();
2225
3477
  setResources(resourcesResult.resources || []);
@@ -2237,15 +3489,16 @@ function useMcp(options) {
2237
3489
  }
2238
3490
  return "success";
2239
3491
  } catch (err) {
2240
- const errorMessage = err?.message || String(err);
2241
- if (err.code === 401 || errorMessage.includes("401") || errorMessage.includes("Unauthorized")) {
3492
+ const error2 = err;
3493
+ const errorMessage = error2?.message || String(err);
3494
+ if (error2.code === 401 || errorMessage.includes("401") || errorMessage.includes("Unauthorized")) {
2242
3495
  if (authProviderRef.current) {
2243
3496
  addLog(
2244
3497
  "info",
2245
3498
  "Authentication required. OAuth provider available."
2246
3499
  );
2247
3500
  try {
2248
- const { auth: auth2 } = await import("@modelcontextprotocol/sdk/client/auth.js");
3501
+ const { auth: auth2 } = await import("@mcp-use/modelcontextprotocol-sdk/client/auth.js");
2249
3502
  const baseUrl = new URL(url).origin;
2250
3503
  auth2(authProviderRef.current, { serverUrl: baseUrl }).catch(
2251
3504
  () => {
@@ -2286,7 +3539,10 @@ function useMcp(options) {
2286
3539
  );
2287
3540
  return "failed";
2288
3541
  }
2289
- failConnection(errorMessage, err);
3542
+ failConnection(
3543
+ errorMessage,
3544
+ error2 instanceof Error ? error2 : new Error(String(error2))
3545
+ );
2290
3546
  return "failed";
2291
3547
  }
2292
3548
  }, "tryConnectWithTransport");
@@ -2340,6 +3596,7 @@ function useMcp(options) {
2340
3596
  );
2341
3597
  }
2342
3598
  addLog("info", `Calling tool: ${name}`, args);
3599
+ const startTime = Date.now();
2343
3600
  try {
2344
3601
  const serverName = "inspector-server";
2345
3602
  const session = clientRef.current.getSession(serverName);
@@ -2352,9 +3609,22 @@ function useMcp(options) {
2352
3609
  options2
2353
3610
  );
2354
3611
  addLog("info", `Tool "${name}" call successful:`, result);
3612
+ Tel.getInstance().trackUseMcpToolCall({
3613
+ toolName: name,
3614
+ success: true,
3615
+ executionTimeMs: Date.now() - startTime
3616
+ }).catch(() => {
3617
+ });
2355
3618
  return result;
2356
3619
  } catch (err) {
2357
3620
  addLog("error", `Tool "${name}" call failed:`, err);
3621
+ Tel.getInstance().trackUseMcpToolCall({
3622
+ toolName: name,
3623
+ success: false,
3624
+ errorType: err instanceof Error ? err.name : "UnknownError",
3625
+ executionTimeMs: Date.now() - startTime
3626
+ }).catch(() => {
3627
+ });
2358
3628
  throw err;
2359
3629
  }
2360
3630
  },
@@ -2410,7 +3680,7 @@ function useMcp(options) {
2410
3680
  });
2411
3681
  authProviderRef.current = freshAuthProvider;
2412
3682
  addLog("info", "Triggering fresh OAuth authorization...");
2413
- const { auth: auth2 } = await import("@modelcontextprotocol/sdk/client/auth.js");
3683
+ const { auth: auth2 } = await import("@mcp-use/modelcontextprotocol-sdk/client/auth.js");
2414
3684
  const baseUrl = new URL(url).origin;
2415
3685
  auth2(freshAuthProvider, {
2416
3686
  serverUrl: baseUrl
@@ -2418,7 +3688,7 @@ function useMcp(options) {
2418
3688
  addLog(
2419
3689
  "info",
2420
3690
  "OAuth flow initiated:",
2421
- err?.message || "Redirecting..."
3691
+ err instanceof Error ? err.message : "Redirecting..."
2422
3692
  );
2423
3693
  });
2424
3694
  } catch (authError) {
@@ -2504,9 +3774,20 @@ function useMcp(options) {
2504
3774
  }
2505
3775
  const result = await session.connector.readResource(uri);
2506
3776
  addLog("info", "Resource read successful:", result);
3777
+ Tel.getInstance().trackUseMcpResourceRead({
3778
+ resourceUri: uri,
3779
+ success: true
3780
+ }).catch(() => {
3781
+ });
2507
3782
  return result;
2508
3783
  } catch (err) {
2509
3784
  addLog("error", "Resource read failed:", err);
3785
+ Tel.getInstance().trackUseMcpResourceRead({
3786
+ resourceUri: uri,
3787
+ success: false,
3788
+ errorType: err instanceof Error ? err.name : "UnknownError"
3789
+ }).catch(() => {
3790
+ });
2510
3791
  throw err;
2511
3792
  }
2512
3793
  },
@@ -2693,7 +3974,7 @@ function useMcp(options) {
2693
3974
  __name(useMcp, "useMcp");
2694
3975
 
2695
3976
  // src/auth/callback.ts
2696
- var import_auth = require("@modelcontextprotocol/sdk/client/auth.js");
3977
+ var import_auth = require("@mcp-use/modelcontextprotocol-sdk/client/auth.js");
2697
3978
  async function onMcpAuthorization() {
2698
3979
  const queryParams = new URLSearchParams(window.location.search);
2699
3980
  const code = queryParams.get("code");
@@ -2801,16 +4082,44 @@ async function onMcpAuthorization() {
2801
4082
  );
2802
4083
  }
2803
4084
  try {
2804
- document.body.innerHTML = `
2805
- <div style="font-family: sans-serif; padding: 20px;">
2806
- <h1>Authentication Error</h1>
2807
- <p style="color: red; background-color: #ffebeb; border: 1px solid red; padding: 10px; border-radius: 4px;">
2808
- ${errorMessage}
2809
- </p>
2810
- <p>You can close this window or <a href="#" onclick="window.close(); return false;">click here to close</a>.</p>
2811
- <pre style="font-size: 0.8em; color: #555; margin-top: 20px; white-space: pre-wrap;">${err instanceof Error ? err.stack : ""}</pre>
2812
- </div>
2813
- `;
4085
+ document.body.innerHTML = "";
4086
+ const container = document.createElement("div");
4087
+ container.style.fontFamily = "sans-serif";
4088
+ container.style.padding = "20px";
4089
+ const heading = document.createElement("h1");
4090
+ heading.textContent = "Authentication Error";
4091
+ container.appendChild(heading);
4092
+ const errorPara = document.createElement("p");
4093
+ errorPara.style.color = "red";
4094
+ errorPara.style.backgroundColor = "#ffebeb";
4095
+ errorPara.style.border = "1px solid red";
4096
+ errorPara.style.padding = "10px";
4097
+ errorPara.style.borderRadius = "4px";
4098
+ errorPara.textContent = errorMessage;
4099
+ container.appendChild(errorPara);
4100
+ const closePara = document.createElement("p");
4101
+ closePara.textContent = "You can close this window or ";
4102
+ const closeLink = document.createElement("a");
4103
+ closeLink.href = "#";
4104
+ closeLink.textContent = "click here to close";
4105
+ closeLink.onclick = (e) => {
4106
+ e.preventDefault();
4107
+ window.close();
4108
+ return false;
4109
+ };
4110
+ closePara.appendChild(closeLink);
4111
+ closePara.appendChild(document.createTextNode("."));
4112
+ container.appendChild(closePara);
4113
+ if (err instanceof Error && err.stack) {
4114
+ const stackPre = document.createElement("pre");
4115
+ stackPre.style.fontSize = "0.8em";
4116
+ stackPre.style.color = "#555";
4117
+ stackPre.style.marginTop = "20px";
4118
+ stackPre.style.whiteSpace = "pre-wrap";
4119
+ stackPre.textContent = err.stack;
4120
+ container.appendChild(stackPre);
4121
+ }
4122
+ document.body.appendChild(container);
2814
4123
  } catch (displayError) {
2815
4124
  console.error(
2816
4125
  `${logPrefix} Could not display error in callback window:`,
@@ -3290,7 +4599,8 @@ function WidgetControls({
3290
4599
  const result = await callTool(toolName, args);
3291
4600
  setActionResult(`Success: ${JSON.stringify(result, null, 2)}`);
3292
4601
  } catch (error) {
3293
- setActionResult(`Error: ${error.message}`);
4602
+ const err = error;
4603
+ setActionResult(`Error: ${err.message}`);
3294
4604
  }
3295
4605
  }, "handleCallTool");
3296
4606
  const handleSendFollowUpMessage = /* @__PURE__ */ __name(async () => {
@@ -3299,7 +4609,8 @@ function WidgetControls({
3299
4609
  await sendFollowUpMessage(followUpMessage);
3300
4610
  setActionResult("Follow-up message sent successfully");
3301
4611
  } catch (error) {
3302
- setActionResult(`Error: ${error.message}`);
4612
+ const err = error;
4613
+ setActionResult(`Error: ${err.message}`);
3303
4614
  }
3304
4615
  }, "handleSendFollowUpMessage");
3305
4616
  const handleOpenExternal = /* @__PURE__ */ __name(() => {
@@ -3307,7 +4618,8 @@ function WidgetControls({
3307
4618
  openExternal(externalUrl);
3308
4619
  setActionResult(`Opened external link: ${externalUrl}`);
3309
4620
  } catch (error) {
3310
- setActionResult(`Error: ${error.message}`);
4621
+ const err = error;
4622
+ setActionResult(`Error: ${err.message}`);
3311
4623
  }
3312
4624
  }, "handleOpenExternal");
3313
4625
  const handleRequestDisplayMode = /* @__PURE__ */ __name(async (mode) => {
@@ -3316,7 +4628,8 @@ function WidgetControls({
3316
4628
  const result = await requestDisplayMode(mode);
3317
4629
  setActionResult(`Display mode granted: ${result.mode}`);
3318
4630
  } catch (error) {
3319
- setActionResult(`Error: ${error.message}`);
4631
+ const err = error;
4632
+ setActionResult(`Error: ${err.message}`);
3320
4633
  }
3321
4634
  }, "handleRequestDisplayMode");
3322
4635
  const handleSetState = /* @__PURE__ */ __name(async () => {
@@ -3326,7 +4639,8 @@ function WidgetControls({
3326
4639
  await setState(newState);
3327
4640
  setActionResult(`State updated: ${JSON.stringify(newState, null, 2)}`);
3328
4641
  } catch (error) {
3329
- setActionResult(`Error: ${error.message}`);
4642
+ const err = error;
4643
+ setActionResult(`Error: ${err.message}`);
3330
4644
  }
3331
4645
  }, "handleSetState");
3332
4646
  const handleFullscreen = /* @__PURE__ */ __name(async () => {