mcp-use 1.1.8-canary.1 → 1.2.0-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 (45) hide show
  1. package/README.md +1 -1
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/{chunk-4SWVHFJH.js → chunk-GKNOUQFQ.js} +284 -208
  4. package/dist/{chunk-2HFIPY7C.js → chunk-ZUEQQ6YK.js} +17 -2
  5. package/dist/index.cjs +315 -220
  6. package/dist/index.js +2 -2
  7. package/dist/{langfuse-YA2S23SM.js → langfuse-6AJGHMAV.js} +1 -1
  8. package/dist/src/agents/mcp_agent.d.ts +33 -8
  9. package/dist/src/agents/mcp_agent.d.ts.map +1 -1
  10. package/dist/src/agents/prompts/system_prompt_builder.d.ts +1 -1
  11. package/dist/src/agents/prompts/system_prompt_builder.d.ts.map +1 -1
  12. package/dist/src/browser.cjs +315 -220
  13. package/dist/src/browser.js +2 -2
  14. package/dist/src/managers/server_manager.d.ts +2 -1
  15. package/dist/src/managers/server_manager.d.ts.map +1 -1
  16. package/dist/src/managers/tools/acquire_active_mcp_server.d.ts +2 -2
  17. package/dist/src/managers/tools/acquire_active_mcp_server.d.ts.map +1 -1
  18. package/dist/src/managers/tools/add_server_from_config.d.ts +3 -3
  19. package/dist/src/managers/tools/add_server_from_config.d.ts.map +1 -1
  20. package/dist/src/managers/tools/base.d.ts +3 -3
  21. package/dist/src/managers/tools/base.d.ts.map +1 -1
  22. package/dist/src/managers/tools/connect_mcp_server.d.ts +2 -2
  23. package/dist/src/managers/tools/connect_mcp_server.d.ts.map +1 -1
  24. package/dist/src/managers/tools/list_mcp_servers.d.ts +2 -2
  25. package/dist/src/managers/tools/list_mcp_servers.d.ts.map +1 -1
  26. package/dist/src/managers/tools/release_mcp_server_connection.d.ts +2 -2
  27. package/dist/src/managers/tools/release_mcp_server_connection.d.ts.map +1 -1
  28. package/dist/src/managers/types.d.ts +14 -0
  29. package/dist/src/managers/types.d.ts.map +1 -0
  30. package/dist/src/observability/langfuse.d.ts.map +1 -1
  31. package/dist/src/observability/manager.d.ts +11 -0
  32. package/dist/src/observability/manager.d.ts.map +1 -1
  33. package/dist/tsup.config.d.ts.map +1 -1
  34. package/package.json +33 -13
  35. package/dist/tests/ai_sdk_compatibility.test.d.ts +0 -13
  36. package/dist/tests/ai_sdk_compatibility.test.d.ts.map +0 -1
  37. package/dist/tests/helpers/widget-generators.d.ts +0 -24
  38. package/dist/tests/helpers/widget-generators.d.ts.map +0 -1
  39. package/dist/tests/mcp-ui-adapter.test.d.ts +0 -8
  40. package/dist/tests/mcp-ui-adapter.test.d.ts.map +0 -1
  41. package/dist/tests/stream_events.test.d.ts +0 -12
  42. package/dist/tests/stream_events.test.d.ts.map +0 -1
  43. package/dist/tests/stream_events_simple.test.d.ts +0 -7
  44. package/dist/tests/stream_events_simple.test.d.ts.map +0 -1
  45. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -280,7 +280,7 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
280
280
  try {
281
281
  const langfuseModule = await import("langfuse-langchain").catch(() => null);
282
282
  if (!langfuseModule) {
283
- logger.debug("Langfuse package not installed - tracing disabled. Install with: npm install langfuse-langchain");
283
+ logger.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");
284
284
  return;
285
285
  }
286
286
  const { CallbackHandler } = langfuseModule;
@@ -407,6 +407,8 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
407
407
  return super.handleAgentEnd(...args);
408
408
  }
409
409
  }
410
+ const initialMetadata = metadata || (metadataProvider ? metadataProvider() : {});
411
+ const initialTags = tagsProvider ? tagsProvider() : [];
410
412
  const config2 = {
411
413
  publicKey: process.env.LANGFUSE_PUBLIC_KEY,
412
414
  secretKey: process.env.LANGFUSE_SECRET_KEY,
@@ -415,8 +417,21 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
415
417
  flushInterval: Number.parseInt(process.env.LANGFUSE_FLUSH_INTERVAL || "10000"),
416
418
  release: process.env.LANGFUSE_RELEASE,
417
419
  requestTimeout: Number.parseInt(process.env.LANGFUSE_REQUEST_TIMEOUT || "10000"),
418
- enabled: process.env.LANGFUSE_ENABLED !== "false"
420
+ enabled: process.env.LANGFUSE_ENABLED !== "false",
421
+ // Set trace name - can be customized via metadata.trace_name or defaults to 'mcp-use-agent'
422
+ traceName: initialMetadata.trace_name || process.env.LANGFUSE_TRACE_NAME || "mcp-use-agent",
423
+ // Pass sessionId, userId, and tags to the handler
424
+ sessionId: initialMetadata.session_id || void 0,
425
+ userId: initialMetadata.user_id || void 0,
426
+ tags: initialTags.length > 0 ? initialTags : void 0,
427
+ metadata: initialMetadata || void 0
419
428
  };
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));
420
435
  langfuseState.handler = new LoggingCallbackHandler(config2, agentId, metadata, metadataProvider, tagsProvider);
421
436
  logger.debug("Langfuse observability initialized successfully with logging enabled");
