mcp-use 1.2.1 → 1.2.2-canary.1

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 (155) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/chunk-3RJENWH4.js +248 -0
  3. package/dist/{chunk-MGUO7HXB.js → chunk-7UX634PO.js} +307 -1066
  4. package/dist/chunk-KLIBVJ3Z.js +759 -0
  5. package/dist/chunk-MZLETWQQ.js +250 -0
  6. package/dist/chunk-RSGKBEHH.js +1411 -0
  7. package/dist/index.cjs +880 -541
  8. package/dist/index.d.ts +24 -24
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +92 -33
  11. package/dist/{langfuse-6AJGHMAV.js → langfuse-LCJ6VJEP.js} +2 -1
  12. package/dist/src/adapters/base.d.ts +2 -2
  13. package/dist/src/adapters/base.d.ts.map +1 -1
  14. package/dist/src/adapters/index.d.ts +2 -2
  15. package/dist/src/adapters/index.d.ts.map +1 -1
  16. package/dist/src/adapters/langchain_adapter.d.ts +4 -4
  17. package/dist/src/adapters/langchain_adapter.d.ts.map +1 -1
  18. package/dist/src/agents/base.d.ts +1 -1
  19. package/dist/src/agents/base.d.ts.map +1 -1
  20. package/dist/src/agents/index.d.ts +3 -3
  21. package/dist/src/agents/index.d.ts.map +1 -1
  22. package/dist/src/agents/mcp_agent.d.ts +12 -12
  23. package/dist/src/agents/mcp_agent.d.ts.map +1 -1
  24. package/dist/src/agents/prompts/system_prompt_builder.d.ts +2 -2
  25. package/dist/src/agents/prompts/system_prompt_builder.d.ts.map +1 -1
  26. package/dist/src/agents/prompts/templates.d.ts.map +1 -1
  27. package/dist/src/agents/remote.d.ts +2 -2
  28. package/dist/src/agents/remote.d.ts.map +1 -1
  29. package/dist/src/agents/types.d.ts +1 -1
  30. package/dist/src/agents/types.d.ts.map +1 -1
  31. package/dist/src/agents/utils/ai_sdk.d.ts +1 -1
  32. package/dist/src/agents/utils/ai_sdk.d.ts.map +1 -1
  33. package/dist/src/agents/utils/index.d.ts +1 -1
  34. package/dist/src/agents/utils/index.d.ts.map +1 -1
  35. package/dist/src/auth/browser-provider.d.ts +2 -2
  36. package/dist/src/auth/browser-provider.d.ts.map +1 -1
  37. package/dist/src/auth/callback.d.ts.map +1 -1
  38. package/dist/src/auth/index.d.ts +3 -3
  39. package/dist/src/auth/index.d.ts.map +1 -1
  40. package/dist/src/auth/types.d.ts +1 -1
  41. package/dist/src/auth/types.d.ts.map +1 -1
  42. package/dist/src/browser.cjs +573 -219
  43. package/dist/src/browser.d.ts +17 -17
  44. package/dist/src/browser.d.ts.map +1 -1
  45. package/dist/src/browser.js +17 -46
  46. package/dist/src/client/base.d.ts +2 -2
  47. package/dist/src/client/base.d.ts.map +1 -1
  48. package/dist/src/client/browser.d.ts +2 -2
  49. package/dist/src/client/browser.d.ts.map +1 -1
  50. package/dist/src/client.d.ts +2 -2
  51. package/dist/src/client.d.ts.map +1 -1
  52. package/dist/src/config.d.ts +1 -1
  53. package/dist/src/config.d.ts.map +1 -1
  54. package/dist/src/connectors/base.d.ts +51 -9
  55. package/dist/src/connectors/base.d.ts.map +1 -1
  56. package/dist/src/connectors/http.d.ts +3 -3
  57. package/dist/src/connectors/http.d.ts.map +1 -1
  58. package/dist/src/connectors/index.d.ts +4 -4
  59. package/dist/src/connectors/index.d.ts.map +1 -1
  60. package/dist/src/connectors/stdio.d.ts +3 -3
  61. package/dist/src/connectors/stdio.d.ts.map +1 -1
  62. package/dist/src/connectors/websocket.d.ts +4 -7
  63. package/dist/src/connectors/websocket.d.ts.map +1 -1
  64. package/dist/src/logging.d.ts +4 -4
  65. package/dist/src/logging.d.ts.map +1 -1
  66. package/dist/src/managers/index.d.ts +2 -2
  67. package/dist/src/managers/index.d.ts.map +1 -1
  68. package/dist/src/managers/server_manager.d.ts +4 -4
  69. package/dist/src/managers/server_manager.d.ts.map +1 -1
  70. package/dist/src/managers/tools/acquire_active_mcp_server.d.ts +3 -3
  71. package/dist/src/managers/tools/acquire_active_mcp_server.d.ts.map +1 -1
  72. package/dist/src/managers/tools/add_server_from_config.d.ts +3 -3
  73. package/dist/src/managers/tools/add_server_from_config.d.ts.map +1 -1
  74. package/dist/src/managers/tools/base.d.ts +6 -6
  75. package/dist/src/managers/tools/base.d.ts.map +1 -1
  76. package/dist/src/managers/tools/connect_mcp_server.d.ts +4 -4
  77. package/dist/src/managers/tools/connect_mcp_server.d.ts.map +1 -1
  78. package/dist/src/managers/tools/index.d.ts +5 -5
  79. package/dist/src/managers/tools/index.d.ts.map +1 -1
  80. package/dist/src/managers/tools/list_mcp_servers.d.ts +3 -3
  81. package/dist/src/managers/tools/list_mcp_servers.d.ts.map +1 -1
  82. package/dist/src/managers/tools/release_mcp_server_connection.d.ts +3 -3
  83. package/dist/src/managers/tools/release_mcp_server_connection.d.ts.map +1 -1
  84. package/dist/src/managers/types.d.ts +3 -3
  85. package/dist/src/managers/types.d.ts.map +1 -1
  86. package/dist/src/oauth-helper.d.ts.map +1 -1
  87. package/dist/src/observability/index.d.ts +3 -3
  88. package/dist/src/observability/index.d.ts.map +1 -1
  89. package/dist/src/observability/langfuse.d.ts +1 -1
  90. package/dist/src/observability/langfuse.d.ts.map +1 -1
  91. package/dist/src/observability/manager.d.ts +1 -1
  92. package/dist/src/observability/manager.d.ts.map +1 -1
  93. package/dist/src/observability/types.d.ts +1 -1
  94. package/dist/src/observability/types.d.ts.map +1 -1
  95. package/dist/src/react/index.cjs +1571 -321
  96. package/dist/src/react/index.d.ts +6 -6
  97. package/dist/src/react/index.d.ts.map +1 -1
  98. package/dist/src/react/index.js +3 -2
  99. package/dist/src/react/types.d.ts +27 -5
  100. package/dist/src/react/types.d.ts.map +1 -1
  101. package/dist/src/react/useMcp.d.ts +32 -1
  102. package/dist/src/react/useMcp.d.ts.map +1 -1
  103. package/dist/src/react/useWidget.d.ts +5 -2
  104. package/dist/src/react/useWidget.d.ts.map +1 -1
  105. package/dist/src/react/widget-types.d.ts +3 -3
  106. package/dist/src/react/widget-types.d.ts.map +1 -1
  107. package/dist/src/server/adapters/mcp-ui-adapter.d.ts +3 -3
  108. package/dist/src/server/adapters/mcp-ui-adapter.d.ts.map +1 -1
  109. package/dist/src/server/index.cjs +170 -50
  110. package/dist/src/server/index.d.ts +4 -4
  111. package/dist/src/server/index.d.ts.map +1 -1
  112. package/dist/src/server/index.js +174 -51
  113. package/dist/src/server/logging.d.ts +1 -1
  114. package/dist/src/server/logging.d.ts.map +1 -1
  115. package/dist/src/server/mcp-server.d.ts +29 -29
  116. package/dist/src/server/mcp-server.d.ts.map +1 -1
  117. package/dist/src/server/types/common.d.ts +2 -2
  118. package/dist/src/server/types/common.d.ts.map +1 -1
  119. package/dist/src/server/types/index.d.ts +4 -4
  120. package/dist/src/server/types/index.d.ts.map +1 -1
  121. package/dist/src/server/types/prompt.d.ts +2 -2
  122. package/dist/src/server/types/prompt.d.ts.map +1 -1
  123. package/dist/src/server/types/resource.d.ts +24 -24
  124. package/dist/src/server/types/resource.d.ts.map +1 -1
  125. package/dist/src/server/types/tool.d.ts +3 -3
  126. package/dist/src/server/types/tool.d.ts.map +1 -1
  127. package/dist/src/server/types/widget.d.ts +1 -1
  128. package/dist/src/server/types.d.ts +1 -1
  129. package/dist/src/server/types.d.ts.map +1 -1
  130. package/dist/src/session.d.ts +1 -1
  131. package/dist/src/session.d.ts.map +1 -1
  132. package/dist/src/task_managers/base.d.ts.map +1 -1
  133. package/dist/src/task_managers/index.d.ts +5 -5
  134. package/dist/src/task_managers/index.d.ts.map +1 -1
  135. package/dist/src/task_managers/sse.d.ts +3 -3
  136. package/dist/src/task_managers/sse.d.ts.map +1 -1
  137. package/dist/src/task_managers/stdio.d.ts +4 -4
  138. package/dist/src/task_managers/stdio.d.ts.map +1 -1
  139. package/dist/src/task_managers/streamable_http.d.ts +3 -3
  140. package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
  141. package/dist/src/task_managers/websocket.d.ts +2 -2
  142. package/dist/src/task_managers/websocket.d.ts.map +1 -1
  143. package/dist/src/telemetry/events.d.ts.map +1 -1
  144. package/dist/src/telemetry/index.d.ts +4 -4
  145. package/dist/src/telemetry/index.d.ts.map +1 -1
  146. package/dist/src/telemetry/telemetry.d.ts +1 -1
  147. package/dist/src/telemetry/telemetry.d.ts.map +1 -1
  148. package/dist/src/telemetry/utils.d.ts +1 -1
  149. package/dist/src/telemetry/utils.d.ts.map +1 -1
  150. package/dist/tsup.config.d.ts.map +1 -1
  151. package/dist/vitest.config.d.ts.map +1 -1
  152. package/package.json +3 -3
  153. package/dist/chunk-62GFHYCL.js +0 -300
  154. package/dist/chunk-JV7HAYUT.js +0 -860
  155. package/dist/chunk-ZUEQQ6YK.js +0 -444
