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

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 (144) hide show
  1. package/README.md +9 -6
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/chunk-6EYDSXO6.js +942 -0
  4. package/dist/{chunk-D22NUQTL.js → chunk-BFSVTG6G.js} +213 -12
  5. package/dist/{chunk-33U4IA4N.js → chunk-BPP5XYP6.js} +99 -5
  6. package/dist/{chunk-3R5PDYIN.js → chunk-J75I2C26.js} +39 -11
  7. package/dist/{chunk-MUZ5WYE3.js → chunk-NBSNYHID.js} +22 -13
  8. package/dist/{chunk-U5BX3ISQ.js → chunk-NRALSDBH.js} +22 -408
  9. package/dist/{chunk-ZQUCGISK.js → chunk-PL645KUX.js} +21 -5
  10. package/dist/{chunk-QREDNTLS.js → chunk-ZMA4JG4C.js} +1 -1
  11. package/dist/index.cjs +854 -122
  12. package/dist/index.d.ts +6 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +57 -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 +2071 -1620
  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 +3299 -2601
  29. package/dist/src/browser.d.ts +2 -1
  30. package/dist/src/browser.d.ts.map +1 -1
  31. package/dist/src/browser.js +10 -5
  32. package/dist/src/client/browser.d.ts +5 -0
  33. package/dist/src/client/browser.d.ts.map +1 -1
  34. package/dist/src/client/connectors/codeMode.d.ts +1 -1
  35. package/dist/src/client/connectors/codeMode.d.ts.map +1 -1
  36. package/dist/src/client/executors/base.d.ts +1 -1
  37. package/dist/src/client/executors/base.d.ts.map +1 -1
  38. package/dist/src/client/prompts.cjs +13 -4
  39. package/dist/src/client/prompts.js +3 -2
  40. package/dist/src/client.d.ts +7 -1
  41. package/dist/src/client.d.ts.map +1 -1
  42. package/dist/src/connectors/base.d.ts +56 -6
  43. package/dist/src/connectors/base.d.ts.map +1 -1
  44. package/dist/src/connectors/http.d.ts.map +1 -1
  45. package/dist/src/connectors/stdio.d.ts.map +1 -1
  46. package/dist/src/connectors/websocket.d.ts +1 -1
  47. package/dist/src/connectors/websocket.d.ts.map +1 -1
  48. package/dist/src/oauth-helper.d.ts.map +1 -1
  49. package/dist/src/react/WidgetControls.d.ts.map +1 -1
  50. package/dist/src/react/index.cjs +1098 -47
  51. package/dist/src/react/index.d.ts +1 -1
  52. package/dist/src/react/index.d.ts.map +1 -1
  53. package/dist/src/react/index.js +5 -5
  54. package/dist/src/react/types.d.ts +1 -1
  55. package/dist/src/react/types.d.ts.map +1 -1
  56. package/dist/src/react/useMcp.d.ts.map +1 -1
  57. package/dist/src/server/endpoints/mount-mcp.d.ts +4 -1
  58. package/dist/src/server/endpoints/mount-mcp.d.ts.map +1 -1
  59. package/dist/src/server/index.cjs +1723 -274
  60. package/dist/src/server/index.d.ts +3 -2
  61. package/dist/src/server/index.d.ts.map +1 -1
  62. package/dist/src/server/index.js +488 -245
  63. package/dist/src/server/mcp-server.d.ts +77 -27
  64. package/dist/src/server/mcp-server.d.ts.map +1 -1
  65. package/dist/src/server/oauth/middleware.d.ts.map +1 -1
  66. package/dist/src/server/oauth/providers/auth0.d.ts +1 -1
  67. package/dist/src/server/oauth/providers/auth0.d.ts.map +1 -1
  68. package/dist/src/server/oauth/providers/custom.d.ts +4 -2
  69. package/dist/src/server/oauth/providers/custom.d.ts.map +1 -1
  70. package/dist/src/server/oauth/providers/keycloak.d.ts +1 -1
  71. package/dist/src/server/oauth/providers/keycloak.d.ts.map +1 -1
  72. package/dist/src/server/oauth/providers/supabase.d.ts +1 -1
  73. package/dist/src/server/oauth/providers/supabase.d.ts.map +1 -1
  74. package/dist/src/server/oauth/providers/types.d.ts +9 -5
  75. package/dist/src/server/oauth/providers/types.d.ts.map +1 -1
  76. package/dist/src/server/oauth/providers.d.ts +27 -9
  77. package/dist/src/server/oauth/providers.d.ts.map +1 -1
  78. package/dist/src/server/oauth/setup.d.ts +5 -4
  79. package/dist/src/server/oauth/setup.d.ts.map +1 -1
  80. package/dist/src/server/oauth/utils.d.ts +3 -2
  81. package/dist/src/server/oauth/utils.d.ts.map +1 -1
  82. package/dist/src/server/prompts/conversion.d.ts +1 -1
  83. package/dist/src/server/prompts/conversion.d.ts.map +1 -1
  84. package/dist/src/server/prompts/index.d.ts +6 -5
  85. package/dist/src/server/prompts/index.d.ts.map +1 -1
  86. package/dist/src/server/resources/conversion.d.ts +1 -1
  87. package/dist/src/server/resources/conversion.d.ts.map +1 -1
  88. package/dist/src/server/resources/index.d.ts +44 -25
  89. package/dist/src/server/resources/index.d.ts.map +1 -1
  90. package/dist/src/server/resources/subscriptions.d.ts +1 -1
  91. package/dist/src/server/resources/subscriptions.d.ts.map +1 -1
  92. package/dist/src/server/sessions/session-manager.d.ts +11 -5
  93. package/dist/src/server/sessions/session-manager.d.ts.map +1 -1
  94. package/dist/src/server/tools/tool-execution-helpers.d.ts +31 -8
  95. package/dist/src/server/tools/tool-execution-helpers.d.ts.map +1 -1
  96. package/dist/src/server/tools/tool-registration.d.ts +21 -7
  97. package/dist/src/server/tools/tool-registration.d.ts.map +1 -1
  98. package/dist/src/server/types/common.d.ts +25 -9
  99. package/dist/src/server/types/common.d.ts.map +1 -1
  100. package/dist/src/server/types/index.d.ts +3 -3
  101. package/dist/src/server/types/index.d.ts.map +1 -1
  102. package/dist/src/server/types/prompt.d.ts +3 -2
  103. package/dist/src/server/types/prompt.d.ts.map +1 -1
  104. package/dist/src/server/types/resource.d.ts +60 -10
  105. package/dist/src/server/types/resource.d.ts.map +1 -1
  106. package/dist/src/server/types/tool-context.d.ts +116 -1
  107. package/dist/src/server/types/tool-context.d.ts.map +1 -1
  108. package/dist/src/server/types/tool.d.ts +43 -2
  109. package/dist/src/server/types/tool.d.ts.map +1 -1
  110. package/dist/src/server/types/widget.d.ts +11 -1
  111. package/dist/src/server/types/widget.d.ts.map +1 -1
  112. package/dist/src/server/utils/response-helpers.d.ts +17 -29
  113. package/dist/src/server/utils/response-helpers.d.ts.map +1 -1
  114. package/dist/src/server/widgets/index.d.ts +3 -3
  115. package/dist/src/server/widgets/index.d.ts.map +1 -1
  116. package/dist/src/server/widgets/mount-widgets-dev.d.ts.map +1 -1
  117. package/dist/src/server/widgets/ui-resource-registration.d.ts +13 -25
  118. package/dist/src/server/widgets/ui-resource-registration.d.ts.map +1 -1
  119. package/dist/src/server/widgets/widget-helpers.d.ts +11 -6
  120. package/dist/src/server/widgets/widget-helpers.d.ts.map +1 -1
  121. package/dist/src/server/widgets/widget-types.d.ts +3 -3
  122. package/dist/src/server/widgets/widget-types.d.ts.map +1 -1
  123. package/dist/src/session.d.ts +372 -2
  124. package/dist/src/session.d.ts.map +1 -1
  125. package/dist/src/task_managers/sse.d.ts +2 -2
  126. package/dist/src/task_managers/sse.d.ts.map +1 -1
  127. package/dist/src/task_managers/stdio.d.ts +2 -2
  128. package/dist/src/task_managers/stdio.d.ts.map +1 -1
  129. package/dist/src/task_managers/streamable_http.d.ts +2 -2
  130. package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
  131. package/dist/src/telemetry/events.d.ts +219 -0
  132. package/dist/src/telemetry/events.d.ts.map +1 -1
  133. package/dist/src/telemetry/index.d.ts +2 -2
  134. package/dist/src/telemetry/index.d.ts.map +1 -1
  135. package/dist/src/telemetry/telemetry.d.ts +56 -1
  136. package/dist/src/telemetry/telemetry.d.ts.map +1 -1
  137. package/dist/src/telemetry/utils.d.ts +1 -1
  138. package/dist/src/telemetry/utils.d.ts.map +1 -1
  139. package/dist/src/version.d.ts +8 -0
  140. package/dist/src/version.d.ts.map +1 -0
  141. package/dist/{tool-execution-helpers-BQJTPWPN.js → tool-execution-helpers-XFVBSRXM.js} +3 -2
  142. package/dist/tsup.config.d.ts.map +1 -1
  143. package/package.json +6 -5
  144. package/dist/chunk-MTHLLDCX.js +0 -97