422
437
  try {
@@ -469,13 +484,13 @@ var init_langfuse = __esm({
469
484
  // src/browser.ts
470
485
  var browser_exports = {};
471
486
  __export(browser_exports, {
472
- AIMessage: () => import_messages3.AIMessage,
487
+ AIMessage: () => import_messages2.AIMessage,
473
488
  BaseAdapter: () => BaseAdapter,
474
489
  BaseConnector: () => BaseConnector,
475
- BaseMessage: () => import_messages3.BaseMessage,
490
+ BaseMessage: () => import_messages2.BaseMessage,
476
491
  BrowserOAuthClientProvider: () => BrowserOAuthClientProvider,
477
492
  HttpConnector: () => HttpConnector,
478
- HumanMessage: () => import_messages3.HumanMessage,
493
+ HumanMessage: () => import_messages2.HumanMessage,
479
494
  LangChainAdapter: () => LangChainAdapter,
480
495
  Logger: () => Logger,
481
496
  MCPAgent: () => MCPAgent,
@@ -483,8 +498,8 @@ __export(browser_exports, {
483
498
  MCPSession: () => MCPSession,
484
499
  ObservabilityManager: () => ObservabilityManager,
485
500
  RemoteAgent: () => RemoteAgent,
486
- SystemMessage: () => import_messages3.SystemMessage,
487
- ToolMessage: () => import_messages3.ToolMessage,
501
+ SystemMessage: () => import_messages2.SystemMessage,
502
+ ToolMessage: () => import_messages2.ToolMessage,
488
503
  WebSocketConnector: () => WebSocketConnector,
489
504
  createReadableStreamFromGenerator: () => createReadableStreamFromGenerator,
490
505
  logger: () => logger,
@@ -1487,11 +1502,8 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
1487
1502
  };
1488
1503
 
1489
1504
  // src/agents/mcp_agent.ts
1490
- var import_manager2 = require("@langchain/core/callbacks/manager");
1491
- var import_messages2 = require("@langchain/core/messages");
1492
- var import_output_parsers = require("@langchain/core/output_parsers");
1493
- var import_prompts = require("@langchain/core/prompts");
1494
- var import_agents = require("langchain/agents");
1505
+ var import_messages = require("@langchain/core/messages");
1506
+ var import_langchain2 = require("langchain");
1495
1507
  var import_zod_to_json_schema2 = require("zod-to-json-schema");
1496
1508
 
1497
1509
  // src/adapters/langchain_adapter.ts
@@ -1712,7 +1724,7 @@ var AcquireActiveMCPServerTool = class extends MCPServerTool {
1712
1724
  };
1713
1725
 
1714
1726
  // src/managers/tools/add_server_from_config.ts
1715
- var import_tools3 = require("langchain/tools");
1727
+ var import_tools3 = require("@langchain/core/tools");
1716
1728
  var import_zod3 = require("zod");
1717
1729
  init_logging();
1718
1730
  var AddMCPServerFromConfigTool = class extends import_tools3.StructuredTool {
@@ -2085,6 +2097,23 @@ var ObservabilityManager = class {
2085
2097
  const callbacks = await this.getCallbacks();
2086
2098
  return callbacks.length > 0;
2087
2099
  }
2100
+ /**
2101
+ * Get the current observability status including metadata and tags.
2102
+ * @returns Object containing enabled status, callback count, handler names, metadata, and tags.
2103
+ */
2104
+ async getStatus() {
2105
+ const callbacks = await this.getCallbacks();
2106
+ const handlerNames = await this.getHandlerNames();
2107
+ const currentMetadata = this.metadataProvider ? this.metadataProvider() : this.metadata || {};
2108
+ const currentTags = this.tagsProvider ? this.tagsProvider() : [];
2109
+ return {
2110
+ enabled: this.observe && callbacks.length > 0,
2111
+ callbackCount: callbacks.length,
2112
+ handlerNames,
2113
+ metadata: currentMetadata,
2114
+ tags: currentTags
2115
+ };
2116
+ }
2088
2117
  /**
2089
2118
  * Add a callback to the custom callbacks list.
2090
2119
  * @param callback The callback to add.
@@ -2516,7 +2545,7 @@ var Telemetry = class _Telemetry {
2516
2545
  };
2517
2546
 
2518
2547
  // src/agents/prompts/system_prompt_builder.ts
2519
- var import_messages = require("@langchain/core/messages");
2548
+ var import_langchain = require("langchain");
2520
2549
  function generateToolDescriptions(tools, disallowedTools) {
2521
2550
  const disallowedSet = new Set(disallowedTools ?? []);
2522
2551
  const descriptions = [];
@@ -2551,7 +2580,7 @@ ${additionalInstructions}`;
2551
2580
  __name(buildSystemPromptContent, "buildSystemPromptContent");
2552
2581
  function createSystemMessage(tools, systemPromptTemplate, serverManagerTemplate, useServerManager, disallowedTools, userProvidedPrompt, additionalInstructions) {
2553
2582
  if (userProvidedPrompt) {
2554
- return new import_messages.SystemMessage({ content: userProvidedPrompt });
2583
+ return new import_langchain.SystemMessage({ content: userProvidedPrompt });
2555
2584
  }
2556
2585
  const template = useServerManager ? serverManagerTemplate : systemPromptTemplate;
2557
2586
  const toolLines = generateToolDescriptions(tools, disallowedTools);
@@ -2560,7 +2589,7 @@ function createSystemMessage(tools, systemPromptTemplate, serverManagerTemplate,
2560
2589
  toolLines,
2561
2590
  additionalInstructions
2562
2591
  );
2563
- return new import_messages.SystemMessage({ content: finalContent });
2592
+ return new import_langchain.SystemMessage({ content: finalContent });
2564
2593
  }
2565
2594
  __name(createSystemMessage, "createSystemMessage");
2566
2595
 
@@ -2837,6 +2866,7 @@ var MCPAgent = class {
2837
2866
  memoryEnabled;
2838
2867
  disallowedTools;
2839
2868
  additionalTools;
2869
+ toolsUsedNames = [];
2840
2870
  useServerManager;
2841
2871
  verbose;
2842
2872
  observe;
@@ -2904,6 +2934,7 @@ var MCPAgent = class {
2904
2934
  this.additionalInstructions = options.additionalInstructions ?? null;
2905
2935
  this.disallowedTools = options.disallowedTools ?? [];
2906
2936
  this.additionalTools = options.additionalTools ?? [];
2937
+ this.toolsUsedNames = options.toolsUsedNames ?? [];
2907
2938
  this.useServerManager = options.useServerManager ?? false;
2908
2939
  this.verbose = options.verbose ?? false;
2909
2940
  this.observe = options.observe ?? true;
@@ -3018,7 +3049,7 @@ var MCPAgent = class {
3018
3049
  if (this.memoryEnabled) {
3019
3050
  this.conversationHistory = [
3020
3051
  this.systemMessage,
3021
- ...this.conversationHistory.filter((m) => !(m instanceof import_messages2.SystemMessage))
3052
+ ...this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage))
3022
3053
  ];
3023
3054
  }
3024
3055
  }
@@ -3027,25 +3058,17 @@ var MCPAgent = class {
3027
3058
  throw new Error("LLM is required to create agent");
3028
3059
  }
3029
3060
  const systemContent = this.systemMessage?.content ?? "You are a helpful assistant.";
3030
- const prompt = import_prompts.ChatPromptTemplate.fromMessages([
3031
- ["system", systemContent],
3032
- new import_prompts.MessagesPlaceholder("chat_history"),
3033
- ["human", "{input}"],
3034
- new import_prompts.MessagesPlaceholder("agent_scratchpad")
3035
- ]);
3036
- const agent = (0, import_agents.createToolCallingAgent)({
3037
- llm: this.llm,
3061
+ const toolNames = this._tools.map((tool) => tool.name);
3062
+ logger.info(`\u{1F9E0} Agent ready with tools: ${toolNames.join(", ")}`);
3063
+ const middleware = [(0, import_langchain2.modelCallLimitMiddleware)({ runLimit: this.maxSteps })];
3064
+ const agent = (0, import_langchain2.createAgent)({
3065
+ model: this.llm,
3038
3066
  tools: this._tools,
3039
- prompt
3040
- });
3041
- return new import_agents.AgentExecutor({
3042
- agent,
3043
- tools: this._tools,
3044
- maxIterations: this.maxSteps,
3045
- verbose: this.verbose,
3046
- returnIntermediateSteps: true,
3047
- callbacks: this.callbacks
3067
+ systemPrompt: systemContent,
3068
+ middleware
3048
3069
  });
3070
+ logger.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`);
3071
+ return agent;
3049
3072
  }
3050
3073
  getConversationHistory() {
3051
3074
  return [...this.conversationHistory];
@@ -3061,9 +3084,9 @@ var MCPAgent = class {
3061
3084
  return this.systemMessage;
3062
3085
  }
3063
3086
  setSystemMessage(message) {
3064
- this.systemMessage = new import_messages2.SystemMessage(message);
3087
+ this.systemMessage = new import_langchain2.SystemMessage(message);
3065
3088
  if (this.memoryEnabled) {
3066
- this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof import_messages2.SystemMessage));
3089
+ this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage));
3067
3090
  this.conversationHistory.unshift(this.systemMessage);
3068
3091
  }
3069
3092
  if (this._initialized && this._tools.length) {
@@ -3213,6 +3236,42 @@ var MCPAgent = class {
3213
3236
  }
3214
3237
  return serverInfo;
3215
3238
  }
3239
+ _normalizeOutput(value) {
3240
+ try {
3241
+ if (typeof value === "string") {
3242
+ return value;
3243
+ }
3244
+ if (value && typeof value === "object" && "content" in value) {
3245
+ return this._normalizeOutput(value.content);
3246
+ }
3247
+ if (Array.isArray(value)) {
3248
+ const parts = [];
3249
+ for (const item of value) {
3250
+ if (typeof item === "object" && item !== null) {
3251
+ if ("text" in item && typeof item.text === "string") {
3252
+ parts.push(item.text);
3253
+ } else if ("content" in item) {
3254
+ parts.push(this._normalizeOutput(item.content));
3255
+ } else {
3256
+ parts.push(String(item));
3257
+ }
3258
+ } else {
3259
+ const partText = item && typeof item === "object" && "text" in item ? item.text : null;
3260
+ if (typeof partText === "string") {
3261
+ parts.push(partText);
3262
+ } else {
3263
+ const partContent = item && typeof item === "object" && "content" in item ? item.content : item;
3264
+ parts.push(this._normalizeOutput(partContent));
3265
+ }
3266
+ }
3267
+ }
3268
+ return parts.join("");
3269
+ }
3270
+ return String(value);
3271
+ } catch (error) {
3272
+ return String(value);
3273
+ }
3274
+ }
3216
3275
  async _consumeAndReturn(generator) {
3217
3276
  while (true) {
3218
3277
  const { done, value } = await generator.next();
@@ -3234,36 +3293,16 @@ var MCPAgent = class {
3234
3293
  );
3235
3294
  return this._consumeAndReturn(generator);
3236
3295
  }
3237
- /**
3238
- * Runs the agent and yields intermediate steps as an async generator.
3239
- * If outputSchema is provided, returns structured output of type T.
3240
- */
3241
3296
  async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
3242
3297
  if (this.isRemote && this.remoteAgent) {
3243
- const result2 = await this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
3244
- return result2;
3298
+ const result = await this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
3299
+ return result;
3245
3300
  }
3246
- let result = "";
3247
3301
  let initializedHere = false;
3248
3302
  const startTime = Date.now();
3249
- const toolsUsedNames = [];
3303
+ let success = false;
3304
+ let finalOutput = null;
3250
3305
  let stepsTaken = 0;
3251
- const structuredOutputSuccess = false;
3252
- const structuredOutputSuccessRef = { value: structuredOutputSuccess };
3253
- let structuredLlm = null;
3254
- let schemaDescription = "";
3255
- if (outputSchema) {
3256
- query = this._enhanceQueryWithSchema(query, outputSchema);
3257
- logger.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`);
3258
- if (this.llm && "withStructuredOutput" in this.llm && typeof this.llm.withStructuredOutput === "function") {
3259
- structuredLlm = this.llm.withStructuredOutput(outputSchema);
3260
- } else if (this.llm) {
3261
- structuredLlm = this.llm;
3262
- } else {
3263
- throw new Error("LLM is required for structured output");
3264
- }
3265
- schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
3266
- }
3267
3306
  try {
3268
3307
  if (manageConnector && !this._initialized) {
3269
3308
  await this.initialize();
@@ -3275,158 +3314,169 @@ var MCPAgent = class {
3275
3314
  if (!this._agentExecutor) {
3276
3315
  throw new Error("MCP agent failed to initialize");
3277
3316
  }
3278
- const steps = maxSteps ?? this.maxSteps;
3279
- this._agentExecutor.maxIterations = steps;
3280
- const display_query = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
3281
- logger.info(`\u{1F4AC} Received query: '${display_query}'`);
3282
- if (this.memoryEnabled) {
3283
- this.addToHistory(new import_messages2.HumanMessage(query));
3317
+ if (this.useServerManager && this.serverManager) {
3318
+ const currentTools = this.serverManager.tools;
3319
+ const currentToolNames = new Set(currentTools.map((t) => t.name));
3320
+ const existingToolNames = new Set(this._tools.map((t) => t.name));
3321
+ if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
3322
+ logger.info(
3323
+ `\u{1F504} Tools changed before execution, updating agent. New tools: ${[...currentToolNames].join(", ")}`
3324
+ );
3325
+ this._tools = currentTools;
3326
+ this._tools.push(...this.additionalTools);
3327
+ await this.createSystemMessageFromTools(this._tools);
3328
+ this._agentExecutor = this.createAgent();
3329
+ }
3284
3330
  }
3285
3331
  const historyToUse = externalHistory ?? this.conversationHistory;
3286
3332
  const langchainHistory = [];
3287
3333
  for (const msg of historyToUse) {
3288
- if (msg instanceof import_messages2.HumanMessage || msg instanceof import_messages2.AIMessage) {
3334
+ if (msg instanceof import_messages.HumanMessage || msg instanceof import_messages.AIMessage) {
3289
3335
  langchainHistory.push(msg);
3290
3336
  }
3291
3337
  }
3292
- const intermediateSteps = [];
3293
- const inputs = { input: query, chat_history: langchainHistory };
3294
- let nameToToolMap = Object.fromEntries(this._tools.map((t) => [t.name, t]));
3295
- logger.info(`\u{1F3C1} Starting agent execution with max_steps=${steps}`);
3296
- let runManager;
3297
- if (this.callbacks?.length > 0) {
3298
- const callbackManager = new import_manager2.CallbackManager(void 0, {
3299
- handlers: this.callbacks,
3300
- inheritableHandlers: this.callbacks
3301
- });
3302
- runManager = await callbackManager.handleChainStart({
3303
- name: "MCPAgent (mcp-use)",
3304
- id: ["MCPAgent (mcp-use)"],
3305
- lc: 1,
3306
- type: "not_implemented"
3307
- }, inputs);
3308
- }
3309
- for (let stepNum = 0; stepNum < steps; stepNum++) {
3310
- stepsTaken = stepNum + 1;
3311
- if (this.useServerManager && this.serverManager) {
3312
- const currentTools = this.serverManager.tools;
3313
- const currentToolNames = new Set(currentTools.map((t) => t.name));
3314
- const existingToolNames = new Set(this._tools.map((t) => t.name));
3315
- const changed = currentTools.length !== this._tools.length || [...currentToolNames].some((n) => !existingToolNames.has(n));
3316
- if (changed) {
3317
- logger.info(
3318
- `\u{1F504} Tools changed before step ${stepNum + 1}, updating agent. New tools: ${[...currentToolNames].join(", ")}`
3319
- );
3320
- this._tools = currentTools;
3321
- this._tools.push(...this.additionalTools);
3322
- await this.createSystemMessageFromTools(this._tools);
3323
- this._agentExecutor = this.createAgent();
3324
- this._agentExecutor.maxIterations = steps;
3325
- nameToToolMap = Object.fromEntries(this._tools.map((t) => [t.name, t]));
3338
+ const displayQuery = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
3339
+ logger.info(`\u{1F4AC} Received query: '${displayQuery}'`);
3340
+ logger.info("\u{1F3C1} Starting agent execution");
3341
+ const maxRestarts = 3;
3342
+ let restartCount = 0;
3343
+ const accumulatedMessages = [...langchainHistory, new import_messages.HumanMessage(query)];
3344
+ while (restartCount <= maxRestarts) {
3345
+ const inputs = { messages: accumulatedMessages };
3346
+ let shouldRestart = false;
3347
+ const stream = await this._agentExecutor.stream(
3348
+ inputs,
3349
+ {
3350
+ streamMode: "updates",
3351
+ // Get updates as they happen
3352
+ callbacks: this.callbacks,
3353
+ metadata: this.getMetadata(),
3354
+ tags: this.getTags(),
3355
+ // Set trace name for LangChain/Langfuse
3356
+ runName: this.metadata.trace_name || "mcp-use-agent",
3357
+ // Pass sessionId for Langfuse if present in metadata
3358
+ ...this.metadata.session_id && { sessionId: this.metadata.session_id }
3326
3359
  }
3327
- }
3328
- logger.info(`\u{1F463} Step ${stepNum + 1}/${steps}`);
3329
- try {
3330
- logger.debug("Starting agent step execution");
3331
- const nextStepOutput = await this._agentExecutor._takeNextStep(
3332
- nameToToolMap,
3333
- inputs,
3334
- intermediateSteps,
3335
- runManager
3336
- );
3337
- if ("returnValues" in nextStepOutput) {
3338
- logger.info(`\u2705 Agent finished at step ${stepNum + 1}`);
3339
- result = nextStepOutput.returnValues?.output ?? "No output generated";
3340
- runManager?.handleChainEnd({ output: result });
3341
- if (outputSchema && structuredLlm) {
3342
- logger.info("\u{1F527} Attempting structured output...");
3343
- const currentResult = result;
3344
- this._attemptStructuredOutput(
3345
- currentResult,
3346
- this.llm,
3347
- outputSchema
3348
- ).then((structuredResult) => {
3349
- if (this.memoryEnabled) {
3350
- this.addToHistory(new import_messages2.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
3360
+ );
3361
+ for await (const chunk of stream) {
3362
+ for (const [nodeName, nodeOutput] of Object.entries(chunk)) {
3363
+ logger.debug(`\u{1F4E6} Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`);
3364
+ if (nodeOutput && typeof nodeOutput === "object" && "messages" in nodeOutput) {
3365
+ let messages = nodeOutput.messages;
3366
+ if (!Array.isArray(messages)) {
3367
+ messages = [messages];
3368
+ }
3369
+ for (const msg of messages) {
3370
+ if (!accumulatedMessages.includes(msg)) {
3371
+ accumulatedMessages.push(msg);
3351
3372
  }
3352
- logger.info("\u2705 Structured output successful");
3353
- structuredOutputSuccessRef.value = true;
3354
- return structuredResult;
3355
- }).catch((e) => {
3356
- logger.warn(`\u26A0\uFE0F Structured output failed: ${e}`);
3357
- const failedStructuredOutputPrompt = `
3358
- The current result cannot be formatted into the required structure.
3359
- Error: ${String(e)}
3360
-
3361
- Current information: ${currentResult}
3362
-
3363
- If information is missing, please continue working to gather the missing information needed for:
3364
- ${schemaDescription}
3365
-
3366
- If the information is complete, please return the result in the required structure.
3367
- `;
3368
- inputs.input = failedStructuredOutputPrompt;
3369
- if (this.memoryEnabled) {
3370
- this.addToHistory(new import_messages2.HumanMessage(failedStructuredOutputPrompt));
3373
+ }
3374
+ for (const message of messages) {
3375
+ if ("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
3376
+ for (const toolCall of message.tool_calls) {
3377
+ const toolName = toolCall.name || "unknown";
3378
+ const toolInput = toolCall.args || {};
3379
+ this.toolsUsedNames.push(toolName);
3380
+ stepsTaken++;
3381
+ let toolInputStr = JSON.stringify(toolInput);
3382
+ if (toolInputStr.length > 100) {
3383
+ toolInputStr = `${toolInputStr.slice(0, 97)}...`;
3384
+ }
3385
+ logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
3386
+ yield {
3387
+ action: {
3388
+ tool: toolName,
3389
+ toolInput,
3390
+ log: `Calling tool ${toolName}`
3391
+ },
3392
+ observation: ""
3393
+ // Will be filled in by tool result
3394
+ };
3395
+ }
3371
3396
  }
3372
- logger.info("\u{1F504} Continuing execution to gather missing information...");
3373
- });
3374
- }
3375
- }
3376
- if (Array.isArray(nextStepOutput)) {
3377
- const stepArray = nextStepOutput;
3378
- intermediateSteps.push(...stepArray);
3379
- for (const step of stepArray) {
3380
- yield step;
3381
- const { action, observation } = step;
3382
- const toolName = action.tool;
3383
- toolsUsedNames.push(toolName);
3384
- let toolInputStr = typeof action.toolInput === "string" ? action.toolInput : JSON.stringify(action.toolInput, null, 2);
3385
- if (toolInputStr.length > 100)
3386
- toolInputStr = `${toolInputStr.slice(0, 97)}...`;
3387
- logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
3388
- let outputStr = String(observation);
3389
- if (outputStr.length > 100)
3390
- outputStr = `${outputStr.slice(0, 97)}...`;
3391
- outputStr = outputStr.replace(/\n/g, " ");
3392
- logger.info(`\u{1F4C4} Tool result: ${outputStr}`);
3393
- }
3394
- if (stepArray.length) {
3395
- const lastStep = stepArray[stepArray.length - 1];
3396
- const toolReturn = await this._agentExecutor._getToolReturn(lastStep);
3397
- if (toolReturn) {
3398
- logger.info(`\u{1F3C6} Tool returned directly at step ${stepNum + 1}`);
3399
- result = toolReturn.returnValues?.output ?? "No output generated";
3397
+ if (message instanceof import_messages.ToolMessage || message && "type" in message && message.type === "tool") {
3398
+ const observation = message.content;
3399
+ let observationStr = String(observation);
3400
+ if (observationStr.length > 100) {
3401
+ observationStr = `${observationStr.slice(0, 97)}...`;
3402
+ }
3403
+ observationStr = observationStr.replace(/\n/g, " ");
3404
+ logger.info(`\u{1F4C4} Tool result: ${observationStr}`);
3405
+ if (this.useServerManager && this.serverManager) {
3406
+ const currentTools = this.serverManager.tools;
3407
+ const currentToolNames = new Set(currentTools.map((t) => t.name));
3408
+ const existingToolNames = new Set(this._tools.map((t) => t.name));
3409
+ if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
3410
+ logger.info(
3411
+ `\u{1F504} Tools changed during execution. New tools: ${[...currentToolNames].join(", ")}`
3412
+ );
3413
+ this._tools = currentTools;
3414
+ this._tools.push(...this.additionalTools);
3415
+ await this.createSystemMessageFromTools(this._tools);
3416
+ this._agentExecutor = this.createAgent();
3417
+ shouldRestart = true;
3418
+ restartCount++;
3419
+ logger.info(
3420
+ `\u{1F503} Restarting execution with updated tools (restart ${restartCount}/${maxRestarts})`
3421
+ );
3422
+ break;
3423
+ }
3424
+ }
3425
+ }
3426
+ if (message instanceof import_messages.AIMessage && !("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0)) {
3427
+ finalOutput = this._normalizeOutput(message.content);
3428
+ logger.info("\u2705 Agent finished with output");
3429
+ }
3430
+ }
3431
+ if (shouldRestart) {
3400
3432
  break;
3401
3433
  }
3402
3434
  }
3403
3435
  }
3404
- } catch (e) {
3405
- if (e instanceof import_output_parsers.OutputParserException) {
3406
- logger.error(`\u274C Output parsing error during step ${stepNum + 1}: ${e}`);
3407
- result = `Agent stopped due to a parsing error: ${e}`;
3408
- runManager?.handleChainError(result);
3436
+ if (shouldRestart) {
3409
3437
  break;
3410
3438
  }
3411
- logger.error(`\u274C Error during agent execution step ${stepNum + 1}: ${e}`);
3412
- console.error(e);
3413
- result = `Agent stopped due to an error: ${e}`;
3414
- runManager?.handleChainError(result);
3439
+ }
3440
+ if (!shouldRestart) {
3441
+ break;
3442
+ }
3443
+ if (restartCount > maxRestarts) {
3444
+ logger.warn(`\u26A0\uFE0F Max restarts (${maxRestarts}) reached. Continuing with current tools.`);
3415
3445
  break;
3416
3446
  }
3417
3447
  }
3418
- if (!result) {
3419
- logger.warn(`\u26A0\uFE0F Agent stopped after reaching max iterations (${steps})`);
3420
- result = `Agent stopped after reaching the maximum number of steps (${steps}).`;
3421
- runManager?.handleChainEnd({ output: result });
3448
+ if (this.memoryEnabled) {
3449
+ this.addToHistory(new import_messages.HumanMessage(query));
3450
+ if (finalOutput) {
3451
+ this.addToHistory(new import_messages.AIMessage(finalOutput));
3452
+ }
3422
3453
  }
3423
- logger.info("\u{1F389} Agent execution complete");
3424
- structuredOutputSuccessRef.value = true;
3425
- return result;
3454
+ if (outputSchema && finalOutput) {
3455
+ try {
3456
+ logger.info("\u{1F527} Attempting structured output...");
3457
+ const structuredResult = await this._attemptStructuredOutput(
3458
+ finalOutput,
3459
+ this.llm,
3460
+ outputSchema
3461
+ );
3462
+ if (this.memoryEnabled) {
3463
+ this.addToHistory(new import_messages.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
3464
+ }
3465
+ logger.info("\u2705 Structured output successful");
3466
+ success = true;
3467
+ return structuredResult;
3468
+ } catch (e) {
3469
+ logger.error(`\u274C Structured output failed: ${e}`);
3470
+ throw new Error(`Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`);
3471
+ }
3472
+ }
3473
+ logger.info(`\u{1F389} Agent execution complete in ${((Date.now() - startTime) / 1e3).toFixed(2)} seconds`);
3474
+ success = true;
3475
+ return finalOutput || "No output generated";
3426
3476
  } catch (e) {
3427
3477
  logger.error(`\u274C Error running query: ${e}`);
3428
3478
  if (initializedHere && manageConnector) {
3429
- logger.info("\u{1F9F9} Cleaning up resources after initialization error in run");
3479
+ logger.info("\u{1F9F9} Cleaning up resources after error");
3430
3480
  await this.close();
3431
3481
  }
3432
3482
  throw e;
@@ -3439,16 +3489,17 @@ var MCPAgent = class {
3439
3489
  serverCount = this.connectors.length;
3440
3490
  }
3441
3491
  const conversationHistoryLength = this.memoryEnabled ? this.conversationHistory.length : 0;
3492
+ const toolsAvailable = this._tools || [];
3442
3493
  await this.telemetry.trackAgentExecution({
3443
3494
  executionMethod: "stream",
3444
3495
  query,
3445
- success: structuredOutputSuccess,
3496
+ success,
3446
3497
  modelProvider: this.modelProvider,
3447
3498
  modelName: this.modelName,
3448
3499
  serverCount,
3449
3500
  serverIdentifiers: this.connectors.map((connector) => connector.publicIdentifier),
3450
- totalToolsAvailable: this._tools.length,
3451
- toolsAvailableNames: this._tools.map((t) => t.name),
3501
+ totalToolsAvailable: toolsAvailable.length,
3502
+ toolsAvailableNames: toolsAvailable.map((t) => t.name),
3452
3503
  maxStepsConfigured: this.maxSteps,
3453
3504
  memoryEnabled: this.memoryEnabled,
3454
3505
  useServerManager: this.useServerManager,
@@ -3456,19 +3507,30 @@ var MCPAgent = class {
3456
3507
  manageConnector,
3457
3508
  externalHistoryUsed: externalHistory !== void 0,
3458
3509
  stepsTaken,
3459
- toolsUsedCount: toolsUsedNames.length,
3460
- toolsUsedNames,
3461
- response: result,
3510
+ toolsUsedCount: this.toolsUsedNames.length,
3511
+ toolsUsedNames: this.toolsUsedNames,
3512
+ response: finalOutput || "",
3462
3513
  executionTimeMs,
3463
- errorType: structuredOutputSuccess ? null : "execution_error",
3514
+ errorType: success ? null : "execution_error",
3464
3515
  conversationHistoryLength
3465
3516
  });
3466
3517
  if (manageConnector && !this.client && initializedHere) {
3467
- logger.info("\u{1F9F9} Closing agent after query completion");
3518
+ logger.info("\u{1F9F9} Closing agent after stream completion");
3468
3519
  await this.close();
3469
3520
  }
3470
3521
  }
3471
3522
  }
3523
+ /**
3524
+ * Flush observability traces to the configured observability platform.
3525
+ * Important for serverless environments where traces need to be sent before function termination.
3526
+ */
3527
+ async flush() {
3528
+ if (this.isRemote && this.remoteAgent) {
3529
+ return;
3530
+ }
3531
+ logger.debug("Flushing observability traces...");
3532
+ await this.observabilityManager.flush();
3533
+ }
3472
3534
  async close() {
3473
3535
  if (this.isRemote && this.remoteAgent) {
3474
3536
  await this.remoteAgent.close();
@@ -3519,34 +3581,40 @@ var MCPAgent = class {
3519
3581
  await this.initialize();
3520
3582
  initializedHere = true;
3521
3583
  }
3522
- const agentExecutor = this.agentExecutor;
3584
+ const agentExecutor = this._agentExecutor;
3523
3585
  if (!agentExecutor) {
3524
3586
  throw new Error("MCP agent failed to initialize");
3525
3587
  }
3526
- const steps = maxSteps ?? this.maxSteps;
3527
- agentExecutor.maxIterations = steps;
3588
+ this.maxSteps = maxSteps ?? this.maxSteps;
3528
3589
  const display_query = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
3529
3590
  logger.info(`\u{1F4AC} Received query for streamEvents: '${display_query}'`);
3530
3591
  if (this.memoryEnabled) {
3531
3592
  logger.info(`\u{1F504} Adding user message to history: ${query}`);
3532
- this.addToHistory(new import_messages2.HumanMessage(query));
3593
+ this.addToHistory(new import_messages.HumanMessage(query));
3533
3594
  }
3534
3595
  const historyToUse = externalHistory ?? this.conversationHistory;
3535
3596
  const langchainHistory = [];
3536
3597
  for (const msg of historyToUse) {
3537
- if (msg instanceof import_messages2.HumanMessage || msg instanceof import_messages2.AIMessage || msg instanceof import_messages2.ToolMessage) {
3598
+ if (msg instanceof import_messages.HumanMessage || msg instanceof import_messages.AIMessage || msg instanceof import_messages.ToolMessage) {
3538
3599
  langchainHistory.push(msg);
3539
3600
  } else {
3540
3601
  logger.info(`\u26A0\uFE0F Skipped message of type: ${msg.constructor.name}`);
3541
3602
  }
3542
3603
  }
3543
- const inputs = { input: query, chat_history: langchainHistory };
3604
+ const inputs = [...langchainHistory, new import_messages.HumanMessage(query)];
3544
3605
  logger.info("callbacks", this.callbacks);
3545
3606
  const eventStream = agentExecutor.streamEvents(
3546
- inputs,
3607
+ { messages: inputs },
3547
3608
  {
3609
+ streamMode: "messages",
3548
3610
  version: "v2",
3549
- callbacks: this.callbacks.length > 0 ? this.callbacks : void 0
3611
+ callbacks: this.callbacks,
3612
+ metadata: this.getMetadata(),
3613
+ tags: this.getTags(),
3614
+ // Set trace name for LangChain/Langfuse
3615
+ runName: this.metadata.trace_name || "mcp-use-agent",
3616
+ // Pass sessionId for Langfuse if present in metadata
3617
+ ...this.metadata.session_id && { sessionId: this.metadata.session_id }
3550
3618
  }
3551
3619
  );
3552
3620
  for await (const event of eventStream) {
@@ -3557,8 +3625,20 @@ var MCPAgent = class {
3557
3625
  if (event.event === "on_chat_model_stream" && event.data?.chunk?.content) {
3558
3626
  totalResponseLength += event.data.chunk.content.length;
3559
3627
  }
3628
+ if (event.event === "on_chat_model_stream" && event.data?.chunk) {
3629
+ logger.info("on_chat_model_stream", event.data.chunk);
3630
+ const chunk = event.data.chunk;
3631
+ if (chunk.content) {
3632
+ if (!finalResponse) {
3633
+ finalResponse = "";
3634
+ }
3635
+ const normalizedContent = this._normalizeOutput(chunk.content);
3636
+ finalResponse += normalizedContent;
3637
+ logger.debug(`\u{1F4DD} Accumulated response length: ${finalResponse.length}`);
3638
+ }
3639
+ }
3560
3640
  yield event;
3561
- if (event.event === "on_chain_end" && event.data?.output) {
3641
+ if (event.event === "on_chain_end" && event.data?.output && !finalResponse) {
3562
3642
  const output = event.data.output;
3563
3643
  if (Array.isArray(output) && output.length > 0 && output[0]?.text) {
3564
3644
  finalResponse = output[0].text;
@@ -3575,7 +3655,7 @@ var MCPAgent = class {
3575
3655
  let conversionCompleted = false;
3576
3656
  let conversionResult = null;
3577
3657
  let conversionError = null;
3578
- const _conversionPromise = this._attemptStructuredOutput(
3658
+ this._attemptStructuredOutput(
3579
3659
  finalResponse,
3580
3660
  this.llm,
3581
3661
  outputSchema
@@ -3611,7 +3691,7 @@ var MCPAgent = class {
3611
3691
  data: { output: conversionResult }
3612
3692
  };
3613
3693
  if (this.memoryEnabled) {
3614
- this.addToHistory(new import_messages2.AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
3694
+ this.addToHistory(new import_messages.AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
3615
3695
  }
3616
3696
  logger.info("\u2705 Structured output successful");
3617
3697
  }
@@ -3623,7 +3703,7 @@ var MCPAgent = class {
3623
3703
  };
3624
3704
  }
3625
3705
  } else if (this.memoryEnabled && finalResponse) {
3626
- this.addToHistory(new import_messages2.AIMessage(finalResponse));
3706
+ this.addToHistory(new import_messages.AIMessage(finalResponse));
3627
3707
  }
3628
3708
  logger.info(`\u{1F389} StreamEvents complete - ${eventCount} events emitted`);
3629
3709
  success = true;
@@ -3672,6 +3752,10 @@ var MCPAgent = class {
3672
3752
  }
3673
3753
  /**
3674
3754
  * Attempt to create structured output from raw result with validation and retry logic.
3755
+ *
3756
+ * @param rawResult - The raw text result from the agent
3757
+ * @param llm - LLM to use for structured output
3758
+ * @param outputSchema - The Zod schema to validate against
3675
3759
  */
3676
3760
  async _attemptStructuredOutput(rawResult, llm, outputSchema) {
3677
3761
  logger.info(`\u{1F504} Attempting structured output with schema: ${outputSchema}`);
@@ -3686,7 +3770,9 @@ var MCPAgent = class {
3686
3770
  } else {
3687
3771
  throw new Error("LLM is required for structured output");
3688
3772
  }
3689
- schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
3773
+ const jsonSchema = (0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema);
3774
+ const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;
3775
+ schemaDescription = JSON.stringify(cleanSchema, null, 2);
3690
3776
  logger.info(`\u{1F504} Schema description: ${schemaDescription}`);
3691
3777
  let textContent = "";
3692
3778
  if (typeof rawResult === "string") {
@@ -3694,6 +3780,7 @@ var MCPAgent = class {
3694
3780
  } else if (rawResult && typeof rawResult === "object") {
3695
3781
  textContent = JSON.stringify(rawResult);
3696
3782
  }
3783
+ logger.info("rawResult", rawResult);
3697
3784
  if (!textContent) {
3698
3785
  textContent = JSON.stringify(rawResult);
3699
3786
  }
@@ -3704,28 +3791,34 @@ var MCPAgent = class {
3704
3791
  let formatPrompt = `
3705
3792
  Please format the following information according to the EXACT schema specified below.
3706
3793
  You must use the exact field names and types as shown in the schema.
3707
-
3794
+
3708
3795
  Required schema format:
3709
3796
  ${schemaDescription}
3710
-
3797
+
3711
3798
  Content to extract from:
3712
3799
  ${textContent}
3713
-
3714
- IMPORTANT:
3800
+
3801
+ IMPORTANT:
3715
3802
  - Use ONLY the field names specified in the schema
3716
3803
  - Match the data types exactly (string, number, boolean, array, etc.)
3717
3804
  - Include ALL required fields
3718
3805
  - Return valid JSON that matches the schema structure exactly
3806
+ - For missing data: use null for nullable fields, omit optional fields entirely
3807
+ - Do NOT use empty strings ("") or zero (0) as placeholders for missing data
3719
3808
  `;
3720
3809
  if (attempt > 1) {
3721
3810
  formatPrompt += `
3722
-
3811
+
3723
3812
  PREVIOUS ATTEMPT FAILED with error: ${lastError}
3724
3813
  Please fix the issues mentioned above and ensure the output matches the schema exactly.
3725
3814
  `;
3726
3815
  }
3727
3816
  try {
3728
3817
  logger.info(`\u{1F504} Structured output attempt ${attempt} - using streaming approach`);
3818
+ const contentPreview = textContent.length > 300 ? `${textContent.slice(0, 300)}...` : textContent;
3819
+ logger.info(`\u{1F504} Content being formatted (${textContent.length} chars): ${contentPreview}`);
3820
+ logger.info(`\u{1F504} Full format prompt (${formatPrompt.length} chars):
3821
+ ${formatPrompt}`);
3729
3822
  const stream = await structuredLlm.stream(formatPrompt);
3730
3823
  let structuredResult = null;
3731
3824
  let chunkCount = 0;
@@ -3801,14 +3894,16 @@ var MCPAgent = class {
3801
3894
  */
3802
3895
  _enhanceQueryWithSchema(query, outputSchema) {
3803
3896
  try {
3804
- const schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
3897
+ const jsonSchema = (0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema);
3898
+ const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;
3899
+ const schemaDescription = JSON.stringify(cleanSchema, null, 2);
3805
3900
  const enhancedQuery = `
3806
3901
  ${query}
3807
-
3902
+
3808
3903
  IMPORTANT: Your response must include sufficient information to populate the following structured output:
3809
-
3904
+
3810
3905
  ${schemaDescription}
3811
-
3906
+
3812
3907
  Make sure you gather ALL the required information during your task execution.
3813
3908
  If any required information is missing, continue working to find it.
3814
3909
  `;
@@ -4171,7 +4266,7 @@ async function* streamEventsToAISDKWithTools(streamEvents) {
4171
4266
  __name(streamEventsToAISDKWithTools, "streamEventsToAISDKWithTools");
4172
4267
 
4173
4268
  // src/browser.ts
4174
- var import_messages3 = require("@langchain/core/messages");
4269
+ var import_messages2 = require("@langchain/core/messages");
4175
4270
  // Annotate the CommonJS export names for ESM import in node:
4176
4271
  0 && (module.exports = {
4177
4272
  AIMessage,