mcp-use 1.0.5 → 1.0.7

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.
package/dist/index.cjs CHANGED
@@ -2276,7 +2276,8 @@ var MCPAgent = class {
2276
2276
  const startTime = Date.now();
2277
2277
  const toolsUsedNames = [];
2278
2278
  let stepsTaken = 0;
2279
- let success = false;
2279
+ const structuredOutputSuccess = false;
2280
+ const structuredOutputSuccessRef = { value: structuredOutputSuccess };
2280
2281
  let structuredLlm = null;
2281
2282
  let schemaDescription = "";
2282
2283
  if (outputSchema) {
@@ -2366,28 +2367,26 @@ var MCPAgent = class {
2366
2367
  result = nextStepOutput.returnValues?.output ?? "No output generated";
2367
2368
  runManager?.handleChainEnd({ output: result });
2368
2369
  if (outputSchema && structuredLlm) {
2369
- try {
2370
- logger.info("\u{1F527} Attempting structured output...");
2371
- const structuredResult = await this._attemptStructuredOutput(
2372
- result,
2373
- structuredLlm,
2374
- outputSchema,
2375
- schemaDescription
2376
- );
2377
- logger.debug(`\u{1F504} Structured result: ${JSON.stringify(structuredResult)}`);
2370
+ logger.info("\u{1F527} Attempting structured output...");
2371
+ const currentResult = result;
2372
+ this._attemptStructuredOutput(
2373
+ currentResult,
2374
+ this.llm,
2375
+ outputSchema
2376
+ ).then((structuredResult) => {
2378
2377
  if (this.memoryEnabled) {
2379
2378
  this.addToHistory(new import_messages2.AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
2380
2379
  }
2381
2380
  logger.info("\u2705 Structured output successful");
2382
- success = true;
2381
+ structuredOutputSuccessRef.value = true;
2383
2382
  return structuredResult;
2384
- } catch (e) {
2383
+ }).catch((e) => {
2385
2384
  logger.warn(`\u26A0\uFE0F Structured output failed: ${e}`);
2386
2385
  const failedStructuredOutputPrompt = `
2387
2386
  The current result cannot be formatted into the required structure.
2388
2387
  Error: ${String(e)}
2389
2388
 
2390
- Current information: ${result}
2389
+ Current information: ${currentResult}
2391
2390
 
2392
2391
  If information is missing, please continue working to gather the missing information needed for:
2393
2392
  ${schemaDescription}
@@ -2399,36 +2398,35 @@ var MCPAgent = class {
2399
2398
  this.addToHistory(new import_messages2.HumanMessage(failedStructuredOutputPrompt));
2400
2399
  }
2401
2400
  logger.info("\u{1F504} Continuing execution to gather missing information...");
2402
- continue;
2403
- }
2404
- } else {
2405
- break;
2401
+ });
2406
2402
  }
2407
2403
  }
2408
- const stepArray = nextStepOutput;
2409
- intermediateSteps.push(...stepArray);
2410
- for (const step of stepArray) {
2411
- yield step;
2412
- const { action, observation } = step;
2413
- const toolName = action.tool;
2414
- toolsUsedNames.push(toolName);
2415
- let toolInputStr = typeof action.toolInput === "string" ? action.toolInput : JSON.stringify(action.toolInput, null, 2);
2416
- if (toolInputStr.length > 100)
2417
- toolInputStr = `${toolInputStr.slice(0, 97)}...`;
2418
- logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
2419
- let outputStr = String(observation);
2420
- if (outputStr.length > 100)
2421
- outputStr = `${outputStr.slice(0, 97)}...`;
2422
- outputStr = outputStr.replace(/\n/g, " ");
2423
- logger.info(`\u{1F4C4} Tool result: ${outputStr}`);
2424
- }
2425
- if (stepArray.length) {
2426
- const lastStep = stepArray[stepArray.length - 1];
2427
- const toolReturn = await this._agentExecutor._getToolReturn(lastStep);
2428
- if (toolReturn) {
2429
- logger.info(`\u{1F3C6} Tool returned directly at step ${stepNum + 1}`);
2430
- result = toolReturn.returnValues?.output ?? "No output generated";
2431
- break;
2404
+ if (Array.isArray(nextStepOutput)) {
2405
+ const stepArray = nextStepOutput;
2406
+ intermediateSteps.push(...stepArray);
2407
+ for (const step of stepArray) {
2408
+ yield step;
2409
+ const { action, observation } = step;
2410
+ const toolName = action.tool;
2411
+ toolsUsedNames.push(toolName);
2412
+ let toolInputStr = typeof action.toolInput === "string" ? action.toolInput : JSON.stringify(action.toolInput, null, 2);
2413
+ if (toolInputStr.length > 100)
2414
+ toolInputStr = `${toolInputStr.slice(0, 97)}...`;
2415
+ logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
2416
+ let outputStr = String(observation);
2417
+ if (outputStr.length > 100)
2418
+ outputStr = `${outputStr.slice(0, 97)}...`;
2419
+ outputStr = outputStr.replace(/\n/g, " ");
2420
+ logger.info(`\u{1F4C4} Tool result: ${outputStr}`);
2421
+ }
2422
+ if (stepArray.length) {
2423
+ const lastStep = stepArray[stepArray.length - 1];
2424
+ const toolReturn = await this._agentExecutor._getToolReturn(lastStep);
2425
+ if (toolReturn) {
2426
+ logger.info(`\u{1F3C6} Tool returned directly at step ${stepNum + 1}`);
2427
+ result = toolReturn.returnValues?.output ?? "No output generated";
2428
+ break;
2429
+ }
2432
2430
  }
2433
2431
  }
2434
2432
  } catch (e) {
@@ -2451,7 +2449,7 @@ var MCPAgent = class {
2451
2449
  runManager?.handleChainEnd({ output: result });
2452
2450
  }
2453
2451
  logger.info("\u{1F389} Agent execution complete");
2454
- success = true;
2452
+ structuredOutputSuccessRef.value = true;
2455
2453
  return result;
2456
2454
  } catch (e) {
2457
2455
  logger.error(`\u274C Error running query: ${e}`);
@@ -2472,7 +2470,7 @@ var MCPAgent = class {
2472
2470
  await this.telemetry.trackAgentExecution({
2473
2471
  executionMethod: "stream",
2474
2472
  query,
2475
- success,
2473
+ success: structuredOutputSuccess,
2476
2474
  modelProvider: this.modelProvider,
2477
2475
  modelName: this.modelName,
2478
2476
  serverCount,
@@ -2490,7 +2488,7 @@ var MCPAgent = class {
2490
2488
  toolsUsedNames,
2491
2489
  response: result,
2492
2490
  executionTimeMs,
2493
- errorType: success ? null : "execution_error",
2491
+ errorType: structuredOutputSuccess ? null : "execution_error",
2494
2492
  conversationHistoryLength
2495
2493
  });
2496
2494
  if (manageConnector && !this.client && initializedHere) {
@@ -2531,13 +2529,16 @@ var MCPAgent = class {
2531
2529
  * Yields LangChain StreamEvent objects from the underlying streamEvents() method.
2532
2530
  * This provides token-level streaming and fine-grained event updates.
2533
2531
  */
2534
- async *streamEvents(query, maxSteps, manageConnector = true, externalHistory) {
2532
+ async *streamEvents(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
2535
2533
  let initializedHere = false;
2536
2534
  const startTime = Date.now();
2537
2535
  let success = false;
2538
2536
  let eventCount = 0;
2539
2537
  let totalResponseLength = 0;
2540
2538
  let finalResponse = "";
2539
+ if (outputSchema) {
2540
+ query = this._enhanceQueryWithSchema(query, outputSchema);
2541
+ }
2541
2542
  try {
2542
2543
  if (manageConnector && !this._initialized) {
2543
2544
  await this.initialize();
@@ -2589,10 +2590,67 @@ var MCPAgent = class {
2589
2590
  const output = event.data.output;
2590
2591
  if (Array.isArray(output) && output.length > 0 && output[0]?.text) {
2591
2592
  finalResponse = output[0].text;
2593
+ } else if (typeof output === "string") {
2594
+ finalResponse = output;
2595
+ } else if (output && typeof output === "object" && "output" in output) {
2596
+ finalResponse = output.output;
2592
2597
  }
2593
2598
  }
2594
2599
  }
2595
- if (this.memoryEnabled && finalResponse) {
2600
+ if (outputSchema && finalResponse) {
2601
+ logger.info("\u{1F527} Attempting structured output conversion...");
2602
+ try {
2603
+ let conversionCompleted = false;
2604
+ let conversionResult = null;
2605
+ let conversionError = null;
2606
+ const _conversionPromise = this._attemptStructuredOutput(
2607
+ finalResponse,
2608
+ this.llm,
2609
+ outputSchema
2610
+ ).then((result) => {
2611
+ conversionCompleted = true;
2612
+ conversionResult = result;
2613
+ return result;
2614
+ }).catch((error) => {
2615
+ conversionCompleted = true;
2616
+ conversionError = error;
2617
+ throw error;
2618
+ });
2619
+ let progressCount = 0;
2620
+ while (!conversionCompleted) {
2621
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
2622
+ if (!conversionCompleted) {
2623
+ progressCount++;
2624
+ yield {
2625
+ event: "on_structured_output_progress",
2626
+ data: {
2627
+ message: `Converting to structured output... (${progressCount * 2}s)`,
2628
+ elapsed: progressCount * 2
2629
+ }
2630
+ };
2631
+ }
2632
+ }
2633
+ if (conversionError) {
2634
+ throw conversionError;
2635
+ }
2636
+ if (conversionResult) {
2637
+ yield {
2638
+ event: "on_structured_output",
2639
+ data: { output: conversionResult }
2640
+ };
2641
+ if (this.memoryEnabled) {
2642
+ this.addToHistory(new import_messages2.AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
2643
+ }
2644
+ logger.info("\u2705 Structured output successful");
2645
+ }
2646
+ } catch (e) {
2647
+ logger.warn(`\u26A0\uFE0F Structured output failed: ${e}`);
2648
+ yield {
2649
+ event: "on_structured_output_error",
2650
+ data: { error: e instanceof Error ? e.message : String(e) }
2651
+ };
2652
+ }
2653
+ } else if (this.memoryEnabled && finalResponse) {
2596
2654
  this.addToHistory(new import_messages2.AIMessage(finalResponse));
2597
2655
  }
2598
2656
  logger.info(`\u{1F389} StreamEvents complete - ${eventCount} events emitted`);
@@ -2643,10 +2701,21 @@ var MCPAgent = class {
2643
2701
  /**
2644
2702
  * Attempt to create structured output from raw result with validation and retry logic.
2645
2703
  */
2646
- async _attemptStructuredOutput(rawResult, structuredLlm, outputSchema, schemaDescription) {
2704
+ async _attemptStructuredOutput(rawResult, llm, outputSchema) {
2647
2705
  logger.info(`\u{1F504} Attempting structured output with schema: ${outputSchema}`);
2648
- logger.info(`\u{1F504} Schema description: ${schemaDescription}`);
2649
2706
  logger.info(`\u{1F504} Raw result: ${JSON.stringify(rawResult, null, 2)}`);
2707
+ let structuredLlm = null;
2708
+ let schemaDescription = "";
2709
+ logger.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`);
2710
+ if (llm && "withStructuredOutput" in llm && typeof llm.withStructuredOutput === "function") {
2711
+ structuredLlm = llm.withStructuredOutput(outputSchema);
2712
+ } else if (llm) {
2713
+ structuredLlm = llm;
2714
+ } else {
2715
+ throw new Error("LLM is required for structured output");
2716
+ }
2717
+ schemaDescription = JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2);
2718
+ logger.info(`\u{1F504} Schema description: ${schemaDescription}`);
2650
2719
  let textContent = "";
2651
2720
  if (typeof rawResult === "string") {
2652
2721
  textContent = rawResult;
@@ -2690,6 +2759,7 @@ var MCPAgent = class {
2690
2759
  let chunkCount = 0;
2691
2760
  for await (const chunk of stream) {
2692
2761
  chunkCount++;
2762
+ logger.info(`Chunk ${chunkCount}: ${JSON.stringify(chunk, null, 2)}`);
2693
2763
  if (typeof chunk === "string") {
2694
2764
  try {
2695
2765
  structuredResult = JSON.parse(chunk);
@@ -2705,7 +2775,6 @@ var MCPAgent = class {
2705
2775
  logger.warn(`\u{1F504} Failed to parse chunk as JSON: ${chunk}`);
2706
2776
  }
2707
2777
  }
2708
- await new Promise((resolve) => setTimeout(resolve, 0));
2709
2778
  if (chunkCount % 10 === 0) {
2710
2779
  logger.info(`\u{1F504} Structured output streaming: ${chunkCount} chunks`);
2711
2780
  }
package/dist/index.js CHANGED
@@ -1773,7 +1773,8 @@ var MCPAgent = class {
1773
1773
  const startTime = Date.now();
1774
1774
  const toolsUsedNames = [];
1775
1775
  let stepsTaken = 0;
1776
- let success = false;
1776
+ const structuredOutputSuccess = false;
1777
+ const structuredOutputSuccessRef = { value: structuredOutputSuccess };
1777
1778
  let structuredLlm = null;
1778
1779
  let schemaDescription = "";
1779
1780
  if (outputSchema) {
@@ -1863,28 +1864,26 @@ var MCPAgent = class {
1863
1864
  result = nextStepOutput.returnValues?.output ?? "No output generated";
1864
1865
  runManager?.handleChainEnd({ output: result });
1865
1866
  if (outputSchema && structuredLlm) {
1866
- try {
1867
- logger.info("\u{1F527} Attempting structured output...");
1868
- const structuredResult = await this._attemptStructuredOutput(
1869
- result,
1870
- structuredLlm,
1871
- outputSchema,
1872
- schemaDescription
1873
- );
1874
- logger.debug(`\u{1F504} Structured result: ${JSON.stringify(structuredResult)}`);
1867
+ logger.info("\u{1F527} Attempting structured output...");
1868
+ const currentResult = result;
1869
+ this._attemptStructuredOutput(
1870
+ currentResult,
1871
+ this.llm,
1872
+ outputSchema
1873
+ ).then((structuredResult) => {
1875
1874
  if (this.memoryEnabled) {
1876
1875
  this.addToHistory(new AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
1877
1876
  }
1878
1877
  logger.info("\u2705 Structured output successful");
1879
- success = true;
1878
+ structuredOutputSuccessRef.value = true;
1880
1879
  return structuredResult;
1881
- } catch (e) {
1880
+ }).catch((e) => {
1882
1881
  logger.warn(`\u26A0\uFE0F Structured output failed: ${e}`);
1883
1882
  const failedStructuredOutputPrompt = `
1884
1883
  The current result cannot be formatted into the required structure.
1885
1884
  Error: ${String(e)}
1886
1885
 
1887
- Current information: ${result}
1886
+ Current information: ${currentResult}
1888
1887
 
1889
1888
  If information is missing, please continue working to gather the missing information needed for:
1890
1889
  ${schemaDescription}
@@ -1896,36 +1895,35 @@ var MCPAgent = class {
1896
1895
  this.addToHistory(new HumanMessage(failedStructuredOutputPrompt));
1897
1896
  }
1898
1897
  logger.info("\u{1F504} Continuing execution to gather missing information...");
1899
- continue;
1900
- }
1901
- } else {
1902
- break;
1898
+ });
1903
1899
  }
1904
1900
  }
1905
- const stepArray = nextStepOutput;
1906
- intermediateSteps.push(...stepArray);
1907
- for (const step of stepArray) {
1908
- yield step;
1909
- const { action, observation } = step;
1910
- const toolName = action.tool;
1911
- toolsUsedNames.push(toolName);
1912
- let toolInputStr = typeof action.toolInput === "string" ? action.toolInput : JSON.stringify(action.toolInput, null, 2);
1913
- if (toolInputStr.length > 100)
1914
- toolInputStr = `${toolInputStr.slice(0, 97)}...`;
1915
- logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
1916
- let outputStr = String(observation);
1917
- if (outputStr.length > 100)
1918
- outputStr = `${outputStr.slice(0, 97)}...`;
1919
- outputStr = outputStr.replace(/\n/g, " ");
1920
- logger.info(`\u{1F4C4} Tool result: ${outputStr}`);
1921
- }
1922
- if (stepArray.length) {
1923
- const lastStep = stepArray[stepArray.length - 1];
1924
- const toolReturn = await this._agentExecutor._getToolReturn(lastStep);
1925
- if (toolReturn) {
1926
- logger.info(`\u{1F3C6} Tool returned directly at step ${stepNum + 1}`);
1927
- result = toolReturn.returnValues?.output ?? "No output generated";
1928
- break;
1901
+ if (Array.isArray(nextStepOutput)) {
1902
+ const stepArray = nextStepOutput;
1903
+ intermediateSteps.push(...stepArray);
1904
+ for (const step of stepArray) {
1905
+ yield step;
1906
+ const { action, observation } = step;
1907
+ const toolName = action.tool;
1908
+ toolsUsedNames.push(toolName);
1909
+ let toolInputStr = typeof action.toolInput === "string" ? action.toolInput : JSON.stringify(action.toolInput, null, 2);
1910
+ if (toolInputStr.length > 100)
1911
+ toolInputStr = `${toolInputStr.slice(0, 97)}...`;
1912
+ logger.info(`\u{1F527} Tool call: ${toolName} with input: ${toolInputStr}`);
1913
+ let outputStr = String(observation);
1914
+ if (outputStr.length > 100)
1915
+ outputStr = `${outputStr.slice(0, 97)}...`;
1916
+ outputStr = outputStr.replace(/\n/g, " ");
1917
+ logger.info(`\u{1F4C4} Tool result: ${outputStr}`);
1918
+ }
1919
+ if (stepArray.length) {
1920
+ const lastStep = stepArray[stepArray.length - 1];
1921
+ const toolReturn = await this._agentExecutor._getToolReturn(lastStep);
1922
+ if (toolReturn) {
1923
+ logger.info(`\u{1F3C6} Tool returned directly at step ${stepNum + 1}`);
1924
+ result = toolReturn.returnValues?.output ?? "No output generated";
1925
+ break;
1926
+ }
1929
1927
  }
1930
1928
  }
1931
1929
  } catch (e) {
@@ -1948,7 +1946,7 @@ var MCPAgent = class {
1948
1946
  runManager?.handleChainEnd({ output: result });
1949
1947
  }
1950
1948
  logger.info("\u{1F389} Agent execution complete");
1951
- success = true;
1949
+ structuredOutputSuccessRef.value = true;
1952
1950
  return result;
1953
1951
  } catch (e) {
1954
1952
  logger.error(`\u274C Error running query: ${e}`);
@@ -1969,7 +1967,7 @@ var MCPAgent = class {
1969
1967
  await this.telemetry.trackAgentExecution({
1970
1968
  executionMethod: "stream",
1971
1969
  query,
1972
- success,
1970
+ success: structuredOutputSuccess,
1973
1971
  modelProvider: this.modelProvider,
1974
1972
  modelName: this.modelName,
1975
1973
  serverCount,
@@ -1987,7 +1985,7 @@ var MCPAgent = class {
1987
1985
  toolsUsedNames,
1988
1986
  response: result,
1989
1987
  executionTimeMs,
1990
- errorType: success ? null : "execution_error",
1988
+ errorType: structuredOutputSuccess ? null : "execution_error",
1991
1989
  conversationHistoryLength
1992
1990
  });
1993
1991
  if (manageConnector && !this.client && initializedHere) {
@@ -2028,13 +2026,16 @@ var MCPAgent = class {
2028
2026
  * Yields LangChain StreamEvent objects from the underlying streamEvents() method.
2029
2027
  * This provides token-level streaming and fine-grained event updates.
2030
2028
  */
2031
- async *streamEvents(query, maxSteps, manageConnector = true, externalHistory) {
2029
+ async *streamEvents(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
2032
2030
  let initializedHere = false;
2033
2031
  const startTime = Date.now();
2034
2032
  let success = false;
2035
2033
  let eventCount = 0;
2036
2034
  let totalResponseLength = 0;
2037
2035
  let finalResponse = "";
2036
+ if (outputSchema) {
2037
+ query = this._enhanceQueryWithSchema(query, outputSchema);
2038
+ }
2038
2039
  try {
2039
2040
  if (manageConnector && !this._initialized) {
2040
2041
  await this.initialize();
@@ -2086,10 +2087,67 @@ var MCPAgent = class {
2086
2087
  const output = event.data.output;
2087
2088
  if (Array.isArray(output) && output.length > 0 && output[0]?.text) {
2088
2089
  finalResponse = output[0].text;
2090
+ } else if (typeof output === "string") {
2091
+ finalResponse = output;
2092
+ } else if (output && typeof output === "object" && "output" in output) {
2093
+ finalResponse = output.output;
2089
2094
  }
2090
2095
  }
2091
2096
  }
2092
- if (this.memoryEnabled && finalResponse) {
2097
+ if (outputSchema && finalResponse) {
2098
+ logger.info("\u{1F527} Attempting structured output conversion...");
2099
+ try {
2100
+ let conversionCompleted = false;
2101
+ let conversionResult = null;
2102
+ let conversionError = null;
2103
+ const _conversionPromise = this._attemptStructuredOutput(
2104
+ finalResponse,
2105
+ this.llm,
2106
+ outputSchema
2107
+ ).then((result) => {
2108
+ conversionCompleted = true;
2109
+ conversionResult = result;
2110
+ return result;
2111
+ }).catch((error) => {
2112
+ conversionCompleted = true;
2113
+ conversionError = error;
2114
+ throw error;
2115
+ });
2116
+ let progressCount = 0;
2117
+ while (!conversionCompleted) {
2118
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
2119
+ if (!conversionCompleted) {
2120
+ progressCount++;
2121
+ yield {
2122
+ event: "on_structured_output_progress",
2123
+ data: {
2124
+ message: `Converting to structured output... (${progressCount * 2}s)`,
2125
+ elapsed: progressCount * 2
2126
+ }
2127
+ };
2128
+ }
2129
+ }
2130
+ if (conversionError) {
2131
+ throw conversionError;
2132
+ }
2133
+ if (conversionResult) {
2134
+ yield {
2135
+ event: "on_structured_output",
2136
+ data: { output: conversionResult }
2137
+ };
2138
+ if (this.memoryEnabled) {
2139
+ this.addToHistory(new AIMessage(`Structured result: ${JSON.stringify(conversionResult)}`));
2140
+ }
2141
+ logger.info("\u2705 Structured output successful");
2142
+ }
2143
+ } catch (e) {
2144
+ logger.warn(`\u26A0\uFE0F Structured output failed: ${e}`);
2145
+ yield {
2146
+ event: "on_structured_output_error",
2147
+ data: { error: e instanceof Error ? e.message : String(e) }
2148
+ };
2149
+ }
2150
+ } else if (this.memoryEnabled && finalResponse) {
2093
2151
  this.addToHistory(new AIMessage(finalResponse));
2094
2152
  }
2095
2153
  logger.info(`\u{1F389} StreamEvents complete - ${eventCount} events emitted`);
@@ -2140,10 +2198,21 @@ var MCPAgent = class {
2140
2198
  /**
2141
2199
  * Attempt to create structured output from raw result with validation and retry logic.
2142
2200
  */
2143
- async _attemptStructuredOutput(rawResult, structuredLlm, outputSchema, schemaDescription) {
2201
+ async _attemptStructuredOutput(rawResult, llm, outputSchema) {
2144
2202
  logger.info(`\u{1F504} Attempting structured output with schema: ${outputSchema}`);
2145
- logger.info(`\u{1F504} Schema description: ${schemaDescription}`);
2146
2203
  logger.info(`\u{1F504} Raw result: ${JSON.stringify(rawResult, null, 2)}`);
2204
+ let structuredLlm = null;
2205
+ let schemaDescription = "";
2206
+ logger.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify(zodToJsonSchema2(outputSchema), null, 2)}`);
2207
+ if (llm && "withStructuredOutput" in llm && typeof llm.withStructuredOutput === "function") {
2208
+ structuredLlm = llm.withStructuredOutput(outputSchema);
2209
+ } else if (llm) {
2210
+ structuredLlm = llm;
2211
+ } else {
2212
+ throw new Error("LLM is required for structured output");
2213
+ }
2214
+ schemaDescription = JSON.stringify(zodToJsonSchema2(outputSchema), null, 2);
2215
+ logger.info(`\u{1F504} Schema description: ${schemaDescription}`);
2147
2216
  let textContent = "";
2148
2217
  if (typeof rawResult === "string") {
2149
2218
  textContent = rawResult;
@@ -2187,6 +2256,7 @@ var MCPAgent = class {
2187
2256
  let chunkCount = 0;
2188
2257
  for await (const chunk of stream) {
2189
2258
  chunkCount++;
2259
+ logger.info(`Chunk ${chunkCount}: ${JSON.stringify(chunk, null, 2)}`);
2190
2260
  if (typeof chunk === "string") {
2191
2261
  try {
2192
2262
  structuredResult = JSON.parse(chunk);
@@ -2202,7 +2272,6 @@ var MCPAgent = class {
2202
2272
  logger.warn(`\u{1F504} Failed to parse chunk as JSON: ${chunk}`);
2203
2273
  }
2204
2274
  }
2205
- await new Promise((resolve) => setTimeout(resolve, 0));
2206
2275
  if (chunkCount % 10 === 0) {
2207
2276
  logger.info(`\u{1F504} Structured output streaming: ${chunkCount} chunks`);
2208
2277
  }
@@ -129,7 +129,7 @@ export declare class MCPAgent {
129
129
  * Yields LangChain StreamEvent objects from the underlying streamEvents() method.
130
130
  * This provides token-level streaming and fine-grained event updates.
131
131
  */
132
- streamEvents(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[]): AsyncGenerator<StreamEvent, void, void>;
132
+ streamEvents<T = string>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): AsyncGenerator<StreamEvent, void, void>;
133
133
  /**
134
134
  * Attempt to create structured output from raw result with validation and retry logic.
135
135
  */
@@ -1 +1 @@
1
- {"version":3,"file":"mcp_agent.d.ts","sourceRoot":"","sources":["../../../src/agents/mcp_agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAA;AAEzE,OAAO,KAAK,EAAE,0BAA0B,EAAqB,MAAM,sCAAsC,CAAA;AAEzG,OAAO,KAAK,EACV,WAAW,EACZ,MAAM,0BAA0B,CAAA;AACjC,OAAO,KAAK,EAAE,uBAAuB,EAAiB,MAAM,uBAAuB,CAAA;AACnF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAA;AACrE,OAAO,KAAK,EAAe,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAC9D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,KAAK,CAAA;AACpC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAG1D,OAAO,EAGL,aAAa,EAEd,MAAM,0BAA0B,CAAA;AAQjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAA;AAEnE,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAO7D,qBAAa,QAAQ;IACnB,OAAO,CAAC,GAAG,CAAC,CAA4B;IACxC,OAAO,CAAC,MAAM,CAAC,CAAW;IAC1B,OAAO,CAAC,UAAU,CAAiB;IACnC,OAAO,CAAC,QAAQ,CAAQ;IACxB,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,eAAe,CAAU;IACjC,OAAO,CAAC,eAAe,CAA2B;IAClD,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAC,CAAe;IACpC,OA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