@@ -75,16 +75,16 @@ function sanitizeParam([k, v]) {
75
75
  __name(sanitizeParam, "sanitizeParam");
76
76
 
77
77
  // src/connectors/http.ts
78
- var import_client = require("@modelcontextprotocol/sdk/client/index.js");
79
- var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
78
+ var import_client = require("@mcp-use/modelcontextprotocol-sdk/client/index.js");
79
+ var import_streamableHttp = require("@mcp-use/modelcontextprotocol-sdk/client/streamableHttp.js");
80
80
 
81
81
  // src/logging.ts
82
82
  async function getNodeModules() {
83
83
  if (typeof process !== "undefined" && process.platform) {
84
84
  try {
85
- const fs = await import("fs");
86
- const path = await import("path");
87
- return { fs: fs.default, path: path.default };
85
+ const fs2 = await import("fs");
86
+ const path2 = await import("path");
87
+ return { fs: fs2.default, path: path2.default };
88
88
  } catch {
89
89
  return { fs: null, path: null };
90
90
  }
@@ -350,7 +350,7 @@ if (isNodeJSEnvironment()) {
350
350
  var logger = Logger.get();
351
351
 
352
352
  // src/task_managers/sse.ts
353
- var import_sse = require("@modelcontextprotocol/sdk/client/sse.js");
353
+ var import_sse = require("@mcp-use/modelcontextprotocol-sdk/client/sse.js");
354
354
 
355
355
  // src/task_managers/base.ts
356
356
  var ConnectionManager = class {
@@ -513,7 +513,815 @@ var SseConnectionManager = class extends ConnectionManager {
513
513
  };
514
514
 
515
515
  // src/connectors/base.ts
516
- var import_types = require("@modelcontextprotocol/sdk/types.js");
516
+ var import_types = require("@mcp-use/modelcontextprotocol-sdk/types.js");
517
+
518
+ // src/telemetry/telemetry.ts
519
+ var fs = __toESM(require("fs"), 1);
520
+ var os = __toESM(require("os"), 1);
521
+ var path = __toESM(require("path"), 1);
522
+ var import_posthog_node = require("posthog-node");
523
+
524
+ // src/server/utils/runtime.ts
525
+ var isDeno = typeof globalThis.Deno !== "undefined";
526
+ function generateUUID() {
527
+ return globalThis.crypto.randomUUID();
528
+ }
529
+ __name(generateUUID, "generateUUID");
530
+
531
+ // src/telemetry/events.ts
532
+ var BaseTelemetryEvent = class {
533
+ static {
534
+ __name(this, "BaseTelemetryEvent");
535
+ }
536
+ };
537
+ var MCPAgentExecutionEvent = class extends BaseTelemetryEvent {
538
+ constructor(data) {
539
+ super();
540
+ this.data = data;
541
+ }
542
+ static {
543
+ __name(this, "MCPAgentExecutionEvent");
544
+ }
545
+ get name() {
546
+ return "mcp_agent_execution";
547
+ }
548
+ get properties() {
549
+ return {
550
+ // Core execution info
551
+ execution_method: this.data.executionMethod,
552
+ query: this.data.query,
553
+ query_length: this.data.query.length,
554
+ success: this.data.success,
555
+ // Agent configuration
556
+ model_provider: this.data.modelProvider,
557
+ model_name: this.data.modelName,
558
+ server_count: this.data.serverCount,
559
+ server_identifiers: this.data.serverIdentifiers,
560
+ total_tools_available: this.data.totalToolsAvailable,
561
+ tools_available_names: this.data.toolsAvailableNames,
562
+ max_steps_configured: this.data.maxStepsConfigured,
563
+ memory_enabled: this.data.memoryEnabled,
564
+ use_server_manager: this.data.useServerManager,
565
+ // Execution parameters (always include, even if null)
566
+ max_steps_used: this.data.maxStepsUsed,
567
+ manage_connector: this.data.manageConnector,
568
+ external_history_used: this.data.externalHistoryUsed,
569
+ // Execution results (always include, even if null)
570
+ steps_taken: this.data.stepsTaken ?? null,
571
+ tools_used_count: this.data.toolsUsedCount ?? null,
572
+ tools_used_names: this.data.toolsUsedNames ?? null,
573
+ response: this.data.response ?? null,
574
+ response_length: this.data.response ? this.data.response.length : null,
575
+ execution_time_ms: this.data.executionTimeMs ?? null,
576
+ error_type: this.data.errorType ?? null,
577
+ conversation_history_length: this.data.conversationHistoryLength ?? null
578
+ };
579
+ }
580
+ };
581
+ function createServerRunEventData(server, transport) {
582
+ const toolRegistrations = Array.from(server.registrations.tools.values());
583
+ const promptRegistrations = Array.from(server.registrations.prompts.values());
584
+ const resourceRegistrations = Array.from(
585
+ server.registrations.resources.values()
586
+ );
587
+ const templateRegistrations = Array.from(
588
+ server.registrations.resourceTemplates.values()
589
+ );
590
+ const allResources = resourceRegistrations.map((r) => ({
591
+ name: r.config.name,
592
+ title: r.config.title ?? null,
593
+ description: r.config.description ?? null,
594
+ uri: r.config.uri ?? null,
595
+ mime_type: r.config.mimeType ?? null
596
+ }));
597
+ const appsSdkResources = allResources.filter(
598
+ (r) => r.mime_type === "text/html+skybridge"
599
+ );
600
+ const mcpUiResources = allResources.filter(
601
+ (r) => r.mime_type === "text/uri-list" || r.mime_type === "text/html"
602
+ );
603
+ const mcpAppsResources = allResources.filter(
604
+ (r) => r.mime_type === "text/html+mcp"
605
+ );
606
+ return {
607
+ transport,
608
+ toolsNumber: server.registeredTools.length,
609
+ resourcesNumber: server.registeredResources.length,
610
+ promptsNumber: server.registeredPrompts.length,
611
+ auth: !!server.oauthProvider,
612
+ name: server.config.name,
613
+ description: server.config.description ?? null,
614
+ baseUrl: server.serverBaseUrl ?? null,
615
+ toolNames: server.registeredTools.length > 0 ? server.registeredTools : null,
616
+ resourceNames: server.registeredResources.length > 0 ? server.registeredResources : null,
617
+ promptNames: server.registeredPrompts.length > 0 ? server.registeredPrompts : null,
618
+ tools: toolRegistrations.length > 0 ? toolRegistrations.map((r) => ({
619
+ name: r.config.name,
620
+ title: r.config.title ?? null,
621
+ description: r.config.description ?? null,
622
+ input_schema: r.config.schema ? JSON.stringify(r.config.schema) : null,
623
+ output_schema: r.config.outputSchema ? JSON.stringify(r.config.outputSchema) : null
624
+ })) : null,
625
+ resources: allResources.length > 0 ? allResources : null,
626
+ prompts: promptRegistrations.length > 0 ? promptRegistrations.map((r) => ({
627
+ name: r.config.name,
628
+ title: r.config.title ?? null,
629
+ description: r.config.description ?? null,
630
+ args: r.config.args ? JSON.stringify(r.config.args) : null
631
+ })) : null,
632
+ templates: templateRegistrations.length > 0 ? templateRegistrations.map((r) => ({
633
+ name: r.config.name,
634
+ title: r.config.title ?? null,
635
+ description: r.config.description ?? null
636
+ })) : null,
637
+ capabilities: {
638
+ logging: true,
639
+ resources: { subscribe: true, listChanged: true }
640
+ },
641
+ appsSdkResources: appsSdkResources.length > 0 ? appsSdkResources : null,
642
+ appsSdkResourcesNumber: appsSdkResources.length,
643
+ mcpUiResources: mcpUiResources.length > 0 ? mcpUiResources : null,
644
+ mcpUiResourcesNumber: mcpUiResources.length,
645
+ mcpAppsResources: mcpAppsResources.length > 0 ? mcpAppsResources : null,
646
+ mcpAppsResourcesNumber: mcpAppsResources.length
647
+ };
648
+ }
649
+ __name(createServerRunEventData, "createServerRunEventData");
650
+ var ServerRunEvent = class extends BaseTelemetryEvent {
651
+ constructor(data) {
652
+ super();
653
+ this.data = data;
654
+ }
655
+ static {
656
+ __name(this, "ServerRunEvent");
657
+ }
658
+ get name() {
659
+ return "server_run";
660
+ }
661
+ get properties() {
662
+ return {
663
+ transport: this.data.transport,
664
+ tools_number: this.data.toolsNumber,
665
+ resources_number: this.data.resourcesNumber,
666
+ prompts_number: this.data.promptsNumber,
667
+ auth: this.data.auth,
668
+ name: this.data.name,
669
+ description: this.data.description ?? null,
670
+ base_url: this.data.baseUrl ?? null,
671
+ tool_names: this.data.toolNames ?? null,
672
+ resource_names: this.data.resourceNames ?? null,
673
+ prompt_names: this.data.promptNames ?? null,
674
+ tools: this.data.tools ?? null,
675
+ resources: this.data.resources ?? null,
676
+ prompts: this.data.prompts ?? null,
677
+ templates: this.data.templates ?? null,
678
+ capabilities: this.data.capabilities ? JSON.stringify(this.data.capabilities) : null,
679
+ apps_sdk_resources: this.data.appsSdkResources ? JSON.stringify(this.data.appsSdkResources) : null,
680
+ apps_sdk_resources_number: this.data.appsSdkResourcesNumber ?? 0,
681
+ mcp_ui_resources: this.data.mcpUiResources ? JSON.stringify(this.data.mcpUiResources) : null,
682
+ mcp_ui_resources_number: this.data.mcpUiResourcesNumber ?? 0,
683
+ mcp_apps_resources: this.data.mcpAppsResources ? JSON.stringify(this.data.mcpAppsResources) : null,
684
+ mcp_apps_resources_number: this.data.mcpAppsResourcesNumber ?? 0
685
+ };
686
+ }
687
+ };
688
+ var ServerInitializeEvent = class extends BaseTelemetryEvent {
689
+ constructor(data) {
690
+ super();
691
+ this.data = data;
692
+ }
693
+ static {
694
+ __name(this, "ServerInitializeEvent");
695
+ }
696
+ get name() {
697
+ return "server_initialize_call";
698
+ }
699
+ get properties() {
700
+ return {
701
+ protocol_version: this.data.protocolVersion,
702
+ client_info: JSON.stringify(this.data.clientInfo),
703
+ client_capabilities: JSON.stringify(this.data.clientCapabilities),
704
+ session_id: this.data.sessionId ?? null
705
+ };
706
+ }
707
+ };
708
+ var ServerToolCallEvent = class extends BaseTelemetryEvent {
709
+ constructor(data) {
710
+ super();
711
+ this.data = data;
712
+ }
713
+ static {
714
+ __name(this, "ServerToolCallEvent");
715
+ }
716
+ get name() {
717
+ return "server_tool_call";
718
+ }
719
+ get properties() {
720
+ return {
721
+ tool_name: this.data.toolName,
722
+ length_input_argument: this.data.lengthInputArgument,
723
+ success: this.data.success,
724
+ error_type: this.data.errorType ?? null,
725
+ execution_time_ms: this.data.executionTimeMs ?? null
726
+ };
727
+ }
728
+ };
729
+ var ServerResourceCallEvent = class extends BaseTelemetryEvent {
730
+ constructor(data) {
731
+ super();
732
+ this.data = data;
733
+ }
734
+ static {
735
+ __name(this, "ServerResourceCallEvent");
736
+ }
737
+ get name() {
738
+ return "server_resource_call";
739
+ }
740
+ get properties() {
741
+ return {
742
+ name: this.data.name,
743
+ description: this.data.description,
744
+ contents: this.data.contents,
745
+ success: this.data.success,
746
+ error_type: this.data.errorType ?? null
747
+ };
748
+ }
749
+ };
750
+ var ServerPromptCallEvent = class extends BaseTelemetryEvent {
751
+ constructor(data) {
752
+ super();
753
+ this.data = data;
754
+ }
755
+ static {
756
+ __name(this, "ServerPromptCallEvent");
757
+ }
758
+ get name() {
759
+ return "server_prompt_call";
760
+ }
761
+ get properties() {
762
+ return {
763
+ name: this.data.name,
764
+ description: this.data.description,
765
+ success: this.data.success,
766
+ error_type: this.data.errorType ?? null
767
+ };
768
+ }
769
+ };
770
+ var ServerContextEvent = class extends BaseTelemetryEvent {
771
+ constructor(data) {
772
+ super();
773
+ this.data = data;
774
+ }
775
+ static {
776
+ __name(this, "ServerContextEvent");
777
+ }
778
+ get name() {
779
+ return `server_context_${this.data.contextType}`;
780
+ }
781
+ get properties() {
782
+ return {
783
+ context_type: this.data.contextType,
784
+ notification_type: this.data.notificationType ?? null
785
+ };
786
+ }
787
+ };
788
+ var MCPClientInitEvent = class extends BaseTelemetryEvent {
789
+ constructor(data) {
790
+ super();
791
+ this.data = data;
792
+ }
793
+ static {
794
+ __name(this, "MCPClientInitEvent");
795
+ }
796
+ get name() {
797
+ return "mcpclient_init";
798
+ }
799
+ get properties() {
800
+ return {
801
+ code_mode: this.data.codeMode,
802
+ sandbox: this.data.sandbox,
803
+ all_callbacks: this.data.allCallbacks,
804
+ verify: this.data.verify,
805
+ servers: this.data.servers,
806
+ num_servers: this.data.numServers
807
+ };
808
+ }
809
+ };
810
+ var ConnectorInitEvent = class extends BaseTelemetryEvent {
811
+ constructor(data) {
812
+ super();
813
+ this.data = data;
814
+ }
815
+ static {
816
+ __name(this, "ConnectorInitEvent");
817
+ }
818
+ get name() {
819
+ return "connector_init";
820
+ }
821
+ get properties() {
822
+ return {
823
+ connector_type: this.data.connectorType,
824
+ server_command: this.data.serverCommand ?? null,
825
+ server_args: this.data.serverArgs ?? null,
826
+ server_url: this.data.serverUrl ?? null,
827
+ public_identifier: this.data.publicIdentifier ?? null
828
+ };
829
+ }
830
+ };
831
+
832
+ // src/version.ts
833
+ var VERSION = "1.10.0-canary.10";
834
+ function getPackageVersion() {
835
+ return VERSION;
836
+ }
837
+ __name(getPackageVersion, "getPackageVersion");
838
+
839
+ // src/telemetry/telemetry.ts
840
+ var USER_ID_STORAGE_KEY = "mcp_use_user_id";
841
+ function detectRuntimeEnvironment() {
842
+ try {
843
+ if (typeof globalThis.Bun !== "undefined") {
844
+ return "bun";
845
+ }
846
+ if (typeof globalThis.Deno !== "undefined") {
847
+ return "deno";
848
+ }
849
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
850
+ return "cloudflare-workers";
851
+ }
852
+ if (typeof globalThis.EdgeRuntime !== "undefined") {
853
+ return "edge";
854
+ }
855
+ if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined" && typeof fs !== "undefined" && typeof fs.existsSync === "function") {
856
+ return "node";
857
+ }
858
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
859
+ return "browser";
860
+ }
861
+ return "unknown";
862
+ } catch {
863
+ return "unknown";
864
+ }
865
+ }
866
+ __name(detectRuntimeEnvironment, "detectRuntimeEnvironment");
867
+ function getStorageCapability(env) {
868
+ switch (env) {
869
+ case "node":
870
+ case "bun":
871
+ return "filesystem";
872
+ case "browser":
873
+ try {
874
+ if (typeof localStorage !== "undefined") {
875
+ localStorage.setItem("__mcp_use_test__", "1");
876
+ localStorage.removeItem("__mcp_use_test__");
877
+ return "localStorage";
878
+ }
879
+ } catch {
880
+ }
881
+ return "session-only";
882
+ case "deno":
883
+ return "session-only";
884
+ default:
885
+ return "session-only";
886
+ }
887
+ }
888
+ __name(getStorageCapability, "getStorageCapability");
889
+ var cachedEnvironment = null;
890
+ function getRuntimeEnvironment() {
891
+ if (cachedEnvironment === null) {
892
+ cachedEnvironment = detectRuntimeEnvironment();
893
+ }
894
+ return cachedEnvironment;
895
+ }
896
+ __name(getRuntimeEnvironment, "getRuntimeEnvironment");
897
+ function isNodeJSEnvironment2() {
898
+ const env = getRuntimeEnvironment();
899
+ return env === "node" || env === "bun";
900
+ }
901
+ __name(isNodeJSEnvironment2, "isNodeJSEnvironment");
902
+ var ScarfEventLogger = class {
903
+ static {
904
+ __name(this, "ScarfEventLogger");
905
+ }
906
+ endpoint;
907
+ timeout;
908
+ constructor(endpoint, timeout = 3e3) {
909
+ this.endpoint = endpoint;
910
+ this.timeout = timeout;
911
+ }
912
+ async logEvent(properties) {
913
+ try {
914
+ const controller = new AbortController();
915
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
916
+ const response = await fetch(this.endpoint, {
917
+ method: "POST",
918
+ headers: {
919
+ "Content-Type": "application/json"
920
+ },
921
+ body: JSON.stringify(properties),
922
+ signal: controller.signal
923
+ });
924
+ clearTimeout(timeoutId);
925
+ if (!response.ok) {
926
+ throw new Error(`HTTP error! status: ${response.status}`);
927
+ }
928
+ } catch (error) {
929
+ logger.debug(`Failed to send Scarf event: ${error}`);
930
+ }
931
+ }
932
+ };
933
+ function getCacheHome() {
934
+ if (!isNodeJSEnvironment2()) {
935
+ return "/tmp/mcp_use_cache";
936
+ }
937
+ const envVar = process.env.XDG_CACHE_HOME;
938
+ if (envVar && path.isAbsolute(envVar)) {
939
+ return envVar;
940
+ }
941
+ const platform = process.platform;
942
+ const homeDir = os.homedir();
943
+ if (platform === "win32") {
944
+ const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
945
+ if (appdata) {
946
+ return appdata;
947
+ }
948
+ return path.join(homeDir, "AppData", "Local");
949
+ } else if (platform === "darwin") {
950
+ return path.join(homeDir, "Library", "Caches");
951
+ } else {
952
+ return path.join(homeDir, ".cache");
953
+ }
954
+ }
955
+ __name(getCacheHome, "getCacheHome");
956
+ var Telemetry = class _Telemetry {
957
+ static {
958
+ __name(this, "Telemetry");
959
+ }
960
+ static instance = null;
961
+ USER_ID_PATH = path.join(
962
+ getCacheHome(),
963
+ "mcp_use_3",
964
+ "telemetry_user_id"
965
+ );
966
+ VERSION_DOWNLOAD_PATH = path.join(
967
+ getCacheHome(),
968
+ "mcp_use",
969
+ "download_version"
970
+ );
971
+ PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
972
+ HOST = "https://eu.i.posthog.com";
973
+ SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
974
+ UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
975
+ _currUserId = null;
976
+ _posthogClient = null;
977
+ _scarfClient = null;
978
+ _runtimeEnvironment;
979
+ _storageCapability;
980
+ _source;
981
+ constructor() {
982
+ this._runtimeEnvironment = getRuntimeEnvironment();
983
+ this._storageCapability = getStorageCapability(this._runtimeEnvironment);
984
+ this._source = typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE || this._runtimeEnvironment;
985
+ const telemetryDisabled = typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false" || false;
986
+ const canSupportTelemetry = this._runtimeEnvironment !== "unknown";
987
+ const isServerlessEnvironment = [
988
+ "cloudflare-workers",
989
+ "edge",
990
+ "deno"
991
+ ].includes(this._runtimeEnvironment);
992
+ if (telemetryDisabled) {
993
+ this._posthogClient = null;
994
+ this._scarfClient = null;
995
+ logger.debug("Telemetry disabled via environment variable");
996
+ } else if (!canSupportTelemetry) {
997
+ this._posthogClient = null;
998
+ this._scarfClient = null;
999
+ logger.debug(
1000
+ `Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`
1001
+ );
1002
+ } else {
1003
+ logger.info(
1004
+ "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
1005
+ );
1006
+ if (this._runtimeEnvironment !== "browser") {
1007
+ try {
1008
+ const posthogOptions = {
1009
+ host: this.HOST,
1010
+ disableGeoip: false
1011
+ };
1012
+ if (isServerlessEnvironment) {
1013
+ posthogOptions.flushAt = 1;
1014
+ posthogOptions.flushInterval = 0;
1015
+ }
1016
+ this._posthogClient = new import_posthog_node.PostHog(
1017
+ this.PROJECT_API_KEY,
1018
+ posthogOptions
1019
+ );
1020
+ } catch (e) {
1021
+ logger.warn(`Failed to initialize PostHog telemetry: ${e}`);
1022
+ this._posthogClient = null;
1023
+ }
1024
+ } else {
1025
+ this._posthogClient = null;
1026
+ }
1027
+ try {
1028
+ this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
1029
+ } catch (e) {
1030
+ logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
1031
+ this._scarfClient = null;
1032
+ }
1033
+ }
1034
+ }
1035
+ /**
1036
+ * Get the detected runtime environment
1037
+ */
1038
+ get runtimeEnvironment() {
1039
+ return this._runtimeEnvironment;
1040
+ }
1041
+ /**
1042
+ * Get the storage capability for this environment
1043
+ */
1044
+ get storageCapability() {
1045
+ return this._storageCapability;
1046
+ }
1047
+ static getInstance() {
1048
+ if (!_Telemetry.instance) {
1049
+ _Telemetry.instance = new _Telemetry();
1050
+ }
1051
+ return _Telemetry.instance;
1052
+ }
1053
+ /**
1054
+ * Set the source identifier for telemetry events.
1055
+ * This allows tracking usage from different applications.
1056
+ * @param source - The source identifier (e.g., "my-app", "cli", "vs-code-extension")
1057
+ */
1058
+ setSource(source) {
1059
+ this._source = source;
1060
+ logger.debug(`Telemetry source set to: ${source}`);
1061
+ }
1062
+ /**
1063
+ * Get the current source identifier.
1064
+ */
1065
+ getSource() {
1066
+ return this._source;
1067
+ }
1068
+ /**
1069
+ * Check if telemetry is enabled.
1070
+ * Returns false if telemetry was disabled via environment variable or if not in Node.js environment.
1071
+ */
1072
+ get isEnabled() {
1073
+ return this._posthogClient !== null || this._scarfClient !== null;
1074
+ }
1075
+ get userId() {
1076
+ if (this._currUserId) {
1077
+ return this._currUserId;
1078
+ }
1079
+ try {
1080
+ switch (this._storageCapability) {
1081
+ case "filesystem":
1082
+ this._currUserId = this.getUserIdFromFilesystem();
1083
+ break;
1084
+ case "localStorage":
1085
+ this._currUserId = this.getUserIdFromLocalStorage();
1086
+ break;
1087
+ case "session-only":
1088
+ default:
1089
+ this._currUserId = `session-${generateUUID()}`;
1090
+ logger.debug(
1091
+ `Using session-based user ID (${this._runtimeEnvironment} environment)`
1092
+ );
1093
+ break;
1094
+ }
1095
+ if (this._storageCapability === "filesystem" && this._currUserId) {
1096
+ this.trackPackageDownloadInternal(this._currUserId, {
1097
+ triggered_by: "user_id_property"
1098
+ }).catch((e) => logger.debug(`Failed to track package download: ${e}`));
1099
+ }
1100
+ } catch (e) {
1101
+ logger.debug(`Failed to get/create user ID: ${e}`);
1102
+ this._currUserId = this.UNKNOWN_USER_ID;
1103
+ }
1104
+ return this._currUserId;
1105
+ }
1106
+ /**
1107
+ * Get or create user ID from filesystem (Node.js/Bun)
1108
+ */
1109
+ getUserIdFromFilesystem() {
1110
+ const isFirstTime = !fs.existsSync(this.USER_ID_PATH);
1111
+ if (isFirstTime) {
1112
+ logger.debug(`Creating user ID path: ${this.USER_ID_PATH}`);
1113
+ fs.mkdirSync(path.dirname(this.USER_ID_PATH), { recursive: true });
1114
+ const newUserId = generateUUID();
1115
+ fs.writeFileSync(this.USER_ID_PATH, newUserId);
1116
+ logger.debug(`User ID path created: ${this.USER_ID_PATH}`);
1117
+ return newUserId;
1118
+ }
1119
+ return fs.readFileSync(this.USER_ID_PATH, "utf-8").trim();
1120
+ }
1121
+ /**
1122
+ * Get or create user ID from localStorage (Browser)
1123
+ */
1124
+ getUserIdFromLocalStorage() {
1125
+ try {
1126
+ let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
1127
+ if (!userId) {
1128
+ userId = generateUUID();
1129
+ localStorage.setItem(USER_ID_STORAGE_KEY, userId);
1130
+ logger.debug(`Created new browser user ID`);
1131
+ }
1132
+ return userId;
1133
+ } catch (e) {
1134
+ logger.debug(`localStorage access failed: ${e}`);
1135
+ return `session-${generateUUID()}`;
1136
+ }
1137
+ }
1138
+ async capture(event) {
1139
+ logger.debug(
1140
+ `CAPTURE: posthog: ${this._posthogClient !== null}, scarf: ${this._scarfClient !== null}`
1141
+ );
1142
+ if (!this._posthogClient && !this._scarfClient) {
1143
+ return;
1144
+ }
1145
+ if (this._posthogClient) {
1146
+ try {
1147
+ const properties = { ...event.properties };
1148
+ properties.mcp_use_version = getPackageVersion();
1149
+ properties.language = "typescript";
1150
+ properties.source = this._source;
1151
+ properties.runtime = this._runtimeEnvironment;
1152
+ logger.debug(`CAPTURE: PostHog Event ${event.name}`);
1153
+ logger.debug(
1154
+ `CAPTURE: PostHog Properties ${JSON.stringify(properties)}`
1155
+ );
1156
+ this._posthogClient.capture({
1157
+ distinctId: this.userId,
1158
+ event: event.name,
1159
+ properties
1160
+ });
1161
+ } catch (e) {
1162
+ logger.debug(`Failed to track PostHog event ${event.name}: ${e}`);
1163
+ }
1164
+ }
1165
+ if (this._scarfClient) {
1166
+ try {
1167
+ const properties = {};
1168
+ properties.mcp_use_version = getPackageVersion();
1169
+ properties.user_id = this.userId;
1170
+ properties.event = event.name;
1171
+ properties.language = "typescript";
1172
+ properties.source = this._source;
1173
+ properties.runtime = this._runtimeEnvironment;
1174
+ await this._scarfClient.logEvent(properties);
1175
+ } catch (e) {
1176
+ logger.debug(`Failed to track Scarf event ${event.name}: ${e}`);
1177
+ }
1178
+ }
1179
+ }
1180
+ /**
1181
+ * Track package download event.
1182
+ * This is a public wrapper that safely accesses userId.
1183
+ */
1184
+ async trackPackageDownload(properties) {
1185
+ return this.trackPackageDownloadInternal(this.userId, properties);
1186
+ }
1187
+ /**
1188
+ * Internal method to track package download with explicit userId.
1189
+ * This avoids circular dependency when called from the userId getter.
1190
+ */
1191
+ async trackPackageDownloadInternal(userId, properties) {
1192
+ if (!this._scarfClient) {
1193
+ return;
1194
+ }
1195
+ if (this._storageCapability !== "filesystem") {
1196
+ return;
1197
+ }
1198
+ try {
1199
+ const currentVersion = getPackageVersion();
1200
+ let shouldTrack = false;
1201
+ let firstDownload = false;
1202
+ if (!fs.existsSync(this.VERSION_DOWNLOAD_PATH)) {
1203
+ shouldTrack = true;
1204
+ firstDownload = true;
1205
+ fs.mkdirSync(path.dirname(this.VERSION_DOWNLOAD_PATH), {
1206
+ recursive: true
1207
+ });
1208
+ fs.writeFileSync(this.VERSION_DOWNLOAD_PATH, currentVersion);
1209
+ } else {
1210
+ const savedVersion = fs.readFileSync(this.VERSION_DOWNLOAD_PATH, "utf-8").trim();
1211
+ if (currentVersion > savedVersion) {
1212
+ shouldTrack = true;
1213
+ firstDownload = false;
1214
+ fs.writeFileSync(this.VERSION_DOWNLOAD_PATH, currentVersion);
1215
+ }
1216
+ }
1217
+ if (shouldTrack) {
1218
+ logger.debug(
1219
+ `Tracking package download event with properties: ${JSON.stringify(properties)}`
1220
+ );
1221
+ const eventProperties = { ...properties || {} };
1222
+ eventProperties.mcp_use_version = currentVersion;
1223
+ eventProperties.user_id = userId;
1224
+ eventProperties.event = "package_download";
1225
+ eventProperties.first_download = firstDownload;
1226
+ eventProperties.language = "typescript";
1227
+ eventProperties.source = this._source;
1228
+ eventProperties.runtime = this._runtimeEnvironment;
1229
+ await this._scarfClient.logEvent(eventProperties);
1230
+ }
1231
+ } catch (e) {
1232
+ logger.debug(`Failed to track Scarf package_download event: ${e}`);
1233
+ }
1234
+ }
1235
+ // ============================================================================
1236
+ // Agent Events
1237
+ // ============================================================================
1238
+ async trackAgentExecution(data) {
1239
+ if (!this.isEnabled) return;
1240
+ const event = new MCPAgentExecutionEvent(data);
1241
+ await this.capture(event);
1242
+ }
1243
+ // ============================================================================
1244
+ // Server Events
1245
+ // ============================================================================
1246
+ /**
1247
+ * Track server run event directly from an MCPServer instance.
1248
+ * This extracts the necessary data from the server and creates the event.
1249
+ * @param server - The MCPServer instance (or any object conforming to MCPServerTelemetryInfo)
1250
+ * @param transport - The transport type (e.g., "http", "stdio", "supabase")
1251
+ */
1252
+ async trackServerRunFromServer(server, transport) {
1253
+ if (!this.isEnabled) return;
1254
+ const data = createServerRunEventData(server, transport);
1255
+ const event = new ServerRunEvent(data);
1256
+ await this.capture(event);
1257
+ }
1258
+ async trackServerInitialize(data) {
1259
+ if (!this.isEnabled) return;
1260
+ const event = new ServerInitializeEvent(data);
1261
+ await this.capture(event);
1262
+ }
1263
+ async trackServerToolCall(data) {
1264
+ if (!this.isEnabled) return;
1265
+ const event = new ServerToolCallEvent(data);
1266
+ await this.capture(event);
1267
+ }
1268
+ async trackServerResourceCall(data) {
1269
+ if (!this.isEnabled) return;
1270
+ const event = new ServerResourceCallEvent(data);
1271
+ await this.capture(event);
1272
+ }
1273
+ async trackServerPromptCall(data) {
1274
+ if (!this.isEnabled) return;
1275
+ const event = new ServerPromptCallEvent(data);
1276
+ await this.capture(event);
1277
+ }
1278
+ async trackServerContext(data) {
1279
+ if (!this.isEnabled) return;
1280
+ const event = new ServerContextEvent(data);
1281
+ await this.capture(event);
1282
+ }
1283
+ // ============================================================================
1284
+ // Client Events
1285
+ // ============================================================================
1286
+ async trackMCPClientInit(data) {
1287
+ if (!this.isEnabled) return;
1288
+ const event = new MCPClientInitEvent(data);
1289
+ await this.capture(event);
1290
+ }
1291
+ async trackConnectorInit(data) {
1292
+ if (!this.isEnabled) return;
1293
+ const event = new ConnectorInitEvent(data);
1294
+ await this.capture(event);
1295
+ }
1296
+ flush() {
1297
+ if (this._posthogClient) {
1298
+ try {
1299
+ this._posthogClient.flush();
1300
+ logger.debug("PostHog client telemetry queue flushed");
1301
+ } catch (e) {
1302
+ logger.debug(`Failed to flush PostHog client: ${e}`);
1303
+ }
1304
+ }
1305
+ if (this._scarfClient) {
1306
+ logger.debug("Scarf telemetry events sent immediately (no flush needed)");
1307
+ }
1308
+ }
1309
+ shutdown() {
1310
+ if (this._posthogClient) {
1311
+ try {
1312
+ this._posthogClient.shutdown();
1313
+ logger.debug("PostHog client shutdown successfully");
1314
+ } catch (e) {
1315
+ logger.debug(`Error shutting down PostHog client: ${e}`);
1316
+ }
1317
+ }
1318
+ if (this._scarfClient) {
1319
+ logger.debug("Scarf telemetry client shutdown (no action needed)");
1320
+ }
1321
+ }
1322
+ };
1323
+
1324
+ // src/connectors/base.ts
517
1325
  var BaseConnector = class {
518
1326
  static {
519
1327
  __name(this, "BaseConnector");
@@ -533,6 +1341,17 @@ var BaseConnector = class {
533
1341
  this.rootsCache = [...opts.roots];
534
1342
  }
535
1343
  }
1344
+ /**
1345
+ * Track connector initialization event
1346
+ * Should be called by subclasses after successful connection
1347
+ */
1348
+ trackConnectorInit(data) {
1349
+ const connectorType = this.constructor.name;
1350
+ Telemetry.getInstance().trackConnectorInit({
1351
+ connectorType,
1352
+ ...data
1353
+ }).catch((e) => logger.debug(`Failed to track connector init: ${e}`));
1354
+ }
536
1355
  /**
537
1356
  * Register a handler for server notifications
538
1357
  *
@@ -741,7 +1560,7 @@ var BaseConnector = class {
741
1560
  }
742
1561
  logger.debug("Caching server capabilities & tools");
743
1562
  const capabilities = this.client.getServerCapabilities();
744
- this.capabilitiesCache = capabilities;
1563
+ this.capabilitiesCache = capabilities || null;
745
1564
  const serverInfo = this.client.getServerVersion();
746
1565
  this.serverInfoCache = serverInfo || null;
747
1566
  const listToolsRes = await this.client.listTools(
@@ -763,7 +1582,7 @@ var BaseConnector = class {
763
1582
  }
764
1583
  /** Expose cached server capabilities. */
765
1584
  get serverCapabilities() {
766
- return this.capabilitiesCache;
1585
+ return this.capabilitiesCache || {};
767
1586
  }
768
1587
  /** Expose cached server info. */
769
1588
  get serverInfo() {
@@ -830,7 +1649,8 @@ var BaseConnector = class {
830
1649
  } while (cursor);
831
1650
  return { resources: allResources };
832
1651
  } catch (err) {
833
- if (err.code === -32601) {
1652
+ const error = err;
1653
+ if (error.code === -32601) {
834
1654
  logger.debug("Server advertised resources but method not found");
835
1655
  return { resources: [] };
836
1656
  }
@@ -897,7 +1717,8 @@ var BaseConnector = class {
897
1717
  logger.debug("Listing prompts");
898
1718
  return await this.client.listPrompts();
899
1719
  } catch (err) {
900
- if (err.code === -32601) {
1720
+ const error = err;
1721
+ if (error.code === -32601) {
901
1722
  logger.debug("Server advertised prompts but method not found");
902
1723
  return { prompts: [] };
903
1724
  }
@@ -1008,15 +1829,16 @@ var HttpConnector = class extends BaseConnector {
1008
1829
  let fallbackReason = "Unknown error";
1009
1830
  let is401Error = false;
1010
1831
  if (err instanceof import_streamableHttp.StreamableHTTPError) {
1011
- is401Error = err.code === 401;
1012
- if (err.code === 400 && err.message.includes("Missing session ID")) {
1832
+ const streamableErr = err;
1833
+ is401Error = streamableErr.code === 401;
1834
+ if (streamableErr.code === 400 && streamableErr.message.includes("Missing session ID")) {
1013
1835
  fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
1014
1836
  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`;
1837
+ } else if (streamableErr.code === 404 || streamableErr.code === 405) {
1838
+ fallbackReason = `Server returned ${streamableErr.code} - server likely doesn't support streamable HTTP`;
1017
1839
  logger.debug(fallbackReason);
1018
1840
  } else {
1019
- fallbackReason = `Server returned ${err.code}: ${err.message}`;
1841
+ fallbackReason = `Server returned ${streamableErr.code}: ${streamableErr.message}`;
1020
1842
  logger.debug(fallbackReason);
1021
1843
  }
1022
1844
  } else if (err instanceof Error) {
@@ -1156,6 +1978,10 @@ var HttpConnector = class extends BaseConnector {
1156
1978
  logger.debug(
1157
1979
  `Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`
1158
1980
  );
1981
+ this.trackConnectorInit({
1982
+ serverUrl: this.baseUrl,
1983
+ publicIdentifier: `${this.baseUrl} (streamable-http)`
1984
+ });
1159
1985
  } catch (err) {
1160
1986
  await this.cleanupResources();
1161
1987
  throw err;
@@ -1203,6 +2029,10 @@ var HttpConnector = class extends BaseConnector {
1203
2029
  logger.debug(
1204
2030
  `Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`
1205
2031
  );
2032
+ this.trackConnectorInit({
2033
+ serverUrl: this.baseUrl,
2034
+ publicIdentifier: `${this.baseUrl} (sse)`
2035
+ });
1206
2036
  } catch (err) {
1207
2037
  await this.cleanupResources();
1208
2038
  throw err;
@@ -1223,13 +2053,6 @@ var HttpConnector = class extends BaseConnector {
1223
2053
  }
1224
2054
  };
1225
2055
 
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
2056
  // src/task_managers/websocket.ts
1234
2057
  var import_ws = __toESM(require("ws"), 1);
1235
2058
  var WebSocketConnectionManager = class extends ConnectionManager {
@@ -1574,6 +2397,190 @@ var MCPSession = class {
1574
2397
  getRoots() {
1575
2398
  return this.connector.getRoots();
1576
2399
  }
2400
+ /**
2401
+ * Get the cached list of tools from the server.
2402
+ *
2403
+ * @returns Array of available tools
2404
+ *
2405
+ * @example
2406
+ * ```typescript
2407
+ * const tools = session.tools;
2408
+ * console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
2409
+ * ```
2410
+ */
2411
+ get tools() {
2412
+ return this.connector.tools;
2413
+ }
2414
+ /**
2415
+ * Get the server capabilities advertised during initialization.
2416
+ *
2417
+ * @returns Server capabilities object
2418
+ */
2419
+ get serverCapabilities() {
2420
+ return this.connector.serverCapabilities;
2421
+ }
2422
+ /**
2423
+ * Get the server information (name and version).
2424
+ *
2425
+ * @returns Server info object or null if not available
2426
+ */
2427
+ get serverInfo() {
2428
+ return this.connector.serverInfo;
2429
+ }
2430
+ /**
2431
+ * Call a tool on the server.
2432
+ *
2433
+ * @param name - Name of the tool to call
2434
+ * @param args - Arguments to pass to the tool
2435
+ * @param options - Optional request options (timeout, progress handlers, etc.)
2436
+ * @returns Result from the tool execution
2437
+ *
2438
+ * @example
2439
+ * ```typescript
2440
+ * const result = await session.callTool("add", { a: 5, b: 3 });
2441
+ * console.log(`Result: ${result.content[0].text}`);
2442
+ * ```
2443
+ */
2444
+ async callTool(name, args, options) {
2445
+ return this.connector.callTool(name, args, options);
2446
+ }
2447
+ /**
2448
+ * List resources from the server with optional pagination.
2449
+ *
2450
+ * @param cursor - Optional cursor for pagination
2451
+ * @param options - Request options
2452
+ * @returns Resource list with optional nextCursor for pagination
2453
+ *
2454
+ * @example
2455
+ * ```typescript
2456
+ * const result = await session.listResources();
2457
+ * console.log(`Found ${result.resources.length} resources`);
2458
+ * ```
2459
+ */
2460
+ async listResources(cursor, options) {
2461
+ return this.connector.listResources(cursor, options);
2462
+ }
2463
+ /**
2464
+ * List all resources from the server, automatically handling pagination.
2465
+ *
2466
+ * @param options - Request options
2467
+ * @returns Complete list of all resources
2468
+ *
2469
+ * @example
2470
+ * ```typescript
2471
+ * const result = await session.listAllResources();
2472
+ * console.log(`Total resources: ${result.resources.length}`);
2473
+ * ```
2474
+ */
2475
+ async listAllResources(options) {
2476
+ return this.connector.listAllResources(options);
2477
+ }
2478
+ /**
2479
+ * List resource templates from the server.
2480
+ *
2481
+ * @param options - Request options
2482
+ * @returns List of available resource templates
2483
+ *
2484
+ * @example
2485
+ * ```typescript
2486
+ * const result = await session.listResourceTemplates();
2487
+ * console.log(`Available templates: ${result.resourceTemplates.length}`);
2488
+ * ```
2489
+ */
2490
+ async listResourceTemplates(options) {
2491
+ return this.connector.listResourceTemplates(options);
2492
+ }
2493
+ /**
2494
+ * Read a resource by URI.
2495
+ *
2496
+ * @param uri - URI of the resource to read
2497
+ * @param options - Request options
2498
+ * @returns Resource content
2499
+ *
2500
+ * @example
2501
+ * ```typescript
2502
+ * const resource = await session.readResource("file:///path/to/file.txt");
2503
+ * console.log(resource.contents);
2504
+ * ```
2505
+ */
2506
+ async readResource(uri, options) {
2507
+ return this.connector.readResource(uri, options);
2508
+ }
2509
+ /**
2510
+ * Subscribe to resource updates.
2511
+ *
2512
+ * @param uri - URI of the resource to subscribe to
2513
+ * @param options - Request options
2514
+ *
2515
+ * @example
2516
+ * ```typescript
2517
+ * await session.subscribeToResource("file:///path/to/file.txt");
2518
+ * // Now you'll receive notifications when this resource changes
2519
+ * ```
2520
+ */
2521
+ async subscribeToResource(uri, options) {
2522
+ return this.connector.subscribeToResource(uri, options);
2523
+ }
2524
+ /**
2525
+ * Unsubscribe from resource updates.
2526
+ *
2527
+ * @param uri - URI of the resource to unsubscribe from
2528
+ * @param options - Request options
2529
+ *
2530
+ * @example
2531
+ * ```typescript
2532
+ * await session.unsubscribeFromResource("file:///path/to/file.txt");
2533
+ * ```
2534
+ */
2535
+ async unsubscribeFromResource(uri, options) {
2536
+ return this.connector.unsubscribeFromResource(uri, options);
2537
+ }
2538
+ /**
2539
+ * List available prompts from the server.
2540
+ *
2541
+ * @returns List of available prompts
2542
+ *
2543
+ * @example
2544
+ * ```typescript
2545
+ * const result = await session.listPrompts();
2546
+ * console.log(`Available prompts: ${result.prompts.length}`);
2547
+ * ```
2548
+ */
2549
+ async listPrompts() {
2550
+ return this.connector.listPrompts();
2551
+ }
2552
+ /**
2553
+ * Get a specific prompt with arguments.
2554
+ *
2555
+ * @param name - Name of the prompt to get
2556
+ * @param args - Arguments for the prompt
2557
+ * @returns Prompt result
2558
+ *
2559
+ * @example
2560
+ * ```typescript
2561
+ * const prompt = await session.getPrompt("greeting", { name: "Alice" });
2562
+ * console.log(prompt.messages);
2563
+ * ```
2564
+ */
2565
+ async getPrompt(name, args) {
2566
+ return this.connector.getPrompt(name, args);
2567
+ }
2568
+ /**
2569
+ * Send a raw request through the client.
2570
+ *
2571
+ * @param method - MCP method name
2572
+ * @param params - Request parameters
2573
+ * @param options - Request options
2574
+ * @returns Response from the server
2575
+ *
2576
+ * @example
2577
+ * ```typescript
2578
+ * const result = await session.request("custom/method", { key: "value" });
2579
+ * ```
2580
+ */
2581
+ async request(method, params = null, options) {
2582
+ return this.connector.request(method, params, options);
2583
+ }
1577
2584
  };
1578
2585
 
1579
2586
  // src/client/base.ts
@@ -1698,6 +2705,13 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
1698
2705
  static {
1699
2706
  __name(this, "BrowserMCPClient");
1700
2707
  }
2708
+ /**
2709
+ * Get the mcp-use package version.
2710
+ * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
2711
+ */
2712
+ static getPackageVersion() {
2713
+ return getPackageVersion();
2714
+ }
1701
2715
  constructor(config) {
1702
2716
  super(config);
1703
2717
  }
@@ -2237,15 +3251,16 @@ function useMcp(options) {
2237
3251
  }
2238
3252
  return "success";
2239
3253
  } catch (err) {
2240
- const errorMessage = err?.message || String(err);
2241
- if (err.code === 401 || errorMessage.includes("401") || errorMessage.includes("Unauthorized")) {
3254
+ const error2 = err;
3255
+ const errorMessage = error2?.message || String(err);
3256
+ if (error2.code === 401 || errorMessage.includes("401") || errorMessage.includes("Unauthorized")) {
2242
3257
  if (authProviderRef.current) {
2243
3258
  addLog(
2244
3259
  "info",
2245
3260
  "Authentication required. OAuth provider available."
2246
3261
  );
2247
3262
  try {
2248
- const { auth: auth2 } = await import("@modelcontextprotocol/sdk/client/auth.js");
3263
+ const { auth: auth2 } = await import("@mcp-use/modelcontextprotocol-sdk/client/auth.js");
2249
3264
  const baseUrl = new URL(url).origin;
2250
3265
  auth2(authProviderRef.current, { serverUrl: baseUrl }).catch(
2251
3266
  () => {
@@ -2286,7 +3301,10 @@ function useMcp(options) {
2286
3301
  );
2287
3302
  return "failed";
2288
3303
  }
2289
- failConnection(errorMessage, err);
3304
+ failConnection(
3305
+ errorMessage,
3306
+ error2 instanceof Error ? error2 : new Error(String(error2))
3307
+ );
2290
3308
  return "failed";
2291
3309
  }
2292
3310
  }, "tryConnectWithTransport");
@@ -2410,7 +3428,7 @@ function useMcp(options) {
2410
3428
  });
2411
3429
  authProviderRef.current = freshAuthProvider;
2412
3430
  addLog("info", "Triggering fresh OAuth authorization...");
2413
- const { auth: auth2 } = await import("@modelcontextprotocol/sdk/client/auth.js");
3431
+ const { auth: auth2 } = await import("@mcp-use/modelcontextprotocol-sdk/client/auth.js");
2414
3432
  const baseUrl = new URL(url).origin;
2415
3433
  auth2(freshAuthProvider, {
2416
3434
  serverUrl: baseUrl
@@ -2418,7 +3436,7 @@ function useMcp(options) {
2418
3436
  addLog(
2419
3437
  "info",
2420
3438
  "OAuth flow initiated:",
2421
- err?.message || "Redirecting..."
3439
+ err instanceof Error ? err.message : "Redirecting..."
2422
3440
  );
2423
3441
  });
2424
3442
  } catch (authError) {
@@ -2693,7 +3711,7 @@ function useMcp(options) {
2693
3711
  __name(useMcp, "useMcp");
2694
3712
 
2695
3713
  // src/auth/callback.ts
2696
- var import_auth = require("@modelcontextprotocol/sdk/client/auth.js");
3714
+ var import_auth = require("@mcp-use/modelcontextprotocol-sdk/client/auth.js");
2697
3715
  async function onMcpAuthorization() {
2698
3716
  const queryParams = new URLSearchParams(window.location.search);
2699
3717
  const code = queryParams.get("code");
@@ -2801,16 +3819,44 @@ async function onMcpAuthorization() {
2801
3819
  );
2802
3820
  }
2803
3821
  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
- `;
3822
+ document.body.innerHTML = "";
3823
+ const container = document.createElement("div");
3824
+ container.style.fontFamily = "sans-serif";
3825
+ container.style.padding = "20px";
3826
+ const heading = document.createElement("h1");
3827
+ heading.textContent = "Authentication Error";
3828
+ container.appendChild(heading);
3829
+ const errorPara = document.createElement("p");
3830
+ errorPara.style.color = "red";
3831
+ errorPara.style.backgroundColor = "#ffebeb";
3832
+ errorPara.style.border = "1px solid red";
3833
+ errorPara.style.padding = "10px";
3834
+ errorPara.style.borderRadius = "4px";
3835
+ errorPara.textContent = errorMessage;
3836
+ container.appendChild(errorPara);
3837
+ const closePara = document.createElement("p");
3838
+ closePara.textContent = "You can close this window or ";
3839
+ const closeLink = document.createElement("a");
3840
+ closeLink.href = "#";
3841
+ closeLink.textContent = "click here to close";
3842
+ closeLink.onclick = (e) => {
3843
+ e.preventDefault();
3844
+ window.close();
3845
+ return false;
3846
+ };
3847
+ closePara.appendChild(closeLink);
3848
+ closePara.appendChild(document.createTextNode("."));
3849
+ container.appendChild(closePara);
3850
+ if (err instanceof Error && err.stack) {
3851
+ const stackPre = document.createElement("pre");
3852
+ stackPre.style.fontSize = "0.8em";
3853
+ stackPre.style.color = "#555";
3854
+ stackPre.style.marginTop = "20px";
3855
+ stackPre.style.whiteSpace = "pre-wrap";
3856
+ stackPre.textContent = err.stack;
3857
+ container.appendChild(stackPre);
3858
+ }
3859
+ document.body.appendChild(container);
2814
3860
  } catch (displayError) {
2815
3861
  console.error(
2816
3862
  `${logPrefix} Could not display error in callback window:`,
@@ -3290,7 +4336,8 @@ function WidgetControls({
3290
4336
  const result = await callTool(toolName, args);
3291
4337
  setActionResult(`Success: ${JSON.stringify(result, null, 2)}`);
3292
4338
  } catch (error) {
3293
- setActionResult(`Error: ${error.message}`);
4339
+ const err = error;
4340
+ setActionResult(`Error: ${err.message}`);
3294
4341
  }
3295
4342
  }, "handleCallTool");
3296
4343
  const handleSendFollowUpMessage = /* @__PURE__ */ __name(async () => {
@@ -3299,7 +4346,8 @@ function WidgetControls({
3299
4346
  await sendFollowUpMessage(followUpMessage);
3300
4347
  setActionResult("Follow-up message sent successfully");
3301
4348
  } catch (error) {
3302
- setActionResult(`Error: ${error.message}`);
4349
+ const err = error;
4350
+ setActionResult(`Error: ${err.message}`);
3303
4351
  }
3304
4352
  }, "handleSendFollowUpMessage");
3305
4353
  const handleOpenExternal = /* @__PURE__ */ __name(() => {
@@ -3307,7 +4355,8 @@ function WidgetControls({
3307
4355
  openExternal(externalUrl);
3308
4356
  setActionResult(`Opened external link: ${externalUrl}`);
3309
4357
  } catch (error) {
3310
- setActionResult(`Error: ${error.message}`);
4358
+ const err = error;
4359
+ setActionResult(`Error: ${err.message}`);
3311
4360
  }
3312
4361
  }, "handleOpenExternal");
3313
4362
  const handleRequestDisplayMode = /* @__PURE__ */ __name(async (mode) => {
@@ -3316,7 +4365,8 @@ function WidgetControls({
3316
4365
  const result = await requestDisplayMode(mode);
3317
4366
  setActionResult(`Display mode granted: ${result.mode}`);
3318
4367
  } catch (error) {
3319
- setActionResult(`Error: ${error.message}`);
4368
+ const err = error;
4369
+ setActionResult(`Error: ${err.message}`);
3320
4370
  }
3321
4371
  }, "handleRequestDisplayMode");
3322
4372
  const handleSetState = /* @__PURE__ */ __name(async () => {
@@ -3326,7 +4376,8 @@ function WidgetControls({
3326
4376
  await setState(newState);
3327
4377
  setActionResult(`State updated: ${JSON.stringify(newState, null, 2)}`);
3328
4378
  } catch (error) {
3329
- setActionResult(`Error: ${error.message}`);
4379
+ const err = error;
4380
+ setActionResult(`Error: ${err.message}`);
3330
4381
  }
3331
4382
  }, "handleSetState");
3332
4383
  const handleFullscreen = /* @__PURE__ */ __name(async () => {
@@ -3603,8 +4654,8 @@ __name(WidgetControls, "WidgetControls");
3603
4654
  var import_react7 = __toESM(require("react"), 1);
3604
4655
  function getBasename() {
3605
4656
  if (typeof window === "undefined") return "/";
3606
- const path = window.location.pathname;
3607
- const match = path.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);
4657
+ const path2 = window.location.pathname;
4658
+ const match = path2.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);
3608
4659
  if (match) {
3609
4660
  return match[1];
3610
4661
  }