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
package/dist/index.cjs CHANGED
@@ -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,16 +484,16 @@ var init_langfuse = __esm({
469
484
  // index.ts
470
485
  var index_exports = {};
471
486
  __export(index_exports, {
472
- AIMessage: () => import_messages3.AIMessage,
487
+ AIMessage: () => import_messages2.AIMessage,
473
488
  AcquireActiveMCPServerTool: () => AcquireActiveMCPServerTool,
474
489
  AddMCPServerFromConfigTool: () => AddMCPServerFromConfigTool,
475
490
  BaseAdapter: () => BaseAdapter,
476
491
  BaseConnector: () => BaseConnector,
477
- BaseMessage: () => import_messages3.BaseMessage,
492
+ BaseMessage: () => import_messages2.BaseMessage,
478
493
  BrowserOAuthClientProvider: () => BrowserOAuthClientProvider,
479
494
  ConnectMCPServerTool: () => ConnectMCPServerTool,
480
495
  HttpConnector: () => HttpConnector,
481
- HumanMessage: () => import_messages3.HumanMessage,
496
+ HumanMessage: () => import_messages2.HumanMessage,
482
497
  LINEAR_OAUTH_CONFIG: () => LINEAR_OAUTH_CONFIG,
483
498
  LangChainAdapter: () => LangChainAdapter,
484
499
  ListMCPServersTool: () => ListMCPServersTool,
@@ -492,9 +507,9 @@ __export(index_exports, {
492
507
  RemoteAgent: () => RemoteAgent,
493
508
  ServerManager: () => ServerManager,
494
509
  StdioConnector: () => StdioConnector,
495
- SystemMessage: () => import_messages3.SystemMessage,
510
+ SystemMessage: () => import_messages2.SystemMessage,
496
511
  Telemetry: () => Telemetry,
497
- ToolMessage: () => import_messages3.ToolMessage,
512
+ ToolMessage: () => import_messages2.ToolMessage,
498
513
  WebSocketConnector: () => WebSocketConnector,
499
514
  createOAuthMCPConfig: () => createOAuthMCPConfig,
500
515
  createReadableStreamFromGenerator: () => createReadableStreamFromGenerator,
@@ -513,11 +528,8 @@ __export(index_exports, {
513
528
  module.exports = __toCommonJS(index_exports);
514
529
 
515
530
  // src/agents/mcp_agent.ts
516
- var import_manager2 = require("@langchain/core/callbacks/manager");
517
- var import_messages2 = require("@langchain/core/messages");
518
- var import_output_parsers = require("@langchain/core/output_parsers");
519
- var import_prompts = require("@langchain/core/prompts");
520
- var import_agents = require("langchain/agents");
531
+ var import_messages = require("@langchain/core/messages");
532
+ var import_langchain2 = require("langchain");
521
533
  var import_zod_to_json_schema2 = require("zod-to-json-schema");
522
534
 
523
535
  // src/adapters/langchain_adapter.ts
@@ -738,7 +750,7 @@ var AcquireActiveMCPServerTool = class extends MCPServerTool {
738
750
  };
739
751
 
740
752
  // src/managers/tools/add_server_from_config.ts
741
- var import_tools3 = require("langchain/tools");
753
+ var import_tools3 = require("@langchain/core/tools");
742
754
  var import_zod3 = require("zod");
743
755
  init_logging();
744
756
  var AddMCPServerFromConfigTool = class extends import_tools3.StructuredTool {
@@ -1111,6 +1123,23 @@ var ObservabilityManager = class {
1111
1123
  const callbacks = await this.getCallbacks();
1112
1124
  return callbacks.length > 0;
1113
1125
  }
1126
+ /**
1127
+ * Get the current observability status including metadata and tags.
1128
+ * @returns Object containing enabled status, callback count, handler names, metadata, and tags.
1129
+ */
1130
+ async getStatus() {
1131
+ const callbacks = await this.getCallbacks();
1132
+ const handlerNames = await this.getHandlerNames();
1133
+ const currentMetadata = this.metadataProvider ? this.metadataProvider() : this.metadata || {};
1134
+ const currentTags = this.tagsProvider ? this.tagsProvider() : [];
1135
+ return {
1136
+ enabled: this.observe && callbacks.length > 0,
1137
+ callbackCount: callbacks.length,
1138
+ handlerNames,
1139
+ metadata: currentMetadata,
1140
+ tags: currentTags
1141
+ };
1142
+ }
1114
1143
  /**
1115
1144
  * Add a callback to the custom callbacks list.
1116
1145
  * @param callback The callback to add.
@@ -1548,7 +1577,7 @@ function setTelemetrySource(source) {
1548
1577
  __name(setTelemetrySource, "setTelemetrySource");
1549
1578
 
1550
1579
  // src/agents/prompts/system_prompt_builder.ts
1551
- var import_messages = require("@langchain/core/messages");
1580
+ var import_langchain = require("langchain");
1552
1581
  function generateToolDescriptions(tools, disallowedTools) {
1553
1582
  const disallowedSet = new Set(disallowedTools ?? []);
1554
1583
  const descriptions = [];
@@ -1583,7 +1612,7 @@ ${additionalInstructions}`;
1583
1612
  __name(buildSystemPromptContent, "buildSystemPromptContent");
1584
1613
  function createSystemMessage(tools, systemPromptTemplate, serverManagerTemplate, useServerManager, disallowedTools, userProvidedPrompt, additionalInstructions) {
1585
1614
  if (userProvidedPrompt) {
1586
- return new import_messages.SystemMessage({ content: userProvidedPrompt });
1615
+ return new import_langchain.SystemMessage({ content: userProvidedPrompt });
1587
1616
  }
1588
1617
  const template = useServerManager ? serverManagerTemplate : systemPromptTemplate;
1589
1618
  const toolLines = generateToolDescriptions(tools, disallowedTools);
@@ -1592,7 +1621,7 @@ function createSystemMessage(tools, systemPromptTemplate, serverManagerTemplate,
1592
1621
  toolLines,
1593
1622
  additionalInstructions
1594
1623
  );
1595
- return new import_messages.SystemMessage({ content: finalContent });
1624
+ return new import_langchain.SystemMessage({ content: finalContent });
1596
1625
  }
1597
1626
  __name(createSystemMessage, "createSystemMessage");
1598
1627
 
@@ -1869,6 +1898,7 @@ var MCPAgent = class {
1869
1898
  memoryEnabled;
1870
1899
  disallowedTools;
1871
1900
  additionalTools;
1901
+ toolsUsedNames = [];
1872
1902
  useServerManager;
1873
1903
  verbose;
1874
1904
  observe;
@@ -1936,6 +1966,7 @@ var MCPAgent = class {
1936
1966
  this.additionalInstructions = options.additionalInstructions ?? null;
1937
1967
  this.disallowedTools = options.disallowedTools ?? [];
1938
1968
  this.additionalTools = options.additionalTools ?? [];
1969
+ this.toolsUsedNames = options.toolsUsedNames ?? [];
1939
1970
  this.useServerManager = options.useServerManager ?? false;
1940
1971
  this.verbose = options.verbose ?? false;
1941
1972
  this.observe = options.observe ?? true;
@@ -2050,7 +2081,7 @@ var MCPAgent = class {
2050
2081
  if (this.memoryEnabled) {
2051
2082
  this.conversationHistory = [
2052
2083
  this.systemMessage,
2053
- ...this.conversationHistory.filter((m) => !(m instanceof import_messages2.SystemMessage))
2084
+ ...this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage))
2054
2085
  ];
2055
2086
  }
2056
2087
  }
@@ -2059,25 +2090,17 @@ var MCPAgent = class {
2059
2090
  throw new Error("LLM is required to create agent");
2060
2091
  }
2061
2092
  const systemContent = this.systemMessage?.content ?? "You are a helpful assistant.";
2062
- const prompt = import_prompts.ChatPromptTemplate.fromMessages([
2063
- ["system", systemContent],
2064
- new import_prompts.MessagesPlaceholder("chat_history"),
2065
- ["human", "{input}"],
2066
- new import_prompts.MessagesPlaceholder("agent_scratchpad")
2067
- ]);
2068
- const agent = (0, import_agents.createToolCallingAgent)({
2069
- llm: this.llm,
2093
+ const toolNames = this._tools.map((tool) => tool.name);
2094
+ logger.info(`\u{1F9E0} Agent ready with tools: ${toolNames.join(", ")}`);
2095
+ const middleware = [(0, import_langchain2.modelCallLimitMiddleware)({ runLimit: this.maxSteps })];
2096
+ const agent = (0, import_langchain2.createAgent)({
2097
+ model: this.llm,
2070
2098
  tools: this._tools,
2071
- prompt
2072
- });
2073
- return new import_agents.AgentExecutor({
2074
- agent,
2075
- tools: this._tools,
2076
- maxIterations: this.maxSteps,
2077
- verbose: this.verbose,
2078
- returnIntermediateSteps: true,
2079
- callbacks: this.callbacks
2099
+ systemPrompt: systemContent,
2100
+ middleware
2080
2101
  });
2102
+ logger.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`);
2103
+ return agent;
2081
2104
  }
2082
2105
  getConversationHistory() {
2083
2106
  return [...this.conversationHistory];
@@ -2093,9 +2116,9 @@ var MCPAgent = class {
2093
2116
  return this.systemMessage;
2094
2117
  }
2095
2118
  setSystemMessage(message) {
2096
- this.systemMessage = new import_messages2.SystemMessage(message);
2119
+ this.systemMessage = new import_langchain2.SystemMessage(message);
2097
2120
  if (this.memoryEnabled) {
2098
- this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof import_messages2.SystemMessage));
2121
+ this.conversationHistory = this.conversationHistory.filter((m) => !(m instanceof import_langchain2.SystemMessage));
2099
2122
  this.conversationHistory.unshift(this.systemMessage);
2100
2123
  }
2101
2124
  if (this._initialized && this._tools.length) {
@@ -2245,6 +2268,42 @@ var MCPAgent = class {
2245
2268
  }
2246
2269
  return serverInfo;
2247
2270
  }
2271
+ _normalizeOutput(value) {
2272
+ try {
2273
+ if (typeof value === "string") {
2274
+ return value;
2275
+ }
2276
+ if (value && typeof value === "object" && "content" in value) {
2277
+ return this._normalizeOutput(value.content);
2278
+ }
2279
+ if (Array.isArray(value)) {
2280
+ const parts = [];
2281
+ for (const item of value) {
2282
+ if (typeof item === "object" && item !== null) {
2283
+ if ("text" in item && typeof item.text === "string") {
2284
+ parts.push(item.text);
2285
+ } else if ("content" in item) {
2286
+ parts.push(this._normalizeOutput(item.content));
2287
+ } else {
2288
+ parts.push(String(item));
2289
+ }
2290
+ } else {
2291
+ const partText = item && typeof item === "object" && "text" in item ? item.text : null;
2292
+ if (typeof partText === "string") {
2293
+ parts.push(partText);
2294
+ } else {
2295
+ const partContent = item && typeof item === "object" && "content" in item ? item.content : item;
2296
+ parts.push(this._normalizeOutput(partContent));
2297
+ }
2298
+ }
2299
+ }
2300
+ return parts.join("");
2301
+ }
2302
+ return String(value);
2303
+ } catch (error) {
2304
+ return String(value);
2305
+ }
2306
+ }
2248
2307
  async _consumeAndReturn(generator) {
2249
2308
  while (true) {
2250
2309
  const { done, value } = await generator.next();
@@ -2266,36 +2325,16 @@ var MCPAgent = class {
2266
2325
  );
2267
2326
  return this._consumeAndReturn(generator);
2268
2327
  }
2269
- /**
2270
- * Runs the agent and yields intermediate steps as an async generator.
2271
- * If outputSchema is provided, returns structured output of type T.
2272
- */
2273
2328
  async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
2274
2329
  if (this.isRemote && this.remoteAgent) {
2275
- const result2 = await this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
2276
- return result2;
2330
+ const result = await this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
2331
+ return result;
2277
2332
  }
2278
- let result = "";
2279
2333
  let initializedHere = false;
2280
2334
  const startTime = Date.now();
2281
- const toolsUsedNames = [];
2335
+ let success = false;
2336
+ let finalOutput = null;
2282
2337
  let stepsTaken = 0;
2283
- const structuredOutputSuccess = false;
2284
- const structuredOutputSuccessRef = { value: structuredOutputSuccess };
2285
- let structuredLlm = null;
2286
- let schemaDescription = "";
2287
- if (outputSchema) {
2288
- query = this._enhanceQueryWithSchema(query, outputSchema);
2289
- logger.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`);
2290
- if (this.llm && "withStructuredOutput" in this.llm && typeof this.llm.withStructuredOutput === "function") {
2291
- structuredLlm = this.llm.withStructuredOutput(outputSchema);
2292
- } else if (this.llm) {
2293
- structuredLlm = this.llm;
2294
- } else {
2295
- throw new Error("LLM is required for structured output");
2296
- }
2297
- schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
2298
- }
2299
2338
  try {
2300
2339
  if (manageConnector && !this._initialized) {
2301
2340
  await this.initialize();
@@ -2307,158 +2346,169 @@ var MCPAgent = class {
2307
2346
  if (!this._agentExecutor) {
2308
2347
  throw new Error("MCP agent failed to initialize");
2309
2348
  }
2310
- const steps = maxSteps ?? this.maxSteps;
2311
- this._agentExecutor.maxIterations = steps;
2312
- const display_query = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
2313
- logger.info(`\u{1F4AC} Received query: '${display_query}'`);
2314
- if (this.memoryEnabled) {
2315
- this.addToHistory(new import_messages2.HumanMessage(query));
2349
+ if (this.useServerManager && this.serverManager) {
2350
+ const currentTools = this.serverManager.tools;
2351
+ const currentToolNames = new Set(currentTools.map((t) => t.name));
2352
+ const existingToolNames = new Set(this._tools.map((t) => t.name));
2353
+ if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
2354
+ logger.info(
2355
+ `\u{1F504} Tools changed before execution, updating agent. New tools: ${[...currentToolNames].join(", ")}`
2356
+ );
2357
+ this._tools = currentTools;
2358
+ this._tools.push(...this.additionalTools);
2359
+ await this.createSystemMessageFromTools(this._tools);
2360
+ this._agentExecutor = this.createAgent();
2361
+ }
2316
2362
  }
2317
2363
  const historyToUse = externalHistory ?? this.conversationHistory;
2318
2364
  const langchainHistory = [];
2319
2365
  for (const msg of historyToUse) {
2320
- if (msg instanceof import_messages2.HumanMessage || msg instanceof import_messages2.AIMessage) {
2366
+ if (msg instanceof import_messages.HumanMessage || msg instanceof import_messages.AIMessage) {
2321
2367
  langchainHistory.push(msg);
2322
2368
  }
2323
2369
  }
2324
- const intermediateSteps = [];
2325
- const inputs = { input: query, chat_history: langchainHistory };
2326
- let nameToToolMap = Object.fromEntries(this._tools.map((t) => [t.name, t]));
2327
- logger.info(`\u{1F3C1} Starting agent execution with max_steps=${steps}`);
2328
- let runManager;
2329
- if (this.callbacks?.length > 0) {
2330
- const callbackManager = new import_manager2.CallbackManager(void 0, {
2331
- handlers: this.callbacks,
2332
- inheritableHandlers: this.callbacks
2333
- });
2334
- runManager = await callbackManager.handleChainStart({
2335
- name: "MCPAgent (mcp-use)",
2336
- id: ["MCPAgent (mcp-use)"],
2337
- lc: 1,
2338
- type: "not_implemented"
2339
- }, inputs);
2340
- }
2341
- for (let stepNum = 0; stepNum < steps; stepNum++) {
2342
- stepsTaken = stepNum + 1;
2343
- if (this.useServerManager && this.serverManager) {
2344
- const currentTools = this.serverManager.tools;
2345
- const currentToolNames = new Set(currentTools.map((t) => t.name));
2346
- const existingToolNames = new Set(this._tools.map((t) => t.name));
2347
- const changed = currentTools.length !== this._tools.length || [...currentToolNames].some((n) => !existingToolNames.has(n));
2348
- if (changed) {
2349
- logger.info(
2350
- `\u{1F504} Tools changed before step ${stepNum + 1}, updating agent. New tools: ${[...currentToolNames].join(", ")}`
2351
- );
2352
- this._tools = currentTools;
2353
- this._tools.push(...this.additionalTools);
2354
- await this.createSystemMessageFromTools(this._tools);
2355
- this._agentExecutor = this.createAgent();
2356
- this._agentExecutor.maxIterations = steps;
2357
- nameToToolMap = Object.fromEntries(this._tools.map((t) => [t.name, t]));
2370
+ const displayQuery = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
2371
+ logger.info(`\u{1F4AC} Received query: '${displayQuery}'`);
2372
+ logger.info("\u{1F3C1} Starting agent execution");
2373
+ const maxRestarts = 3;
2374
+ let restartCount = 0;
2375
+ const accumulatedMessages = [...langchainHistory, new import_messages.HumanMessage(query)];
2376
+ while (restartCount <= maxRestarts) {
2377
+ const inputs = { messages: accumulatedMessages };
2378
+ let shouldRestart = false;
2379
+ const stream = await this._agentExecutor.stream(
2380
+ inputs,
2381
+ {
2382
+ streamMode: "updates",
2383
+ // Get updates as they happen
2384
+ callbacks: this.callbacks,
2385
+ metadata: this.getMetadata(),
2386
+ tags: this.getTags(),
2387
+ // Set trace name for LangChain/Langfuse
2388
+ runName: this.metadata.trace_name || "mcp-use-agent",
2389
+ // Pass sessionId for Langfuse if present in metadata
2390
+ ...this.metadata.session_id && { sessionId: this.metadata.session_id }
2358
2391
  }
2359
- }
2360
- logger.info(`\u{1F463} Step ${stepNum + 1}/${steps}`);
2361
- try {
2362
- logger.debug("Starting agent step execution");
2363
- const nextStepOutput = await this._agentExecutor._takeNextStep(
2364
- nameToToolMap,
2365
- inputs,
2366
- intermediateSteps,
2367
- runManager
2368
- );
2369
- if ("returnValues" in nextStepOutput) {
2370
- logger.info(`\u2705 Agent finished at step ${stepNum + 1}`);
2371
- result = nextStepOutput.returnValues?.output ?? "No output generated";
2372
- runManager?.handleChainEnd({ output: result });
2373
- if (outputSchema && structuredLlm) {
2374
- logger.info("\u{1F527} Attempting structured output...");
2375
- const currentResult = result;
2376
- this._attemptStructuredOutput(
2377
- currentResult,
2378
- this.llm,
2379
- outputSchema
2380
- ).then((structuredResult) => {
2381
- if (this.memoryEnabled) {
2382
- this.addToHistory(new import_messages2.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
2392
+ );
2393
+ for await (const chunk of stream) {
2394
+ for (const [nodeName, nodeOutput] of Object.entries(chunk)) {
2395
+ logger.debug(`\u{1F4E6} Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`);
2396
+ if (nodeOutput && typeof nodeOutput === "object" && "messages" in nodeOutput) {
2397
+ let messages = nodeOutput.messages;
2398
+ if (!Array.isArray(messages)) {
2399
+ messages = [messages];
2400
+ }
2401
+ for (const msg of messages) {
2402
+ if (!accumulatedMessages.includes(msg)) {
2403
+ accumulatedMessages.push(msg);
2383
2404
  }
2384
- logger.info("\u2705 Structured output successful");
2385
- structuredOutputSuccessRef.value = true;
2386
- return structuredResult;
2387
- }).catch((e) => {
2388
- logger.warn(`\u26A0\uFE0F Structured output failed: ${e}`);
2389
- const failedStructuredOutputPrompt = `
2390
- The current result cannot be formatted into the required structure.
2391
- Error: ${String(e)}
2392
-
2393
- Current information: ${currentResult}
2394
-
2395
- If information is missing, please continue working to gather the missing information needed for:
2396
- ${schemaDescription}
2397
-
2398
- If the information is complete, please return the result in the required structure.
2399
- `;
2400
- inputs.input = failedStructuredOutputPrompt;
2401
- if (this.memoryEnabled) {
2402
- this.addToHistory(new import_messages2.HumanMessage(failedStructuredOutputPrompt));
2405
+ }
2406
+ for (const message of messages) {
2407
+ if ("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
2408
+ for (const toolCall of message.tool_calls) {
2409
+ const toolName = toolCall.name || "unknown";
2410
+ const toolInput = toolCall.args || {};
2411
+ this.toolsUsedNames.push(toolName);
2412
+ stepsTaken++;
2413
+ let toolInputStr = JSON.stringify(toolInput);
2414
+ if (toolInputStr.length > 100) {
2415
+ toolInputStr = `${toolInputStr.slice(0, 97)}...`;
2416
+ }
2417
+ logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
2418
+ yield {
2419
+ action: {
2420
+ tool: toolName,
2421
+ toolInput,
2422
+ log: `Calling tool ${toolName}`
2423
+ },
2424
+ observation: ""
2425
+ // Will be filled in by tool result
2426
+ };
2427
+ }
2403
2428
  }
2404
- logger.info("\u{1F504} Continuing execution to gather missing information...");
2405
- });
2406
- }
2407
- }
2408
- if (Array.isArray(nextStepOutput)) {
2409
- const stepArray = nextStepOutput;
2410
- intermediateSteps.push(...stepArray);
2411
- for (const step of stepArray) {
2412
- yield step;
2413
- const { action, observation } = step;
2414
- const toolName = action.tool;
2415
- toolsUsedNames.push(toolName);
2416
- let toolInputStr = typeof action.toolInput === "string" ? action.toolInput : JSON.stringify(action.toolInput, null, 2);
2417
- if (toolInputStr.length > 100)
2418
- toolInputStr = `${toolInputStr.slice(0, 97)}...`;
2419
- logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
2420
- let outputStr = String(observation);
2421
- if (outputStr.length > 100)
2422
- outputStr = `${outputStr.slice(0, 97)}...`;
2423
- outputStr = outputStr.replace(/\n/g, " ");
2424
- logger.info(`\u{1F4C4} Tool result: ${outputStr}`);
2425
- }
2426
- if (stepArray.length) {
2427
- const lastStep = stepArray[stepArray.length - 1];
2428
- const toolReturn = await this._agentExecutor._getToolReturn(lastStep);
2429
- if (toolReturn) {
2430
- logger.info(`\u{1F3C6} Tool returned directly at step ${stepNum + 1}`);
2431
- result = toolReturn.returnValues?.output ?? "No output generated";
2429
+ if (message instanceof import_messages.ToolMessage || message && "type" in message && message.type === "tool") {
2430
+ const observation = message.content;
2431
+ let observationStr = String(observation);
2432
+ if (observationStr.length > 100) {
2433
+ observationStr = `${observationStr.slice(0, 97)}...`;
2434
+ }
2435
+ observationStr = observationStr.replace(/\n/g, " ");
2436
+ logger.info(`\u{1F4C4} Tool result: ${observationStr}`);
2437
+ if (this.useServerManager && this.serverManager) {
2438
+ const currentTools = this.serverManager.tools;
2439
+ const currentToolNames = new Set(currentTools.map((t) => t.name));
2440
+ const existingToolNames = new Set(this._tools.map((t) => t.name));
2441
+ if (currentToolNames.size !== existingToolNames.size || [...currentToolNames].some((n) => !existingToolNames.has(n))) {
2442
+ logger.info(
2443
+ `\u{1F504} Tools changed during execution. New tools: ${[...currentToolNames].join(", ")}`
2444
+ );
2445
+ this._tools = currentTools;
2446
+ this._tools.push(...this.additionalTools);
2447
+ await this.createSystemMessageFromTools(this._tools);
2448
+ this._agentExecutor = this.createAgent();
2449
+ shouldRestart = true;
2450
+ restartCount++;
2451
+ logger.info(
2452
+ `\u{1F503} Restarting execution with updated tools (restart ${restartCount}/${maxRestarts})`
2453
+ );
2454
+ break;
2455
+ }
2456
+ }
2457
+ }
2458
+ if (message instanceof import_messages.AIMessage && !("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0)) {
2459
+ finalOutput = this._normalizeOutput(message.content);
2460
+ logger.info("\u2705 Agent finished with output");
2461
+ }
2462
+ }
2463
+ if (shouldRestart) {
2432
2464
  break;
2433
2465
  }
2434
2466
  }
2435
2467
  }
2436
- } catch (e) {
2437
- if (e instanceof import_output_parsers.OutputParserException) {
2438
- logger.error(`\u274C Output parsing error during step ${stepNum + 1}: ${e}`);
2439
- result = `Agent stopped due to a parsing error: ${e}`;
2440
- runManager?.handleChainError(result);
2468
+ if (shouldRestart) {
2441
2469
  break;
2442
2470
  }
2443
- logger.error(`\u274C Error during agent execution step ${stepNum + 1}: ${e}`);
2444
- console.error(e);
2445
- result = `Agent stopped due to an error: ${e}`;
2446
- runManager?.handleChainError(result);
2471
+ }
2472
+ if (!shouldRestart) {
2473
+ break;
2474
+ }
2475
+ if (restartCount > maxRestarts) {
2476
+ logger.warn(`\u26A0\uFE0F Max restarts (${maxRestarts}) reached. Continuing with current tools.`);
2447
2477
  break;
2448
2478
  }
2449
2479
  }
2450
- if (!result) {
2451
- logger.warn(`\u26A0\uFE0F Agent stopped after reaching max iterations (${steps})`);
2452
- result = `Agent stopped after reaching the maximum number of steps (${steps}).`;
2453
- runManager?.handleChainEnd({ output: result });
2480
+ if (this.memoryEnabled) {
2481
+ this.addToHistory(new import_messages.HumanMessage(query));
2482
+ if (finalOutput) {
2483
+ this.addToHistory(new import_messages.AIMessage(finalOutput));
2484
+ }
2454
2485
  }
2455
- logger.info("\u{1F389} Agent execution complete");
2456
- structuredOutputSuccessRef.value = true;
2457
- return result;
2486
+ if (outputSchema && finalOutput) {
2487
+ try {
2488
+ logger.info("\u{1F527} Attempting structured output...");
2489
+ const structuredResult = await this._attemptStructuredOutput(
2490
+ finalOutput,
2491
+ this.llm,
2492
+ outputSchema
2493
+ );
2494
+ if (this.memoryEnabled) {
2495
+ this.addToHistory(new import_messages.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
2496
+ }
2497
+ logger.info("\u2705 Structured output successful");
2498
+ success = true;
2499
+ return structuredResult;
2500
+ } catch (e) {
2501
+ logger.error(`\u274C Structured output failed: ${e}`);
2502
+ throw new Error(`Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`);
2503
+ }
2504
+ }
2505
+ logger.info(`\u{1F389} Agent execution complete in ${((Date.now() - startTime) / 1e3).toFixed(2)} seconds`);
2506
+ success = true;
2507
+ return finalOutput || "No output generated";
2458
2508
  } catch (e) {
2459
2509
  logger.error(`\u274C Error running query: ${e}`);
2460
2510
  if (initializedHere && manageConnector) {
2461
- logger.info("\u{1F9F9} Cleaning up resources after initialization error in run");
2511
+ logger.info("\u{1F9F9} Cleaning up resources after error");
2462
2512
  await this.close();
2463
2513
  }
2464
2514
  throw e;
@@ -2471,16 +2521,17 @@ var MCPAgent = class {
2471
2521
  serverCount = this.connectors.length;
2472
2522
  }
2473
2523
  const conversationHistoryLength = this.memoryEnabled ? this.conversationHistory.length : 0;
2524
+ const toolsAvailable = this._tools || [];
2474
2525
  await this.telemetry.trackAgentExecution({
2475
2526
  executionMethod: "stream",
2476
2527
  query,
2477
- success: structuredOutputSuccess,
2528
+ success,
2478
2529
  modelProvider: this.modelProvider,
2479
2530
  modelName: this.modelName,
2480
2531
  serverCount,
2481
2532
  serverIdentifiers: this.connectors.map((connector) => connector.publicIdentifier),
2482
- totalToolsAvailable: this._tools.length,
2483
- toolsAvailableNames: this._tools.map((t) => t.name),
2533
+ totalToolsAvailable: toolsAvailable.length,
2534
+ toolsAvailableNames: toolsAvailable.map((t) => t.name),
2484
2535
  maxStepsConfigured: this.maxSteps,
2485
2536
  memoryEnabled: this.memoryEnabled,
2486
2537
  useServerManager: this.useServerManager,
@@ -2488,19 +2539,30 @@ var MCPAgent = class {
2488
2539
  manageConnector,
2489
2540
  externalHistoryUsed: externalHistory !== void 0,
2490
2541
  stepsTaken,
2491
- toolsUsedCount: toolsUsedNames.length,
2492
- toolsUsedNames,
2493
- response: result,
2542
+ toolsUsedCount: this.toolsUsedNames.length,
2543
+ toolsUsedNames: this.toolsUsedNames,
2544
+ response: finalOutput || "",
2494
2545
  executionTimeMs,
2495
- errorType: structuredOutputSuccess ? null : "execution_error",
2546
+ errorType: success ? null : "execution_error",
2496
2547
  conversationHistoryLength
2497
2548
  });
2498
2549
  if (manageConnector && !this.client && initializedHere) {
2499
- logger.info("\u{1F9F9} Closing agent after query completion");
2550
+ logger.info("\u{1F9F9} Closing agent after stream completion");
2500
2551
  await this.close();
2501
2552
  }
2502
2553
  }
2503
2554
  }
2555
+ /**
2556
+ * Flush observability traces to the configured observability platform.
2557
+ * Important for serverless environments where traces need to be sent before function termination.
2558
+ */
2559
+ async flush() {
2560
+ if (this.isRemote && this.remoteAgent) {
2561
+ return;
2562
+ }
2563
+ logger.debug("Flushing observability traces...");
2564
+ await this.observabilityManager.flush();
2565
+ }
2504
2566
  async close() {
2505
2567
  if (this.isRemote && this.remoteAgent) {
2506
2568
  await this.remoteAgent.close();
@@ -2551,34 +2613,40 @@ var MCPAgent = class {
2551
2613
  await this.initialize();
2552
2614
  initializedHere = true;
2553
2615
  }
2554
- const agentExecutor = this.agentExecutor;
2616
+ const agentExecutor = this._agentExecutor;
2555
2617
  if (!agentExecutor) {
2556
2618
  throw new Error("MCP agent failed to initialize");
2557
2619
  }
2558
- const steps = maxSteps ?? this.maxSteps;
2559
- agentExecutor.maxIterations = steps;
2620
+ this.maxSteps = maxSteps ?? this.maxSteps;
2560
2621
  const display_query = query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : query.replace(/\n/g, " ");
2561
2622
  logger.info(`\u{1F4AC} Received query for streamEvents: '${display_query}'`);
2562
2623
  if (this.memoryEnabled) {
2563
2624
  logger.info(`\u{1F504} Adding user message to history: ${query}`);
2564
- this.addToHistory(new import_messages2.HumanMessage(query));
2625
+ this.addToHistory(new import_messages.HumanMessage(query));
2565
2626
  }
2566
2627
  const historyToUse = externalHistory ?? this.conversationHistory;
2567
2628
  const langchainHistory = [];
2568
2629
  for (const msg of historyToUse) {
2569
- if (msg instanceof import_messages2.HumanMessage || msg instanceof import_messages2.AIMessage || msg instanceof import_messages2.ToolMessage) {
2630
+ if (msg instanceof import_messages.HumanMessage || msg instanceof import_messages.AIMessage || msg instanceof import_messages.ToolMessage) {
2570
2631
  langchainHistory.push(msg);
2571
2632
  } else {
2572
2633
  logger.info(`\u26A0\uFE0F Skipped message of type: ${msg.constructor.name}`);
2573
2634
  }
2574
2635
  }
2575
- const inputs = { input: query, chat_history: langchainHistory };
2636
+ const inputs = [...langchainHistory, new import_messages.HumanMessage(query)];
2576
2637
  logger.info("callbacks", this.callbacks);
2577
2638
  const eventStream = agentExecutor.streamEvents(
2578
- inputs,
2639
+ { messages: inputs },
2579
2640
  {
2641
+ streamMode: "messages",
2580
2642
  version: "v2",
2581
- callbacks: this.callbacks.length > 0 ? this.callbacks : void 0
2643
+ callbacks: this.callbacks,
2644
+ metadata: this.getMetadata(),
2645
+ tags: this.getTags(),
2646
+ // Set trace name for LangChain/Langfuse
2647
+ runName: this.metadata.trace_name || "mcp-use-agent",
2648
+ // Pass sessionId for Langfuse if present in metadata
2649
+ ...this.metadata.session_id && { sessionId: this.metadata.session_id }
2582
2650
  }
2583
2651
  );
2584
2652
  for await (const event of eventStream) {
@@ -2589,8 +2657,20 @@ var MCPAgent = class {
2589
2657
  if (event.event === "on_chat_model_stream" && event.data?.chunk?.content) {
2590
2658
  totalResponseLength += event.data.chunk.content.length;
2591
2659
  }
2660
+ if (event.event === "on_chat_model_stream" && event.data?.chunk) {
2661
+ logger.info("on_chat_model_stream", event.data.chunk);
2662
+ const chunk = event.data.chunk;
2663
+ if (chunk.content) {
2664
+ if (!finalResponse) {
2665
+ finalResponse = "";
2666
+ }
2667
+ const normalizedContent = this._normalizeOutput(chunk.content);
2668
+ finalResponse += normalizedContent;
2669
+ logger.debug(`\u{1F4DD} Accumulated response length: ${finalResponse.length}`);
2670
+ }
2671
+ }
2592
2672
  yield event;
2593
- if (event.event === "on_chain_end" && event.data?.output) {
2673
+ if (event.event === "on_chain_end" && event.data?.output && !finalResponse) {
2594
2674
  const output = event.data.output;
2595
2675
  if (Array.isArray(output) && output.length > 0 && output[0]?.text) {
2596
2676
  finalResponse = output[0].text;
@@ -2607,7 +2687,7 @@ var MCPAgent = class {
2607
2687
  let conversionCompleted = false;
2608
2688
  let conversionResult = null;
2609
2689
  let conversionError = null;
2610
- const _conversionPromise = this._attemptStructuredOutput(
2690
+ this._attemptStructuredOutput(
2611
2691
  finalResponse,
2612
2692
  this.llm,
2613
2693
  outputSchema
@@ -2643,7 +2723,7 @@ var MCPAgent = class {
2643
2723
  data: { output: conversionResult }
2644
2724
  };
2645
2725
  if (this.memoryEnabled) {
2646
- this.addToHistory(new import_messages2.AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
2726
+ this.addToHistory(new import_messages.AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
2647
2727
  }
2648
2728
  logger.info("\u2705 Structured output successful");
2649
2729
  }
@@ -2655,7 +2735,7 @@ var MCPAgent = class {
2655
2735
  };
2656
2736
  }
2657
2737
  } else if (this.memoryEnabled && finalResponse) {
2658
- this.addToHistory(new import_messages2.AIMessage(finalResponse));
2738
+ this.addToHistory(new import_messages.AIMessage(finalResponse));
2659
2739
  }
2660
2740
  logger.info(`\u{1F389} StreamEvents complete - ${eventCount} events emitted`);
2661
2741
  success = true;
@@ -2704,6 +2784,10 @@ var MCPAgent = class {
2704
2784
  }
2705
2785
  /**
2706
2786
  * Attempt to create structured output from raw result with validation and retry logic.
2787
+ *
2788
+ * @param rawResult - The raw text result from the agent
2789
+ * @param llm - LLM to use for structured output
2790
+ * @param outputSchema - The Zod schema to validate against
2707
2791
  */
2708
2792
  async _attemptStructuredOutput(rawResult, llm, outputSchema) {
2709
2793
  logger.info(`\u{1F504} Attempting structured output with schema: ${outputSchema}`);
@@ -2718,7 +2802,9 @@ var MCPAgent = class {
2718
2802
  } else {
2719
2803
  throw new Error("LLM is required for structured output");
2720
2804
  }
2721
- schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
2805
+ const jsonSchema = (0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema);
2806
+ const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;
2807
+ schemaDescription = JSON.stringify(cleanSchema, null, 2);
2722
2808
  logger.info(`\u{1F504} Schema description: ${schemaDescription}`);
2723
2809
  let textContent = "";
2724
2810
  if (typeof rawResult === "string") {
@@ -2726,6 +2812,7 @@ var MCPAgent = class {
2726
2812
  } else if (rawResult && typeof rawResult === "object") {
2727
2813
  textContent = JSON.stringify(rawResult);
2728
2814
  }
2815
+ logger.info("rawResult", rawResult);
2729
2816
  if (!textContent) {
2730
2817
  textContent = JSON.stringify(rawResult);
2731
2818
  }
@@ -2736,28 +2823,34 @@ var MCPAgent = class {
2736
2823
  let formatPrompt = `
2737
2824
  Please format the following information according to the EXACT schema specified below.
2738
2825
  You must use the exact field names and types as shown in the schema.
2739
-
2826
+
2740
2827
  Required schema format:
2741
2828
  ${schemaDescription}
2742
-
2829
+
2743
2830
  Content to extract from:
2744
2831
  ${textContent}
2745
-
2746
- IMPORTANT:
2832
+
2833
+ IMPORTANT:
2747
2834
  - Use ONLY the field names specified in the schema
2748
2835
  - Match the data types exactly (string, number, boolean, array, etc.)
2749
2836
  - Include ALL required fields
2750
2837
  - Return valid JSON that matches the schema structure exactly
2838
+ - For missing data: use null for nullable fields, omit optional fields entirely
2839
+ - Do NOT use empty strings ("") or zero (0) as placeholders for missing data
2751
2840
  `;
2752
2841
  if (attempt > 1) {
2753
2842
  formatPrompt += `
2754
-
2843
+
2755
2844
  PREVIOUS ATTEMPT FAILED with error: ${lastError}
2756
2845
  Please fix the issues mentioned above and ensure the output matches the schema exactly.
2757
2846
  `;
2758
2847
  }
2759
2848
  try {
2760
2849
  logger.info(`\u{1F504} Structured output attempt ${attempt} - using streaming approach`);
2850
+ const contentPreview = textContent.length > 300 ? `${textContent.slice(0, 300)}...` : textContent;
2851
+ logger.info(`\u{1F504} Content being formatted (${textContent.length} chars): ${contentPreview}`);
2852
+ logger.info(`\u{1F504} Full format prompt (${formatPrompt.length} chars):
2853
+ ${formatPrompt}`);
2761
2854
  const stream = await structuredLlm.stream(formatPrompt);
2762
2855
  let structuredResult = null;
2763
2856
  let chunkCount = 0;
@@ -2833,14 +2926,16 @@ var MCPAgent = class {
2833
2926
  */
2834
2927
  _enhanceQueryWithSchema(query, outputSchema) {
2835
2928
  try {
2836
- const schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
2929
+ const jsonSchema = (0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema);
2930
+ const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;
2931
+ const schemaDescription = JSON.stringify(cleanSchema, null, 2);
2837
2932
  const enhancedQuery = `
2838
2933
  ${query}
2839
-
2934
+
2840
2935
  IMPORTANT: Your response must include sufficient information to populate the following structured output:
2841
-
2936
+
2842
2937
  ${schemaDescription}
2843
-
2938
+
2844
2939
  Make sure you gather ALL the required information during your task execution.
2845
2940
  If any required information is missing, continue working to find it.
2846
2941
  `;
@@ -5567,7 +5662,7 @@ function useWidgetState(defaultState) {
5567
5662
  __name(useWidgetState, "useWidgetState");
5568
5663
 
5569
5664
  // index.ts
5570
- var import_messages3 = require("@langchain/core/messages");
5665
+ var import_messages2 = require("@langchain/core/messages");
5571
5666
  // Annotate the CommonJS export names for ESM import in node:
5572
5667
  0 && (module.exports = {
5573
5668
  AIMessage,