@@ -90,7 +90,15 @@ var init_logging = __esm({
90
90
  this._level = level;
91
91
  }
92
92
  shouldLog(level) {
93
- const levels = ["error", "warn", "info", "http", "verbose", "debug", "silly"];
93
+ const levels = [
94
+ "error",
95
+ "warn",
96
+ "info",
97
+ "http",
98
+ "verbose",
99
+ "debug",
100
+ "silly"
101
+ ];
94
102
  const currentIndex = levels.indexOf(this._level);
95
103
  const messageIndex = levels.indexOf(level);
96
104
  return messageIndex <= currentIndex;
@@ -163,7 +171,10 @@ var init_logging = __esm({
163
171
  if (!isNodeJSEnvironment()) {
164
172
  if (!this.simpleInstances[name]) {
165
173
  const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
166
- this.simpleInstances[name] = new SimpleConsoleLogger(name, resolveLevel(debugEnv));
174
+ this.simpleInstances[name] = new SimpleConsoleLogger(
175
+ name,
176
+ resolveLevel(debugEnv)
177
+ );
167
178
  }
168
179
  return this.simpleInstances[name];
169
180
  }
@@ -237,10 +248,8 @@ var init_logging = __esm({
237
248
  }
238
249
  static setDebug(enabled) {
239
250
  let level;
240
- if (enabled === 2 || enabled === true)
241
- level = "debug";
242
- else if (enabled === 1)
243
- level = "info";
251
+ if (enabled === 2 || enabled === true) level = "debug";
252
+ else if (enabled === 1) level = "info";
244
253
  else level = "info";
245
254
  Object.values(this.simpleInstances).forEach((logger2) => {
246
255
  logger2.level = level;
@@ -280,7 +289,9 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
280
289
  try {
281
290
  const langfuseModule = await import("langfuse-langchain").catch(() => null);
282
291
  if (!langfuseModule) {
283
- logger.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");
292
+ logger.debug(
293
+ "Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain"
294
+ );
284
295
  return;
285
296
  }
286
297
  const { CallbackHandler } = langfuseModule;
@@ -309,10 +320,23 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
309
320
  const enhancedTags = [...tags || [], ...customTags];
310
321
  const enhancedMetadata = { ...metadata2 || {}, ...metadataToAdd };
311
322
  if (this.verbose) {
312
- logger.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(enhancedTags)}`);
313
- logger.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(enhancedMetadata)}`);
323
+ logger.debug(
324
+ `Langfuse: Chain start with custom tags: ${JSON.stringify(enhancedTags)}`
325
+ );
326
+ logger.debug(
327
+ `Langfuse: Chain start with metadata: ${JSON.stringify(enhancedMetadata)}`
328
+ );
314
329
  }
315
- return super.handleChainStart(chain, inputs, runId, parentRunId, enhancedTags, enhancedMetadata, name, kwargs);
330
+ return super.handleChainStart(
331
+ chain,
332
+ inputs,
333
+ runId,
334
+ parentRunId,
335
+ enhancedTags,
336
+ enhancedMetadata,
337
+ name,
338
+ kwargs
339
+ );
316
340
  }
317
341
  // Get custom tags based on environment and agent configuration
318
342
  getCustomTags() {
@@ -388,7 +412,9 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
388
412
  async handleRetrieverStart(...args) {
389
413
  logger.debug("Langfuse: Retriever start intercepted");
390
414
  if (this.verbose) {
391
- logger.debug(`Langfuse: Retriever start args: ${JSON.stringify(args)}`);
415
+ logger.debug(
416
+ `Langfuse: Retriever start args: ${JSON.stringify(args)}`
417
+ );
392
418
  }
393
419
  return super.handleRetrieverStart(...args);
394
420
  }
@@ -414,9 +440,13 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
414
440
  secretKey: process.env.LANGFUSE_SECRET_KEY,
415
441
  baseUrl: process.env.LANGFUSE_HOST || process.env.LANGFUSE_BASEURL || "https://cloud.langfuse.com",
416
442
  flushAt: Number.parseInt(process.env.LANGFUSE_FLUSH_AT || "15"),
417
- flushInterval: Number.parseInt(process.env.LANGFUSE_FLUSH_INTERVAL || "10000"),
443
+ flushInterval: Number.parseInt(
444
+ process.env.LANGFUSE_FLUSH_INTERVAL || "10000"
445
+ ),
418
446
  release: process.env.LANGFUSE_RELEASE,
419
- requestTimeout: Number.parseInt(process.env.LANGFUSE_REQUEST_TIMEOUT || "10000"),
447
+ requestTimeout: Number.parseInt(
448
+ process.env.LANGFUSE_REQUEST_TIMEOUT || "10000"
449
+ ),
420
450
  enabled: process.env.LANGFUSE_ENABLED !== "false",
421
451
  // Set trace name - can be customized via metadata.trace_name or defaults to 'mcp-use-agent'
422
452
  traceName: initialMetadata.trace_name || process.env.LANGFUSE_TRACE_NAME || "mcp-use-agent",
@@ -426,14 +456,29 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
426
456
  tags: initialTags.length > 0 ? initialTags : void 0,
427
457
  metadata: initialMetadata || void 0
428
458
  };
429
- logger.debug("Langfuse handler config:", JSON.stringify({
430
- traceName: config2.traceName,
431
- sessionId: config2.sessionId,
432
- userId: config2.userId,
433
- tags: config2.tags
434
- }, null, 2));
435
- langfuseState.handler = new LoggingCallbackHandler(config2, agentId, metadata, metadataProvider, tagsProvider);
436
- logger.debug("Langfuse observability initialized successfully with logging enabled");
459
+ logger.debug(
460
+ "Langfuse handler config:",
461
+ JSON.stringify(
462
+ {
463
+ traceName: config2.traceName,
464
+ sessionId: config2.sessionId,
465
+ userId: config2.userId,
466
+ tags: config2.tags
467
+ },
468
+ null,
469
+ 2
470
+ )
471
+ );
472
+ langfuseState.handler = new LoggingCallbackHandler(
473
+ config2,
474
+ agentId,
475
+ metadata,
476
+ metadataProvider,
477
+ tagsProvider
478
+ );
479
+ logger.debug(
480
+ "Langfuse observability initialized successfully with logging enabled"
481
+ );
437
482
  try {
438
483
  const langfuseCore = await import("langfuse").catch(() => null);
439
484
  if (langfuseCore) {
@@ -467,7 +512,9 @@ var init_langfuse = __esm({
467
512
  };
468
513
  __name(initializeLangfuse, "initializeLangfuse");
469
514
  if (langfuseDisabled) {
470
- logger.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable");
515
+ logger.debug(
516
+ "Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"
517
+ );
471
518
  } else if (!process.env.LANGFUSE_PUBLIC_KEY || !process.env.LANGFUSE_SECRET_KEY) {
472
519
  logger.debug(
473
520
  "Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"
@@ -605,7 +652,9 @@ var ConnectionManager = class {
605
652
  try {
606
653
  await this.closeConnection(this._connection);
607
654
  } catch (closeErr) {
608
- logger.warn(`Error closing connection in ${this.constructor.name}: ${closeErr}`);
655
+ logger.warn(
656
+ `Error closing connection in ${this.constructor.name}: ${closeErr}`
657
+ );
609
658
  }
610
659
  this._connection = null;
611
660
  }
@@ -738,6 +787,7 @@ var BaseConnector = class {
738
787
  client = null;
739
788
  connectionManager = null;
740
789
  toolsCache = null;
790
+ capabilitiesCache = null;
741
791
  connected = false;
742
792
  opts;
743
793
  constructor(opts = {}) {
@@ -771,9 +821,14 @@ var BaseConnector = class {
771
821
  }
772
822
  logger.debug("Caching server capabilities & tools");
773
823
  const capabilities = this.client.getServerCapabilities();
774
- const listToolsRes = await this.client.listTools(void 0, defaultRequestOptions);
824
+ this.capabilitiesCache = capabilities;
825
+ const listToolsRes = await this.client.listTools(
826
+ void 0,
827
+ defaultRequestOptions
828
+ );
775
829
  this.toolsCache = listToolsRes.tools ?? [];
776
830
  logger.debug(`Fetched ${this.toolsCache.length} tools from server`);
831
+ logger.debug("Server capabilities:", capabilities);
777
832
  return capabilities;
778
833
  }
779
834
  /** Lazily expose the cached tools list. */
@@ -789,13 +844,17 @@ var BaseConnector = class {
789
844
  throw new Error("MCP client is not connected");
790
845
  }
791
846
  logger.debug(`Calling tool '${name}' with args`, args);
792
- const res = await this.client.callTool({ name, arguments: args }, void 0, options);
847
+ const res = await this.client.callTool(
848
+ { name, arguments: args },
849
+ void 0,
850
+ options
851
+ );
793
852
  logger.debug(`Tool '${name}' returned`, res);
794
853
  return res;
795
854
  }
796
855
  /**
797
856
  * List resources from the server with optional pagination
798
- *
857
+ *
799
858
  * @param cursor - Optional cursor for pagination
800
859
  * @param options - Request options
801
860
  * @returns Resource list with optional nextCursor for pagination
@@ -809,7 +868,7 @@ var BaseConnector = class {
809
868
  }
810
869
  /**
811
870
  * List all resources from the server, automatically handling pagination
812
- *
871
+ *
813
872
  * @param options - Request options
814
873
  * @returns Complete list of all resources
815
874
  */
@@ -817,19 +876,31 @@ var BaseConnector = class {
817
876
  if (!this.client) {
818
877
  throw new Error("MCP client is not connected");
819
878
  }
820
- logger.debug("Listing all resources (with auto-pagination)");
821
- const allResources = [];
822
- let cursor = void 0;
823
- do {
824
- const result = await this.client.listResources({ cursor }, options);
825
- allResources.push(...result.resources || []);
826
- cursor = result.nextCursor;
827
- } while (cursor);
828
- return { resources: allResources };
879
+ if (!this.capabilitiesCache?.resources) {
880
+ logger.debug("Server does not advertise resources capability, skipping");
881
+ return { resources: [] };
882
+ }
883
+ try {
884
+ logger.debug("Listing all resources (with auto-pagination)");
885
+ const allResources = [];
886
+ let cursor = void 0;
887
+ do {
888
+ const result = await this.client.listResources({ cursor }, options);
889
+ allResources.push(...result.resources || []);
890
+ cursor = result.nextCursor;
891
+ } while (cursor);
892
+ return { resources: allResources };
893
+ } catch (err) {
894
+ if (err.code === -32601) {
895
+ logger.debug("Server advertised resources but method not found");
896
+ return { resources: [] };
897
+ }
898
+ throw err;
899
+ }
829
900
  }
830
901
  /**
831
902
  * List resource templates from the server
832
- *
903
+ *
833
904
  * @param options - Request options
834
905
  * @returns List of available resource templates
835
906
  */
@@ -847,11 +918,11 @@ var BaseConnector = class {
847
918
  }
848
919
  logger.debug(`Reading resource ${uri}`);
849
920
  const res = await this.client.readResource({ uri }, options);
850
- return { content: res.content, mimeType: res.mimeType };
921
+ return res;
851
922
  }
852
923
  /**
853
924
  * Subscribe to resource updates
854
- *
925
+ *
855
926
  * @param uri - URI of the resource to subscribe to
856
927
  * @param options - Request options
857
928
  */
@@ -864,7 +935,7 @@ var BaseConnector = class {
864
935
  }
865
936
  /**
866
937
  * Unsubscribe from resource updates
867
- *
938
+ *
868
939
  * @param uri - URI of the resource to unsubscribe from
869
940
  * @param options - Request options
870
941
  */
@@ -879,8 +950,20 @@ var BaseConnector = class {
879
950
  if (!this.client) {
880
951
  throw new Error("MCP client is not connected");
881
952
  }
882
- logger.debug("Listing prompt");
883
- return await this.client.listPrompts();
953
+ if (!this.capabilitiesCache?.prompts) {
954
+ logger.debug("Server does not advertise prompts capability, skipping");
955
+ return { prompts: [] };
956
+ }
957
+ try {
958
+ logger.debug("Listing prompts");
959
+ return await this.client.listPrompts();
960
+ } catch (err) {
961
+ if (err.code === -32601) {
962
+ logger.debug("Server advertised prompts but method not found");
963
+ return { prompts: [] };
964
+ }
965
+ throw err;
966
+ }
884
967
  }
885
968
  async getPrompt(name, args) {
886
969
  if (!this.client) {
@@ -895,7 +978,11 @@ var BaseConnector = class {
895
978
  throw new Error("MCP client is not connected");
896
979
  }
897
980
  logger.debug(`Sending raw request '${method}' with params`, params);
898
- return await this.client.request({ method, params: params ?? {} }, void 0, options);
981
+ return await this.client.request(
982
+ { method, params: params ?? {} },
983
+ void 0,
984
+ options
985
+ );
899
986
  }
900
987
  /**
901
988
  * Helper to tear down the client & connection manager safely.
@@ -954,7 +1041,10 @@ var HttpConnector = class extends BaseConnector {
954
1041
  }
955
1042
  this.timeout = opts.timeout ?? 3e4;
956
1043
  this.sseReadTimeout = opts.sseReadTimeout ?? 3e5;
957
- this.clientInfo = opts.clientInfo ?? { name: "http-connector", version: "1.0.0" };
1044
+ this.clientInfo = opts.clientInfo ?? {
1045
+ name: "http-connector",
1046
+ version: "1.0.0"
1047
+ };
958
1048
  this.preferSse = opts.preferSse ?? false;
959
1049
  }
960
1050
  /** Establish connection to the MCP implementation via HTTP (streamable or SSE). */
@@ -976,7 +1066,9 @@ var HttpConnector = class extends BaseConnector {
976
1066
  logger.info("\u2705 Successfully connected via streamable HTTP");
977
1067
  } catch (err) {
978
1068
  let fallbackReason = "Unknown error";
1069
+ let is401Error = false;
979
1070
  if (err instanceof import_streamableHttp2.StreamableHTTPError) {
1071
+ is401Error = err.code === 401;
980
1072
  if (err.code === 400 && err.message.includes("Missing session ID")) {
981
1073
  fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
982
1074
  logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
@@ -990,6 +1082,7 @@ var HttpConnector = class extends BaseConnector {
990
1082
  } else if (err instanceof Error) {
991
1083
  const errorStr = err.toString();
992
1084
  const errorMsg = err.message || "";
1085
+ is401Error = errorStr.includes("401") || errorMsg.includes("Unauthorized");
993
1086
  if (errorStr.includes("Missing session ID") || errorStr.includes("Bad Request: Missing session ID") || errorMsg.includes("FastMCP session ID error")) {
994
1087
  fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
995
1088
  logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
@@ -1001,6 +1094,13 @@ var HttpConnector = class extends BaseConnector {
1001
1094
  logger.debug(fallbackReason);
1002
1095
  }
1003
1096
  }
1097
+ if (is401Error) {
1098
+ logger.info("Authentication required - skipping SSE fallback");
1099
+ await this.cleanupResources();
1100
+ const authError = new Error("Authentication required");
1101
+ authError.code = 401;
1102
+ throw authError;
1103
+ }
1004
1104
  logger.info("\u{1F504} Falling back to SSE transport...");
1005
1105
  try {
1006
1106
  await this.connectWithSse(baseUrl);
@@ -1009,27 +1109,34 @@ var HttpConnector = class extends BaseConnector {
1009
1109
  logger.error(` Streamable HTTP: ${fallbackReason}`);
1010
1110
  logger.error(` SSE: ${sseErr}`);
1011
1111
  await this.cleanupResources();
1012
- throw new Error("Could not connect to server with any available transport");
1112
+ const sseIs401 = sseErr?.message?.includes("401") || sseErr?.message?.includes("Unauthorized");
1113
+ if (sseIs401) {
1114
+ const authError = new Error("Authentication required");
1115
+ authError.code = 401;
1116
+ throw authError;
1117
+ }
1118
+ throw new Error(
1119
+ "Could not connect to server with any available transport"
1120
+ );
1013
1121
  }
1014
1122
  }
1015
1123
  }
1016
1124
  async connectWithStreamableHttp(baseUrl) {
1017
1125
  try {
1018
- this.connectionManager = new StreamableHttpConnectionManager(
1019
- baseUrl,
1020
- {
1021
- requestInit: {
1022
- headers: this.headers
1023
- },
1024
- // Pass through timeout and other options
1025
- reconnectionOptions: {
1026
- maxReconnectionDelay: 3e4,
1027
- initialReconnectionDelay: 1e3,
1028
- reconnectionDelayGrowFactor: 1.5,
1029
- maxRetries: 2
1030
- }
1126
+ this.connectionManager = new StreamableHttpConnectionManager(baseUrl, {
1127
+ authProvider: this.opts.authProvider,
1128
+ // ← Pass OAuth provider to SDK
1129
+ requestInit: {
1130
+ headers: this.headers
1131
+ },
1132
+ // Pass through timeout and other options
1133
+ reconnectionOptions: {
1134
+ maxReconnectionDelay: 3e4,
1135
+ initialReconnectionDelay: 1e3,
1136
+ reconnectionDelayGrowFactor: 1.5,
1137
+ maxRetries: 2
1031
1138
  }
1032
- );
1139
+ });
1033
1140
  const transport = await this.connectionManager.start();
1034
1141
  this.client = new import_client.Client(this.clientInfo, this.opts.clientOptions);
1035
1142
  try {
@@ -1038,7 +1145,9 @@ var HttpConnector = class extends BaseConnector {
1038
1145
  if (connectErr instanceof Error) {
1039
1146
  const errMsg = connectErr.message || connectErr.toString();
1040
1147
  if (errMsg.includes("Missing session ID") || errMsg.includes("Bad Request: Missing session ID")) {
1041
- const wrappedError = new Error(`FastMCP session ID error: ${errMsg}`);
1148
+ const wrappedError = new Error(
1149
+ `FastMCP session ID error: ${errMsg}`
1150
+ );
1042
1151
  wrappedError.cause = connectErr;
1043
1152
  throw wrappedError;
1044
1153
  }
@@ -1047,7 +1156,9 @@ var HttpConnector = class extends BaseConnector {
1047
1156
  }
1048
1157
  this.connected = true;
1049
1158
  this.transportType = "streamable-http";
1050
- logger.debug(`Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`);
1159
+ logger.debug(
1160
+ `Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`
1161
+ );
1051
1162
  } catch (err) {
1052
1163
  await this.cleanupResources();
1053
1164
  throw err;
@@ -1055,20 +1166,19 @@ var HttpConnector = class extends BaseConnector {
1055
1166
  }
1056
1167
  async connectWithSse(baseUrl) {
1057
1168
  try {
1058
- this.connectionManager = new SseConnectionManager(
1059
- baseUrl,
1060
- {
1061
- requestInit: {
1062
- headers: this.headers
1063
- }
1169
+ this.connectionManager = new SseConnectionManager(baseUrl, {
1170
+ requestInit: {
1171
+ headers: this.headers
1064
1172
  }
1065
- );
1173
+ });
1066
1174
  const transport = await this.connectionManager.start();
1067
1175
  this.client = new import_client.Client(this.clientInfo, this.opts.clientOptions);
1068
1176
  await this.client.connect(transport);
1069
1177
  this.connected = true;
1070
1178
  this.transportType = "sse";
1071
- logger.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`);
1179
+ logger.debug(
1180
+ `Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`
1181
+ );
1072
1182
  } catch (err) {
1073
1183
  await this.cleanupResources();
1074
1184
  throw err;
@@ -1116,7 +1226,9 @@ var WebSocketConnectionManager = class extends ConnectionManager {
1116
1226
  async establishConnection() {
1117
1227
  logger.debug(`Connecting to WebSocket: ${this.url}`);
1118
1228
  return new Promise((resolve, reject) => {
1119
- const ws = new import_ws.default(this.url, { headers: this.headers });
1229
+ const ws = new import_ws.default(this.url, {
1230
+ headers: this.headers
1231
+ });
1120
1232
  this._ws = ws;
1121
1233
  const onOpen = /* @__PURE__ */ __name(() => {
1122
1234
  cleanup();
@@ -1176,8 +1288,7 @@ var WebSocketConnector = class extends BaseConnector {
1176
1288
  super();
1177
1289
  this.url = url;
1178
1290
  this.headers = { ...opts.headers ?? {} };
1179
- if (opts.authToken)
1180
- this.headers.Authorization = `Bearer ${opts.authToken}`;
1291
+ if (opts.authToken) this.headers.Authorization = `Bearer ${opts.authToken}`;
1181
1292
  }
1182
1293
  async connect() {
1183
1294
  if (this.connected) {
@@ -1186,7 +1297,10 @@ var WebSocketConnector = class extends BaseConnector {
1186
1297
  }
1187
1298
  logger.debug(`Connecting via WebSocket: ${this.url}`);
1188
1299
  try {
1189
- this.connectionManager = new WebSocketConnectionManager(this.url, this.headers);
1300
+ this.connectionManager = new WebSocketConnectionManager(
1301
+ this.url,
1302
+ this.headers
1303
+ );
1190
1304
  this.ws = await this.connectionManager.start();
1191
1305
  this.receiverTask = this.receiveLoop();
1192
1306
  this.connected = true;
@@ -1207,8 +1321,7 @@ var WebSocketConnector = class extends BaseConnector {
1207
1321
  this.connected = false;
1208
1322
  }
1209
1323
  sendRequest(method, params = null) {
1210
- if (!this.ws)
1211
- throw new Error("WebSocket is not connected");
1324
+ if (!this.ws) throw new Error("WebSocket is not connected");
1212
1325
  const id = (0, import_uuid.v4)();
1213
1326
  const payload = JSON.stringify({ id, method, params: params ?? {} });
1214
1327
  return new Promise((resolve, reject) => {
@@ -1222,8 +1335,7 @@ var WebSocketConnector = class extends BaseConnector {
1222
1335
  });
1223
1336
  }
1224
1337
  async receiveLoop() {
1225
- if (!this.ws)
1226
- return;
1338
+ if (!this.ws) return;
1227
1339
  const socket = this.ws;
1228
1340
  const onMessage = /* @__PURE__ */ __name((msg) => {
1229
1341
  let data;
@@ -1237,10 +1349,8 @@ var WebSocketConnector = class extends BaseConnector {
1237
1349
  if (id && this.pending.has(id)) {
1238
1350
  const { resolve, reject } = this.pending.get(id);
1239
1351
  this.pending.delete(id);
1240
- if ("result" in data)
1241
- resolve(data.result);
1242
- else if ("error" in data)
1243
- reject(data.error);
1352
+ if ("result" in data) resolve(data.result);
1353
+ else if ("error" in data) reject(data.error);
1244
1354
  } else {
1245
1355
  logger.debug("Received unsolicited message", data);
1246
1356
  }
@@ -1292,20 +1402,18 @@ var WebSocketConnector = class extends BaseConnector {
1292
1402
  }
1293
1403
  async readResource(uri) {
1294
1404
  const res = await this.sendRequest("resources/read", { uri });
1295
- return { content: res.content, mimeType: res.mimeType };
1405
+ return res;
1296
1406
  }
1297
1407
  async request(method, params = null) {
1298
1408
  return await this.sendRequest(method, params);
1299
1409
  }
1300
1410
  get tools() {
1301
- if (!this.toolsCache)
1302
- throw new Error("MCP client is not initialized");
1411
+ if (!this.toolsCache) throw new Error("MCP client is not initialized");
1303
1412
  return this.toolsCache;
1304
1413
  }
1305
1414
  async cleanupResources() {
1306
- if (this.receiverTask)
1307
- await this.receiverTask.catch(() => {
1308
- });
1415
+ if (this.receiverTask) await this.receiverTask.catch(() => {
1416
+ });
1309
1417
  this.receiverTask = null;
1310
1418
  this.rejectAll(new Error("WebSocket disconnected"));
1311
1419
  if (this.connectionManager) {
@@ -1433,7 +1541,9 @@ var BaseMCPClient = class {
1433
1541
  async closeSession(serverName) {
1434
1542
  const session = this.sessions[serverName];
1435
1543
  if (!session) {
1436
- logger.warn(`No session exists for server ${serverName}, nothing to close`);
1544
+ logger.warn(
1545
+ `No session exists for server ${serverName}, nothing to close`
1546
+ );
1437
1547
  return;
1438
1548
  }
1439
1549
  try {
@@ -1460,7 +1570,9 @@ var BaseMCPClient = class {
1460
1570
  }
1461
1571
  }
1462
1572
  if (errors.length) {
1463
- logger.error(`Encountered ${errors.length} errors while closing sessions`);
1573
+ logger.error(
1574
+ `Encountered ${errors.length} errors while closing sessions`
1575
+ );
1464
1576
  } else {
1465
1577
  logger.debug("All sessions closed successfully");
1466
1578
  }
@@ -1483,13 +1595,15 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
1483
1595
  * Supports HTTP and WebSocket connectors only
1484
1596
  */
1485
1597
  createConnectorFromConfig(serverConfig) {
1486
- const { url, transport, headers, authToken } = serverConfig;
1598
+ const { url, transport, headers, authToken, authProvider } = serverConfig;
1487
1599
  if (!url) {
1488
1600
  throw new Error("Server URL is required");
1489
1601
  }
1490
1602
  const connectorOptions = {
1491
1603
  headers,
1492
- authToken
1604
+ authToken,
1605
+ authProvider
1606
+ // ← Pass OAuth provider to connector
1493
1607
  };
1494
1608
  if (transport === "websocket" || url.startsWith("ws://") || url.startsWith("wss://")) {
1495
1609
  return new WebSocketConnector(url, connectorOptions);
@@ -1656,9 +1770,14 @@ var LangChainAdapter = class extends BaseAdapter {
1656
1770
  // Blank is acceptable but discouraged.
1657
1771
  schema: argsSchema,
1658
1772
  func: /* @__PURE__ */ __name(async (input) => {
1659
- logger.debug(`MCP tool "${mcpTool.name}" received input: ${JSON.stringify(input)}`);
1773
+ logger.debug(
1774
+ `MCP tool "${mcpTool.name}" received input: ${JSON.stringify(input)}`
1775
+ );
1660
1776
  try {
1661
- const result = await connector.callTool(mcpTool.name, input);
1777
+ const result = await connector.callTool(
1778
+ mcpTool.name,
1779
+ input
1780
+ );
1662
1781
  return JSON.stringify(result);
1663
1782
  } catch (err) {
1664
1783
  logger.error(`Error executing MCP tool: ${err.message}`);
@@ -1818,7 +1937,9 @@ var ConnectMCPServerTool = class extends MCPServerTool {
1818
1937
  const numTools = serverTools.length;
1819
1938
  return `Connected to MCP server '${serverName}'. ${numTools} tools are now available.`;
1820
1939
  } catch (error) {
1821
- logger.error(`Error connecting to server '${serverName}': ${String(error)}`);
1940
+ logger.error(
1941
+ `Error connecting to server '${serverName}': ${String(error)}`
1942
+ );
1822
1943
  return `Failed to connect to server '${serverName}': ${String(error)}`;
1823
1944
  }
1824
1945
  }
@@ -1854,7 +1975,9 @@ var ListMCPServersTool = class extends MCPServerTool {
1854
1975
  outputLines.push(`${numberOfTools} tools available for this server
1855
1976
  `);
1856
1977
  } catch (error) {
1857
- logger.error(`Unexpected error listing tools for server '${serverName}': ${String(error)}`);
1978
+ logger.error(
1979
+ `Unexpected error listing tools for server '${serverName}': ${String(error)}`
1980
+ );
1858
1981
  }
1859
1982
  }
1860
1983
  return outputLines.join("\n");
@@ -1915,10 +2038,10 @@ var ServerManager = class {
1915
2038
  }
1916
2039
  const tableData = allServerNames.map((name) => ({
1917
2040
  "Server Name": name,
1918
- "Connected": activeSessionNames.includes(name) ? "\u2705" : "\u274C",
1919
- "Initialized": this.initializedServers[name] ? "\u2705" : "\u274C",
2041
+ Connected: activeSessionNames.includes(name) ? "\u2705" : "\u274C",
2042
+ Initialized: this.initializedServers[name] ? "\u2705" : "\u274C",
1920
2043
  "Tool Count": this.serverTools[name]?.length ?? 0,
1921
- "Active": this.activeServer === name ? "\u2705" : "\u274C"
2044
+ Active: this.activeServer === name ? "\u2705" : "\u274C"
1922
2045
  }));
1923
2046
  logger.info(`Server Manager State: [${context}]`);
1924
2047
  console.table(tableData);
@@ -1935,13 +2058,19 @@ var ServerManager = class {
1935
2058
  try {
1936
2059
  let session = null;
1937
2060
  session = this.client.getSession(serverName);
1938
- logger.debug(`Using existing session for server '${serverName}' to prefetch tools.`);
2061
+ logger.debug(
2062
+ `Using existing session for server '${serverName}' to prefetch tools.`
2063
+ );
1939
2064
  if (!session) {
1940
2065
  session = await this.client.createSession(serverName).catch((createSessionError) => {
1941
- logger.warn(`Could not create session for '${serverName}' during prefetch: ${createSessionError}`);
2066
+ logger.warn(
2067
+ `Could not create session for '${serverName}' during prefetch: ${createSessionError}`
2068
+ );
1942
2069
  return null;
1943
2070
  });
1944
- logger.debug(`Temporarily created session for '${serverName}' to prefetch tools.`);
2071
+ logger.debug(
2072
+ `Temporarily created session for '${serverName}' to prefetch tools.`
2073
+ );
1945
2074
  }
1946
2075
  if (session) {
1947
2076
  const connector = session.connector;
@@ -1949,7 +2078,9 @@ var ServerManager = class {
1949
2078
  try {
1950
2079
  tools = await this.adapter.createToolsFromConnectors([connector]);
1951
2080
  } catch (toolFetchError) {
1952
- logger.error(`Failed to create tools from connector for server '${serverName}': ${toolFetchError}`);
2081
+ logger.error(
2082
+ `Failed to create tools from connector for server '${serverName}': ${toolFetchError}`
2083
+ );
1953
2084
  continue;
1954
2085
  }
1955
2086
  const cachedTools = this.serverTools[serverName];
@@ -1957,7 +2088,9 @@ var ServerManager = class {
1957
2088
  if (toolsChanged) {
1958
2089
  this.serverTools[serverName] = tools;
1959
2090
  this.initializedServers[serverName] = true;
1960
- logger.debug(`Prefetched ${tools.length} tools for server '${serverName}'.`);
2091
+ logger.debug(
2092
+ `Prefetched ${tools.length} tools for server '${serverName}'.`
2093
+ );
1961
2094
  } else {
1962
2095
  logger.debug(
1963
2096
  `Tools for server '${serverName}' unchanged, using cached version.`
@@ -1965,7 +2098,9 @@ var ServerManager = class {
1965
2098
  }
1966
2099
  }
1967
2100
  } catch (outerError) {
1968
- logger.error(`Error prefetching tools for server '${serverName}': ${outerError}`);
2101
+ logger.error(
2102
+ `Error prefetching tools for server '${serverName}': ${outerError}`
2103
+ );
1969
2104
  }
1970
2105
  }
1971
2106
  }
@@ -2031,8 +2166,15 @@ var ObservabilityManager = class {
2031
2166
  const { langfuseHandler: langfuseHandler2, langfuseInitPromise: langfuseInitPromise2 } = await Promise.resolve().then(() => (init_langfuse(), langfuse_exports));
2032
2167
  if (this.agentId || this.metadata || this.metadataProvider || this.tagsProvider) {
2033
2168
  const { initializeLangfuse: initializeLangfuse2 } = await Promise.resolve().then(() => (init_langfuse(), langfuse_exports));
2034
- await initializeLangfuse2(this.agentId, this.metadata, this.metadataProvider, this.tagsProvider);
2035
- logger.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`);
2169
+ await initializeLangfuse2(
2170
+ this.agentId,
2171
+ this.metadata,
2172
+ this.metadataProvider,
2173
+ this.tagsProvider
2174
+ );
2175
+ logger.debug(
2176
+ `ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`
2177
+ );
2036
2178
  } else {
2037
2179
  const initPromise = langfuseInitPromise2();
2038
2180
  if (initPromise) {
@@ -2056,16 +2198,22 @@ var ObservabilityManager = class {
2056
2198
  */
2057
2199
  async getCallbacks() {
2058
2200
  if (!this.observe) {
2059
- logger.debug("ObservabilityManager: Observability disabled via observe=false");
2201
+ logger.debug(
2202
+ "ObservabilityManager: Observability disabled via observe=false"
2203
+ );
2060
2204
  return [];
2061
2205
  }
2062
2206
  if (this.customCallbacks) {
2063
- logger.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`);
2207
+ logger.debug(
2208
+ `ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`
2209
+ );
2064
2210
  return this.customCallbacks;
2065
2211
  }
2066
2212
  await this.collectAvailableHandlers();
2067
2213
  if (this.availableHandlers.length > 0) {
2068
- logger.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`);
2214
+ logger.debug(
2215
+ `ObservabilityManager: Using ${this.availableHandlers.length} handlers`
2216
+ );
2069
2217
  } else {
2070
2218
  logger.debug("ObservabilityManager: No callbacks configured");
2071
2219
  }
@@ -2122,7 +2270,9 @@ var ObservabilityManager = class {
2122
2270
  this.customCallbacks = [];
2123
2271
  }
2124
2272
  this.customCallbacks.push(callback);
2125
- logger.debug(`ObservabilityManager: Added custom callback: ${callback.constructor.name}`);
2273
+ logger.debug(
2274
+ `ObservabilityManager: Added custom callback: ${callback.constructor.name}`
2275
+ );
2126
2276
  }
2127
2277
  /**
2128
2278
  * Clear all custom callbacks.
@@ -2254,7 +2404,15 @@ function getModelName(llm) {
2254
2404
  if ("_identifyingParams" in llm) {
2255
2405
  const identifyingParams = llm._identifyingParams;
2256
2406
  if (typeof identifyingParams === "object" && identifyingParams !== null) {
2257
- for (const key of ["model", "modelName", "model_name", "modelId", "model_id", "deploymentName", "deployment_name"]) {
2407
+ for (const key of [
2408
+ "model",
2409
+ "modelName",
2410
+ "model_name",
2411
+ "modelId",
2412
+ "model_id",
2413
+ "deploymentName",
2414
+ "deployment_name"
2415
+ ]) {
2258
2416
  if (key in identifyingParams) {
2259
2417
  return String(identifyingParams[key]);
2260
2418
  }
@@ -2345,8 +2503,16 @@ var Telemetry = class _Telemetry {
2345
2503
  __name(this, "Telemetry");
2346
2504
  }
2347
2505
  static instance = null;
2348
- USER_ID_PATH = path2.join(getCacheHome(), "mcp_use_3", "telemetry_user_id");
2349
- VERSION_DOWNLOAD_PATH = path2.join(getCacheHome(), "mcp_use", "download_version");
2506
+ USER_ID_PATH = path2.join(
2507
+ getCacheHome(),
2508
+ "mcp_use_3",
2509
+ "telemetry_user_id"
2510
+ );
2511
+ VERSION_DOWNLOAD_PATH = path2.join(
2512
+ getCacheHome(),
2513
+ "mcp_use",
2514
+ "download_version"
2515
+ );
2350
2516
  PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
2351
2517
  HOST = "https://eu.i.posthog.com";
2352
2518
  SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
@@ -2366,17 +2532,18 @@ var Telemetry = class _Telemetry {
2366
2532
  } else if (!isNodeJS) {
2367
2533
  this._posthogClient = null;
2368
2534
  this._scarfClient = null;
2369
- logger.debug("Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)");
2535
+ logger.debug(
2536
+ "Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)"
2537
+ );
2370
2538
  } else {
2371
- logger.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable.");
2539
+ logger.info(
2540
+ "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
2541
+ );
2372
2542
  try {
2373
- this._posthogClient = new import_posthog_node.PostHog(
2374
- this.PROJECT_API_KEY,
2375
- {
2376
- host: this.HOST,
2377
- disableGeoip: false
2378
- }
2379
- );
2543
+ this._posthogClient = new import_posthog_node.PostHog(this.PROJECT_API_KEY, {
2544
+ host: this.HOST,
2545
+ disableGeoip: false
2546
+ });
2380
2547
  } catch (e) {
2381
2548
  logger.warn(`Failed to initialize PostHog telemetry: ${e}`);
2382
2549
  this._posthogClient = null;
@@ -2486,7 +2653,9 @@ var Telemetry = class _Telemetry {
2486
2653
  if (!fs2.existsSync(this.VERSION_DOWNLOAD_PATH)) {
2487
2654
  shouldTrack = true;
2488
2655
  firstDownload = true;
2489
- fs2.mkdirSync(path2.dirname(this.VERSION_DOWNLOAD_PATH), { recursive: true });
2656
+ fs2.mkdirSync(path2.dirname(this.VERSION_DOWNLOAD_PATH), {
2657
+ recursive: true
2658
+ });
2490
2659
  fs2.writeFileSync(this.VERSION_DOWNLOAD_PATH, currentVersion);
2491
2660
  } else {
2492
2661
  const savedVersion = fs2.readFileSync(this.VERSION_DOWNLOAD_PATH, "utf-8").trim();
@@ -2497,7 +2666,9 @@ var Telemetry = class _Telemetry {
2497
2666
  }
2498
2667
  }
2499
2668
  if (shouldTrack) {
2500
- logger.debug(`Tracking package download event with properties: ${JSON.stringify(properties)}`);
2669
+ logger.debug(
2670
+ `Tracking package download event with properties: ${JSON.stringify(properties)}`
2671
+ );
2501
2672
  const eventProperties = { ...properties || {} };
2502
2673
  eventProperties.mcp_use_version = currentVersion;
2503
2674
  eventProperties.user_id = this.userId;
@@ -2549,8 +2720,7 @@ function generateToolDescriptions(tools, disallowedTools) {
2549
2720
  const disallowedSet = new Set(disallowedTools ?? []);
2550
2721
  const descriptions = [];
2551
2722
  for (const tool of tools) {
2552
- if (disallowedSet.has(tool.name))
2553
- continue;
2723
+ if (disallowedSet.has(tool.name)) continue;
2554
2724
  const escaped = tool.description.replace(/\{/g, "{{").replace(/\}/g, "}}");
2555
2725
  descriptions.push(`- ${tool.name}: ${escaped}`);
2556
2726
  }
@@ -2563,7 +2733,9 @@ function buildSystemPromptContent(template, toolDescriptionLines, additionalInst
2563
2733
  if (template.includes("{tool_descriptions}")) {
2564
2734
  content = template.replace("{tool_descriptions}", block);
2565
2735
  } else {
2566
- console.warn("`{tool_descriptions}` placeholder not found; appending at end.");
2736
+ console.warn(
2737
+ "`{tool_descriptions}` placeholder not found; appending at end."
2738
+ );
2567
2739
  content = `${template}
2568
2740
 
2569
2741
  Available tools:
@@ -2719,7 +2891,9 @@ var RemoteAgent = class {
2719
2891
  `Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`
2720
2892
  );
2721
2893
  }
2722
- throw new Error(`Failed to create chat session: ${statusCode} - ${responseText}`);
2894
+ throw new Error(
2895
+ `Failed to create chat session: ${statusCode} - ${responseText}`
2896
+ );
2723
2897
  }
2724
2898
  const chatData = await response.json();
2725
2899
  const chatId = chatData.id;
@@ -2792,8 +2966,12 @@ var RemoteAgent = class {
2792
2966
  "Internal server error occurred during agent execution. Please try again later or contact support if the issue persists."
2793
2967
  );
2794
2968
  } else {
2795
- logger.error(`\u274C Remote execution failed with status ${statusCode}: ${responseText}`);
2796
- throw new Error(`Remote agent execution failed: ${statusCode} - ${responseText}`);
2969
+ logger.error(
2970
+ `\u274C Remote execution failed with status ${statusCode}: ${responseText}`
2971
+ );
2972
+ throw new Error(
2973
+ `Remote agent execution failed: ${statusCode} - ${responseText}`
2974
+ );
2797
2975
  }
2798
2976
  }
2799
2977
  const result = await response.json();
@@ -2844,7 +3022,13 @@ Raw error: ${result}`
2844
3022
  }
2845
3023
  // eslint-disable-next-line require-yield
2846
3024
  async *stream(query, maxSteps, manageConnector, externalHistory, outputSchema) {
2847
- const result = await this.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
3025
+ const result = await this.run(
3026
+ query,
3027
+ maxSteps,
3028
+ manageConnector,
3029
+ externalHistory,
3030
+ outputSchema
3031
+ );
2848
3032
  return result;
2849
3033
  }
2850
3034
  async close() {
@@ -2920,7 +3104,9 @@ var MCPAgent = class {
2920
3104
  return;
2921
3105
  }
2922
3106
  if (!options.llm) {
2923
- throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");
3107
+ throw new Error(
3108
+ "llm is required for local execution. For remote execution, provide agentId instead."
3109
+ );
2924
3110
  }
2925
3111
  this.llm = options.llm;
2926
3112
  this.client = options.client;
@@ -2938,11 +3124,15 @@ var MCPAgent = class {
2938
3124
  this.verbose = options.verbose ?? false;
2939
3125
  this.observe = options.observe ?? true;
2940
3126
  if (!this.client && this.connectors.length === 0) {
2941
- throw new Error("Either 'client' or at least one 'connector' must be provided.");
3127
+ throw new Error(
3128
+ "Either 'client' or at least one 'connector' must be provided."
3129
+ );
2942
3130
  }
2943
3131
  if (this.useServerManager) {
2944
3132
  if (!this.client) {
2945
- throw new Error("'client' must be provided when 'useServerManager' is true.");
3133
+ throw new Error(
3134
+ "'client' must be provided when 'useServerManager' is true."
3135
+ );
2946
3136
  }
2947
3137
  this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
2948
3138
  this.serverManager = options.serverManagerFactory?.(this.client) ?? new ServerManager(this.client, this.adapter);
@@ -3002,25 +3192,37 @@ var MCPAgent = class {
3002
3192
  } else {
3003
3193
  if (this.client) {
3004
3194
  this.sessions = this.client.getAllActiveSessions();
3005
- logger.info(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`);
3195
+ logger.info(
3196
+ `\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`
3197
+ );
3006
3198
  if (Object.keys(this.sessions).length === 0) {
3007
3199
  logger.info("\u{1F504} No active sessions found, creating new ones...");
3008
3200
  this.sessions = await this.client.createAllSessions();
3009
- logger.info(`\u2705 Created ${Object.keys(this.sessions).length} new sessions`);
3201
+ logger.info(
3202
+ `\u2705 Created ${Object.keys(this.sessions).length} new sessions`
3203
+ );
3010
3204
  }
3011
3205
  this._tools = await LangChainAdapter.createTools(this.client);
3012
3206
  this._tools.push(...this.additionalTools);
3013
- logger.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain tools from client`);
3207
+ logger.info(
3208
+ `\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain tools from client`
3209
+ );
3014
3210
  } else {
3015
- logger.info(`\u{1F517} Connecting to ${this.connectors.length} direct connectors...`);
3211
+ logger.info(
3212
+ `\u{1F517} Connecting to ${this.connectors.length} direct connectors...`
3213
+ );
3016
3214
  for (const connector of this.connectors) {
3017
3215
  if (!connector.isClientConnected) {
3018
3216
  await connector.connect();
3019
3217
  }
3020
3218
  }
3021
- this._tools = await this.adapter.createToolsFromConnectors(this.connectors);
3219
+ this._tools = await this.adapter.createToolsFromConnectors(
3220
+ this.connectors
3221
+ );
3022
3222
  this._tools.push(...this.additionalTools);
3023
- logger.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain tools from connectors`);
3223
+ logger.info(
3224
+ `\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain tools from connectors`
3225
+ );
3024
3226
  }
3025
3227
  logger.info(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`);
3026
3228
  await this.createSystemMessageFromTools(this._tools);
@@ -3030,7 +3232,9 @@ var MCPAgent = class {
3030
3232
  const mcpServerInfo = this.getMCPServerInfo();
3031
3233
  if (Object.keys(mcpServerInfo).length > 0) {
3032
3234
  this.setMetadata(mcpServerInfo);
3033
- logger.debug(`MCP server info added to metadata: ${JSON.stringify(mcpServerInfo)}`);
3235
+ logger.debug(
3236
+ `MCP server info added to metadata: ${JSON.stringify(mcpServerInfo)}`
3237
+ );
3034
3238
  }
3035
3239
  logger.info("\u2728 Agent initialization complete");
3036
3240
  }
@@ -3048,7 +3252,9 @@ var MCPAgent = class {
3048
3252
  if (this.memoryEnabled) {
3049
3253
  this.conversationHistory = [
3050
3254
  this.systemMessage,
3051
- ...this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage))
3255
+ ...this.conversationHistory.filter(
3256
+ (m) => !(m instanceof import_langchain2.SystemMessage)
3257
+ )
3052
3258
  ];
3053
3259
  }
3054
3260
  }
@@ -3066,7 +3272,9 @@ var MCPAgent = class {
3066
3272
  systemPrompt: systemContent,
3067
3273
  middleware
3068
3274
  });
3069
- logger.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`);
3275
+ logger.debug(
3276
+ `Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`
3277
+ );
3070
3278
  return agent;
3071
3279
  }
3072
3280
  getConversationHistory() {
@@ -3076,8 +3284,7 @@ var MCPAgent = class {
3076
3284
  this.conversationHistory = this.memoryEnabled && this.systemMessage ? [this.systemMessage] : [];
3077
3285
  }
3078
3286
  addToHistory(message) {
3079
- if (this.memoryEnabled)
3080
- this.conversationHistory.push(message);
3287
+ if (this.memoryEnabled) this.conversationHistory.push(message);
3081
3288
  }
3082
3289
  getSystemMessage() {
3083
3290
  return this.systemMessage;
@@ -3085,7 +3292,9 @@ var MCPAgent = class {
3085
3292
  setSystemMessage(message) {
3086
3293
  this.systemMessage = new import_langchain2.SystemMessage(message);
3087
3294
  if (this.memoryEnabled) {
3088
- this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage));
3295
+ this.conversationHistory = this.conversationHistory.filter(
3296
+ (m) => !(m instanceof import_langchain2.SystemMessage)
3297
+ );
3089
3298
  this.conversationHistory.unshift(this.systemMessage);
3090
3299
  }
3091
3300
  if (this._initialized && this._tools.length) {
@@ -3097,7 +3306,9 @@ var MCPAgent = class {
3097
3306
  this.disallowedTools = disallowedTools;
3098
3307
  this.adapter = new LangChainAdapter(this.disallowedTools);
3099
3308
  if (this._initialized) {
3100
- logger.debug("Agent already initialized. Changes will take effect on next initialization.");
3309
+ logger.debug(
3310
+ "Agent already initialized. Changes will take effect on next initialization."
3311
+ );
3101
3312
  }
3102
3313
  }
3103
3314
  getDisallowedTools() {
@@ -3163,16 +3374,22 @@ var MCPAgent = class {
3163
3374
  try {
3164
3375
  const serialized = JSON.stringify(value);
3165
3376
  if (serialized.length > 1e3) {
3166
- logger.warn(`Metadata value for key '${sanitizedKey}' is too large. Truncating.`);
3377
+ logger.warn(
3378
+ `Metadata value for key '${sanitizedKey}' is too large. Truncating.`
3379
+ );
3167
3380
  sanitized[sanitizedKey] = `${serialized.substring(0, 1e3)}...`;
3168
3381
  } else {
3169
3382
  sanitized[sanitizedKey] = value;
3170
3383
  }
3171
3384
  } catch (error) {
3172
- logger.warn(`Failed to serialize metadata value for key '${sanitizedKey}': ${error}. Skipping.`);
3385
+ logger.warn(
3386
+ `Failed to serialize metadata value for key '${sanitizedKey}': ${error}. Skipping.`
3387
+ );
3173
3388
  }
3174
3389
  } else {
3175
- logger.warn(`Unsupported metadata value type for key '${sanitizedKey}': ${typeof value}. Skipping.`);
3390
+ logger.warn(
3391
+ `Unsupported metadata value type for key '${sanitizedKey}': ${typeof value}. Skipping.`
3392
+ );
3176
3393
  }
3177
3394
  }
3178
3395
  return sanitized;
@@ -3219,15 +3436,24 @@ var MCPAgent = class {
3219
3436
  };
3220
3437
  }
3221
3438
  } catch (error) {
3222
- logger.warn(`Failed to get config for server '${serverName}': ${error}`);
3223
- serverConfigs[serverName] = { type: "error", error: "config_unavailable" };
3439
+ logger.warn(
3440
+ `Failed to get config for server '${serverName}': ${error}`
3441
+ );
3442
+ serverConfigs[serverName] = {
3443
+ type: "error",
3444
+ error: "config_unavailable"
3445
+ };
3224
3446
  }
3225
3447
  }
3226
3448
  serverInfo.mcp_server_configs = serverConfigs;
3227
3449
  } else if (this.connectors && this.connectors.length > 0) {
3228
3450
  serverInfo.mcp_servers_count = this.connectors.length;
3229
- serverInfo.mcp_server_names = this.connectors.map((c) => c.publicIdentifier);
3230
- serverInfo.mcp_server_types = this.connectors.map((c) => c.constructor.name);
3451
+ serverInfo.mcp_server_names = this.connectors.map(
3452
+ (c) => c.publicIdentifier
3453
+ );
3454
+ serverInfo.mcp_server_types = this.connectors.map(
3455
+ (c) => c.constructor.name
3456
+ );
3231
3457
  }
3232
3458
  } catch (error) {
3233
3459
  logger.warn(`Failed to collect MCP server info: ${error}`);
@@ -3281,7 +3507,13 @@ var MCPAgent = class {
3281
3507
  }
3282
3508
  async run(query, maxSteps, manageConnector, externalHistory, outputSchema) {
3283
3509
  if (this.isRemote && this.remoteAgent) {
3284
- return this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
3510
+ return this.remoteAgent.run(
3511
+ query,
3512
+ maxSteps,
3513
+ manageConnector,
3514
+ externalHistory,
3515
+ outputSchema
3516
+ );
3285
3517
  }
3286
3518
  const generator = this.stream(
3287
3519
  query,
@@ -3294,7 +3526,13 @@ var MCPAgent = class {
3294
3526
  }
3295
3527
  async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
3296
3528
  if (this.isRemote && this.remoteAgent) {
3297
- const result = await this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
3529
+ const result = await this.remoteAgent.run(
3530
+ query,
3531
+ maxSteps,
3532
+ manageConnector,
3533
+ externalHistory,
3534
+ outputSchema
3535
+ );
3298
3536
  return result;
3299
3537
  }
3300
3538
  let initializedHere = false;
@@ -3339,27 +3577,31 @@ var MCPAgent = class {
3339
3577
  logger.info("\u{1F3C1} Starting agent execution");
3340
3578
  const maxRestarts = 3;
3341
3579
  let restartCount = 0;
3342
- const accumulatedMessages = [...langchainHistory, new import_langchain2.HumanMessage(query)];
3580
+ const accumulatedMessages = [
3581
+ ...langchainHistory,
3582
+ new import_langchain2.HumanMessage(query)
3583
+ ];
3343
3584
  while (restartCount <= maxRestarts) {
3344
3585
  const inputs = { messages: accumulatedMessages };
3345
3586
  let shouldRestart = false;
3346
- const stream = await this._agentExecutor.stream(
3347
- inputs,
3348
- {
3349
- streamMode: "updates",
3350
- // Get updates as they happen
3351
- callbacks: this.callbacks,
3352
- metadata: this.getMetadata(),
3353
- tags: this.getTags(),
3354
- // Set trace name for LangChain/Langfuse
3355
- runName: this.metadata.trace_name || "mcp-use-agent",
3356
- // Pass sessionId for Langfuse if present in metadata
3357
- ...this.metadata.session_id && { sessionId: this.metadata.session_id }
3587
+ const stream = await this._agentExecutor.stream(inputs, {
3588
+ streamMode: "updates",
3589
+ // Get updates as they happen
3590
+ callbacks: this.callbacks,
3591
+ metadata: this.getMetadata(),
3592
+ tags: this.getTags(),
3593
+ // Set trace name for LangChain/Langfuse
3594
+ runName: this.metadata.trace_name || "mcp-use-agent",
3595
+ // Pass sessionId for Langfuse if present in metadata
3596
+ ...this.metadata.session_id && {
3597
+ sessionId: this.metadata.session_id
3358
3598
  }
3359
- );
3599
+ });
3360
3600
  for await (const chunk of stream) {
3361
3601
  for (const [nodeName, nodeOutput] of Object.entries(chunk)) {
3362
- logger.debug(`\u{1F4E6} Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`);
3602
+ logger.debug(
3603
+ `\u{1F4E6} Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`
3604
+ );
3363
3605
  if (nodeOutput && typeof nodeOutput === "object" && "messages" in nodeOutput) {
3364
3606
  let messages = nodeOutput.messages;
3365
3607
  if (!Array.isArray(messages)) {
@@ -3381,7 +3623,9 @@ var MCPAgent = class {
3381
3623
  if (toolInputStr.length > 100) {
3382
3624
  toolInputStr = `${toolInputStr.slice(0, 97)}...`;
3383
3625
  }
3384
- logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
3626
+ logger.info(
3627
+ `\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`
3628
+ );
3385
3629
  yield {
3386
3630
  action: {
3387
3631
  tool: toolName,
@@ -3403,9 +3647,15 @@ var MCPAgent = class {
3403
3647
  logger.info(`\u{1F4C4} Tool result: ${observationStr}`);
3404
3648
  if (this.useServerManager && this.serverManager) {
3405
3649
  const currentTools = this.serverManager.tools;
3406
- const currentToolNames = new Set(currentTools.map((t) => t.name));
3407
- const existingToolNames = new Set(this._tools.map((t) => t.name));
3408
- if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
3650
+ const currentToolNames = new Set(
3651
+ currentTools.map((t) => t.name)
3652
+ );
3653
+ const existingToolNames = new Set(
3654
+ this._tools.map((t) => t.name)
3655
+ );
3656
+ if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some(
3657
+ (n) => !existingToolNames.has(n)
3658
+ )) {
3409
3659
  logger.info(
3410
3660
  `\u{1F504} Tools changed during execution. New tools: ${[...currentToolNames].join(", ")}`
3411
3661
  );
@@ -3440,7 +3690,9 @@ var MCPAgent = class {
3440
3690
  break;
3441
3691
  }
3442
3692
  if (restartCount > maxRestarts) {
3443
- logger.warn(`\u26A0\uFE0F Max restarts (${maxRestarts}) reached. Continuing with current tools.`);
3693
+ logger.warn(
3694
+ `\u26A0\uFE0F Max restarts (${maxRestarts}) reached. Continuing with current tools.`
3695
+ );
3444
3696
  break;
3445
3697
  }
3446
3698
  }
@@ -3459,17 +3711,25 @@ var MCPAgent = class {
3459
3711
  outputSchema
3460
3712
  );
3461
3713
  if (this.memoryEnabled) {
3462
- this.addToHistory(new import_langchain2.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
3714
+ this.addToHistory(
3715
+ new import_langchain2.AIMessage(
3716
+ `Structured result: ${JSON.stringify(structuredResult)}`
3717
+ )
3718
+ );
3463
3719
  }
3464
3720
  logger.info("\u2705 Structured output successful");
3465
3721
  success = true;
3466
3722
  return structuredResult;
3467
3723
  } catch (e) {
3468
3724
  logger.error(`\u274C Structured output failed: ${e}`);
3469
- throw new Error(`Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`);
3725
+ throw new Error(
3726
+ `Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`
3727
+ );
3470
3728
  }
3471
3729
  }
3472
- logger.info(`\u{1F389} Agent execution complete in ${((Date.now() - startTime) / 1e3).toFixed(2)} seconds`);
3730
+ logger.info(
3731
+ `\u{1F389} Agent execution complete in ${((Date.now() - startTime) / 1e3).toFixed(2)} seconds`
3732
+ );
3473
3733
  success = true;
3474
3734
  return finalOutput || "No output generated";
3475
3735
  } catch (e) {
@@ -3496,7 +3756,9 @@ var MCPAgent = class {
3496
3756
  modelProvider: this.modelProvider,
3497
3757
  modelName: this.modelName,
3498
3758
  serverCount,
3499
- serverIdentifiers: this.connectors.map((connector) => connector.publicIdentifier),
3759
+ serverIdentifiers: this.connectors.map(
3760
+ (connector) => connector.publicIdentifier
3761
+ ),
3500
3762
  totalToolsAvailable: toolsAvailable.length,
3501
3763
  toolsAvailableNames: toolsAvailable.map((t) => t.name),
3502
3764
  maxStepsConfigured: this.maxSteps,
@@ -3600,7 +3862,10 @@ var MCPAgent = class {
3600
3862
  logger.info(`\u26A0\uFE0F Skipped message of type: ${msg.constructor.name}`);
3601
3863
  }
3602
3864
  }
3603
- const inputs = [...langchainHistory, new import_langchain2.HumanMessage(query)];
3865
+ const inputs = [
3866
+ ...langchainHistory,
3867
+ new import_langchain2.HumanMessage(query)
3868
+ ];
3604
3869
  logger.info("callbacks", this.callbacks);
3605
3870
  const eventStream = agentExecutor.streamEvents(
3606
3871
  { messages: inputs },
@@ -3613,7 +3878,9 @@ var MCPAgent = class {
3613
3878
  // Set trace name for LangChain/Langfuse
3614
3879
  runName: this.metadata.trace_name || "mcp-use-agent",
3615
3880
  // Pass sessionId for Langfuse if present in metadata
3616
- ...this.metadata.session_id && { sessionId: this.metadata.session_id }
3881
+ ...this.metadata.session_id && {
3882
+ sessionId: this.metadata.session_id
3883
+ }
3617
3884
  }
3618
3885
  );
3619
3886
  for await (const event of eventStream) {
@@ -3632,7 +3899,9 @@ var MCPAgent = class {
3632
3899
  }
3633
3900
  const normalizedContent = this._normalizeOutput(chunk.content);
3634
3901
  finalResponse += normalizedContent;
3635
- logger.debug(`\u{1F4DD} Accumulated response length: ${finalResponse.length}`);
3902
+ logger.debug(
3903
+ `\u{1F4DD} Accumulated response length: ${finalResponse.length}`
3904
+ );
3636
3905
  }
3637
3906
  }
3638
3907
  yield event;
@@ -3689,7 +3958,11 @@ var MCPAgent = class {
3689
3958
  data: { output: conversionResult }
3690
3959
  };
3691
3960
  if (this.memoryEnabled) {
3692
- this.addToHistory(new import_langchain2.AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
3961
+ this.addToHistory(
3962
+ new import_langchain2.AIMessage(
3963
+ `Structured result: ${JSON.stringify(conversionResult)}`
3964
+ )
3965
+ );
3693
3966
  }
3694
3967
  logger.info("\u2705 Structured output successful");
3695
3968
  }
@@ -3708,7 +3981,9 @@ var MCPAgent = class {
3708
3981
  } catch (e) {
3709
3982
  logger.error(`\u274C Error during streamEvents: ${e}`);
3710
3983
  if (initializedHere && manageConnector) {
3711
- logger.info("\u{1F9F9} Cleaning up resources after initialization error in streamEvents");
3984
+ logger.info(
3985
+ "\u{1F9F9} Cleaning up resources after initialization error in streamEvents"
3986
+ );
3712
3987
  await this.close();
3713
3988
  }
3714
3989
  throw e;
@@ -3728,7 +4003,9 @@ var MCPAgent = class {
3728
4003
  modelProvider: this.modelProvider,
3729
4004
  modelName: this.modelName,
3730
4005
  serverCount,
3731
- serverIdentifiers: this.connectors.map((connector) => connector.publicIdentifier),
4006
+ serverIdentifiers: this.connectors.map(
4007
+ (connector) => connector.publicIdentifier
4008
+ ),
3732
4009
  totalToolsAvailable: this._tools.length,
3733
4010
  toolsAvailableNames: this._tools.map((t) => t.name),
3734
4011
  maxStepsConfigured: this.maxSteps,
@@ -3756,11 +4033,15 @@ var MCPAgent = class {
3756
4033
  * @param outputSchema - The Zod schema to validate against
3757
4034
  */
3758
4035
  async _attemptStructuredOutput(rawResult, llm, outputSchema) {
3759
- logger.info(`\u{1F504} Attempting structured output with schema: ${JSON.stringify(outputSchema, null, 2)}`);
4036
+ logger.info(
4037
+ `\u{1F504} Attempting structured output with schema: ${JSON.stringify(outputSchema, null, 2)}`
4038
+ );
3760
4039
  logger.info(`\u{1F504} Raw result: ${JSON.stringify(rawResult, null, 2)}`);
3761
4040
  let structuredLlm = null;
3762
4041
  let schemaDescription = "";
3763
- logger.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`);
4042
+ logger.debug(
4043
+ `\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`
4044
+ );
3764
4045
  if (llm && "withStructuredOutput" in llm && typeof llm.withStructuredOutput === "function") {
3765
4046
  structuredLlm = llm.withStructuredOutput(outputSchema);
3766
4047
  } else if (llm) {
@@ -3812,11 +4093,17 @@ var MCPAgent = class {
3812
4093
  `;
3813
4094
  }
3814
4095
  try {
3815
- logger.info(`\u{1F504} Structured output attempt ${attempt} - using streaming approach`);
4096
+ logger.info(
4097
+ `\u{1F504} Structured output attempt ${attempt} - using streaming approach`
4098
+ );
3816
4099
  const contentPreview = textContent.length > 300 ? `${textContent.slice(0, 300)}...` : textContent;
3817
- logger.info(`\u{1F504} Content being formatted (${textContent.length} chars): ${contentPreview}`);
3818
- logger.info(`\u{1F504} Full format prompt (${formatPrompt.length} chars):
3819
- ${formatPrompt}`);
4100
+ logger.info(
4101
+ `\u{1F504} Content being formatted (${textContent.length} chars): ${contentPreview}`
4102
+ );
4103
+ logger.info(
4104
+ `\u{1F504} Full format prompt (${formatPrompt.length} chars):
4105
+ ${formatPrompt}`
4106
+ );
3820
4107
  const stream = await structuredLlm.stream(formatPrompt);
3821
4108
  let structuredResult = null;
3822
4109
  let chunkCount = 0;
@@ -3842,19 +4129,30 @@ ${formatPrompt}`);
3842
4129
  logger.info(`\u{1F504} Structured output streaming: ${chunkCount} chunks`);
3843
4130
  }
3844
4131
  }
3845
- logger.info(`\u{1F504} Structured result attempt ${attempt}: ${JSON.stringify(structuredResult, null, 2)}`);
4132
+ logger.info(
4133
+ `\u{1F504} Structured result attempt ${attempt}: ${JSON.stringify(structuredResult, null, 2)}`
4134
+ );
3846
4135
  if (!structuredResult) {
3847
4136
  throw new Error("No structured result received from stream");
3848
4137
  }
3849
- const validatedResult = this._validateStructuredResult(structuredResult, outputSchema);
4138
+ const validatedResult = this._validateStructuredResult(
4139
+ structuredResult,
4140
+ outputSchema
4141
+ );
3850
4142
  logger.info(`\u2705 Structured output successful on attempt ${attempt}`);
3851
4143
  return validatedResult;
3852
4144
  } catch (e) {
3853
4145
  lastError = e instanceof Error ? e.message : String(e);
3854
- logger.warn(`\u26A0\uFE0F Structured output attempt ${attempt} failed: ${lastError}`);
4146
+ logger.warn(
4147
+ `\u26A0\uFE0F Structured output attempt ${attempt} failed: ${lastError}`
4148
+ );
3855
4149
  if (attempt === maxRetries) {
3856
- logger.error(`\u274C All ${maxRetries} structured output attempts failed`);
3857
- throw new Error(`Failed to generate valid structured output after ${maxRetries} attempts. Last error: ${lastError}`);
4150
+ logger.error(
4151
+ `\u274C All ${maxRetries} structured output attempts failed`
4152
+ );
4153
+ throw new Error(
4154
+ `Failed to generate valid structured output after ${maxRetries} attempts. Last error: ${lastError}`
4155
+ );
3858
4156
  }
3859
4157
  continue;
3860
4158
  }
@@ -3869,14 +4167,18 @@ ${formatPrompt}`);
3869
4167
  const validatedResult = outputSchema.parse(structuredResult);
3870
4168
  const schemaType = outputSchema;
3871
4169
  if (schemaType._def && schemaType._def.shape) {
3872
- for (const [fieldName, fieldSchema] of Object.entries(schemaType._def.shape)) {
4170
+ for (const [fieldName, fieldSchema] of Object.entries(
4171
+ schemaType._def.shape
4172
+ )) {
3873
4173
  const field = fieldSchema;
3874
4174
  const isOptional = field.isOptional?.() ?? field._def?.typeName === "ZodOptional";
3875
4175
  const isNullable = field.isNullable?.() ?? field._def?.typeName === "ZodNullable";
3876
4176
  if (!isOptional && !isNullable) {
3877
4177
  const value = validatedResult[fieldName];
3878
4178
  if (value === null || value === void 0 || typeof value === "string" && !value.trim() || Array.isArray(value) && value.length === 0) {
3879
- throw new Error(`Required field '${fieldName}' is missing or empty`);
4179
+ throw new Error(
4180
+ `Required field '${fieldName}' is missing or empty`
4181
+ );
3880
4182
  }
3881
4183
  }
3882
4184
  }
@@ -3962,7 +4264,10 @@ var BrowserOAuthClientProvider = class {
3962
4264
  try {
3963
4265
  return JSON.parse(data);
3964
4266
  } catch (e) {
3965
- console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`, e);
4267
+ console.warn(
4268
+ `[${this.storageKeyPrefix}] Failed to parse client information:`,
4269
+ e
4270
+ );
3966
4271
  localStorage.removeItem(key);
3967
4272
  return void 0;
3968
4273
  }
@@ -4044,7 +4349,11 @@ var BrowserOAuthClientProvider = class {
4044
4349
  const sanitizedAuthUrl = await this.prepareAuthorizationUrl(authorizationUrl);
4045
4350
  const popupFeatures = "width=600,height=700,resizable=yes,scrollbars=yes,status=yes";
4046
4351
  try {
4047
- const popup = window.open(sanitizedAuthUrl, `mcp_auth_${this.serverUrlHash}`, popupFeatures);
4352
+ const popup = window.open(
4353
+ sanitizedAuthUrl,
4354
+ `mcp_auth_${this.serverUrlHash}`,
4355
+ popupFeatures
4356
+ );
4048
4357
  if (this.onPopupWindow) {
4049
4358
  this.onPopupWindow(sanitizedAuthUrl, popupFeatures, popup);
4050
4359
  }
@@ -4054,10 +4363,15 @@ var BrowserOAuthClientProvider = class {
4054
4363
  );
4055
4364
  } else {
4056
4365
  popup.focus();
4057
- console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`);
4366
+ console.info(
4367
+ `[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`
4368
+ );
4058
4369
  }
4059
4370
  } catch (e) {
4060
- console.error(`[${this.storageKeyPrefix}] Error opening popup window:`, e);
4371
+ console.error(
4372
+ `[${this.storageKeyPrefix}] Error opening popup window:`,
4373
+ e
4374
+ );
4061
4375
  }
4062
4376
  }
4063
4377
  // --- Helper Methods ---
@@ -4088,7 +4402,10 @@ var BrowserOAuthClientProvider = class {
4088
4402
  }
4089
4403
  }
4090
4404
  } catch (e) {
4091
- console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${key} during clearStorage:`, e);
4405
+ console.warn(
4406
+ `[${this.storageKeyPrefix}] Error parsing state key ${key} during clearStorage:`,
4407
+ e
4408
+ );
4092
4409
  }
4093
4410
  }
4094
4411
  }
@@ -4122,23 +4439,36 @@ async function onMcpAuthorization() {
4122
4439
  const error = queryParams.get("error");
4123
4440
  const errorDescription = queryParams.get("error_description");
4124
4441
  const logPrefix = "[mcp-callback]";
4125
- console.log(`${logPrefix} Handling callback...`, { code, state, error, errorDescription });
4442
+ console.log(`${logPrefix} Handling callback...`, {
4443
+ code,
4444
+ state,
4445
+ error,
4446
+ errorDescription
4447
+ });
4126
4448
  let provider = null;
4127
4449
  let storedStateData = null;
4128
4450
  const stateKey = state ? `mcp:auth:state_${state}` : null;
4129
4451
  try {
4130
4452
  if (error) {
4131
- throw new Error(`OAuth error: ${error} - ${errorDescription || "No description provided."}`);
4453
+ throw new Error(
4454
+ `OAuth error: ${error} - ${errorDescription || "No description provided."}`
4455
+ );
4132
4456
  }
4133
4457
  if (!code) {
4134
- throw new Error("Authorization code not found in callback query parameters.");
4458
+ throw new Error(
4459
+ "Authorization code not found in callback query parameters."
4460
+ );
4135
4461
  }
4136
4462
  if (!state || !stateKey) {
4137
- throw new Error("State parameter not found or invalid in callback query parameters.");
4463
+ throw new Error(
4464
+ "State parameter not found or invalid in callback query parameters."
4465
+ );
4138
4466
  }
4139
4467
  const storedStateJSON = localStorage.getItem(stateKey);
4140
4468
  if (!storedStateJSON) {
4141
- throw new Error(`Invalid or expired state parameter "${state}". No matching state found in storage.`);
4469
+ throw new Error(
4470
+ `Invalid or expired state parameter "${state}". No matching state found in storage.`
4471
+ );
4142
4472
  }
4143
4473
  try {
4144
4474
  storedStateData = JSON.parse(storedStateJSON);
@@ -4147,38 +4477,59 @@ async function onMcpAuthorization() {
4147
4477
  }
4148
4478
  if (!storedStateData.expiry || storedStateData.expiry < Date.now()) {
4149
4479
  localStorage.removeItem(stateKey);
4150
- throw new Error("OAuth state has expired. Please try initiating authentication again.");
4480
+ throw new Error(
4481
+ "OAuth state has expired. Please try initiating authentication again."
4482
+ );
4151
4483
  }
4152
4484
  if (!storedStateData.providerOptions) {
4153
4485
  throw new Error("Stored state is missing required provider options.");
4154
4486
  }
4155
4487
  const { serverUrl, ...providerOptions } = storedStateData.providerOptions;
4156
- console.log(`${logPrefix} Re-instantiating provider for server: ${serverUrl}`);
4488
+ console.log(
4489
+ `${logPrefix} Re-instantiating provider for server: ${serverUrl}`
4490
+ );
4157
4491
  provider = new BrowserOAuthClientProvider(serverUrl, providerOptions);
4158
4492
  console.log(`${logPrefix} Calling SDK auth() to exchange code...`);
4159
4493
  const baseUrl = new URL(serverUrl).origin;
4160
- const authResult = await (0, import_auth.auth)(provider, { serverUrl: baseUrl, authorizationCode: code });
4494
+ const authResult = await (0, import_auth.auth)(provider, {
4495
+ serverUrl: baseUrl,
4496
+ authorizationCode: code
4497
+ });
4161
4498
  if (authResult === "AUTHORIZED") {
4162
- console.log(`${logPrefix} Authorization successful via SDK auth(). Notifying opener...`);
4499
+ console.log(
4500
+ `${logPrefix} Authorization successful via SDK auth(). Notifying opener...`
4501
+ );
4163
4502
  if (window.opener && !window.opener.closed) {
4164
- window.opener.postMessage({ type: "mcp_auth_callback", success: true }, window.location.origin);
4503
+ window.opener.postMessage(
4504
+ { type: "mcp_auth_callback", success: true },
4505
+ window.location.origin
4506
+ );
4165
4507
  window.close();
4166
4508
  } else {
4167
- console.warn(`${logPrefix} No opener window detected. Redirecting to root.`);
4509
+ console.warn(
4510
+ `${logPrefix} No opener window detected. Redirecting to root.`
4511
+ );
4168
4512
  const pathParts = window.location.pathname.split("/").filter(Boolean);
4169
4513
  const basePath = pathParts.length > 0 && pathParts[pathParts.length - 1] === "callback" ? "/" + pathParts.slice(0, -2).join("/") : "/";
4170
4514
  window.location.href = basePath || "/";
4171
4515
  }
4172
4516
  localStorage.removeItem(stateKey);
4173
4517
  } else {
4174
- console.warn(`${logPrefix} SDK auth() returned unexpected status: ${authResult}`);
4175
- throw new Error(`Unexpected result from authentication library: ${authResult}`);
4518
+ console.warn(
4519
+ `${logPrefix} SDK auth() returned unexpected status: ${authResult}`
4520
+ );
4521
+ throw new Error(
4522
+ `Unexpected result from authentication library: ${authResult}`
4523
+ );
4176
4524
  }
4177
4525
  } catch (err) {
4178
4526
  console.error(`${logPrefix} Error during OAuth callback handling:`, err);
4179
4527
  const errorMessage = err instanceof Error ? err.message : String(err);
4180
4528
  if (window.opener && !window.opener.closed) {
4181
- window.opener.postMessage({ type: "mcp_auth_callback", success: false, error: errorMessage }, window.location.origin);
4529
+ window.opener.postMessage(
4530
+ { type: "mcp_auth_callback", success: false, error: errorMessage },
4531
+ window.location.origin
4532
+ );
4182
4533
  }
4183
4534
  try {
4184
4535
  document.body.innerHTML = `
@@ -4192,7 +4543,10 @@ async function onMcpAuthorization() {
4192
4543
  </div>
4193
4544
  `;
4194
4545
  } catch (displayError) {
4195
- console.error(`${logPrefix} Could not display error in callback window:`, displayError);
4546
+ console.error(
4547
+ `${logPrefix} Could not display error in callback window:`,
4548
+ displayError
4549
+ );
4196
4550
  }
4197
4551
  if (stateKey) {
4198
4552
  localStorage.removeItem(stateKey);