mcp-use 0.1.11 → 0.1.14

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.d.ts CHANGED
@@ -12,6 +12,7 @@ export * from './src/agents/utils/index.js';
12
12
  export { ServerManager } from './src/managers/server_manager.js';
13
13
  export * from './src/managers/tools/index.js';
14
14
  export { setTelemetrySource, Telemetry } from './src/telemetry/index.js';
15
+ export { AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
15
16
  export type { StreamEvent } from '@langchain/core/tracers/log_stream';
16
17
  export { BaseConnector, HttpConnector, loadConfigFile, Logger, logger, MCPAgent, MCPClient, MCPSession, StdioConnector, WebSocketConnector };
17
18
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAA;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAA;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAA;AAElE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAE7C,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAA;AAEvE,cAAc,6BAA6B,CAAA;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAA;AAEhE,cAAc,+BAA+B,CAAA;AAG7C,OAAO,EAAE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AAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAA"}
package/dist/index.js CHANGED
@@ -14,4 +14,6 @@ export { ServerManager } from './src/managers/server_manager.js';
14
14
  export * from './src/managers/tools/index.js';
15
15
  // Export telemetry utilities
16
16
  export { setTelemetrySource, Telemetry } from './src/telemetry/index.js';
17
+ // Re-export message classes to ensure a single constructor instance is shared by consumers
18
+ export { AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
17
19
  export { BaseConnector, HttpConnector, loadConfigFile, Logger, logger, MCPAgent, MCPClient, MCPSession, StdioConnector, WebSocketConnector };
@@ -3,7 +3,7 @@ import type { BaseMessage } from '@langchain/core/messages';
3
3
  import type { StructuredToolInterface } from '@langchain/core/tools';
4
4
  import type { StreamEvent } from '@langchain/core/tracers/log_stream';
5
5
  import type { AgentStep } from 'langchain/agents';
6
- import type { z } from 'zod';
6
+ import type { ZodSchema } from 'zod';
7
7
  import type { MCPClient } from '../client.js';
8
8
  import type { BaseConnector } from '../connectors/base.js';
9
9
  import { SystemMessage } from '@langchain/core/messages';
@@ -69,12 +69,12 @@ export declare class MCPAgent {
69
69
  /**
70
70
  * Runs the agent with structured output and returns a promise for the typed result.
71
71
  */
72
- run<T>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: z.ZodSchema<T>): Promise<T>;
72
+ run<T>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): Promise<T>;
73
73
  /**
74
74
  * Runs the agent and yields intermediate steps as an async generator.
75
75
  * If outputSchema is provided, returns structured output of type T.
76
76
  */
77
- stream<T = string>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: z.ZodSchema<T>): AsyncGenerator<AgentStep, string | T, void>;
77
+ stream<T = string>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): AsyncGenerator<AgentStep, string | T, void>;
78
78
  close(): Promise<void>;
79
79
  /**
80
80
  * Yields LangChain StreamEvent objects from the underlying streamEvents() method.
@@ -82,9 +82,13 @@ export declare class MCPAgent {
82
82
  */
83
83
  streamEvents(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[]): AsyncGenerator<StreamEvent, void, void>;
84
84
  /**
85
- * Attempt to create structured output from raw result with validation.
85
+ * Attempt to create structured output from raw result with validation and retry logic.
86
86
  */
87
87
  private _attemptStructuredOutput;
88
+ /**
89
+ * Validate the structured result against the schema with detailed error reporting
90
+ */
91
+ private _validateStructuredResult;
88
92
  /**
89
93
  * Enhance the query with schema information to make the agent aware of required fields.
90
94
  */
@@ -1 +1 @@
1
- {"version":3,"file":"mcp_agent.d.ts","sourceRoot":"","sources":["../../../src/agents/mcp_agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAqB,MAAM,sCAAsC,CAAA;AACzG,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,CAAC,EAAE,MAAM,KAAK,CAAA;AAC5B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAE1D,OAAO,EAGL,aAAa,EACd,MAAM,0BAA0B,CAAA;AAUjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAA;AAEnE,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;AAK7D,qBAAa,QAAQ;IACnB,OAAO,CAAC,GA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AE,MAAM,EACb,QAAQ,CAAC,EAAE,MAAM,EACjB,eAAe,UAAO,EACtB,eAAe,CAAC,EAAE,WAAW,EAAE,GAC9B,cAAc,CAAC,WAAW,EAAE,IAAI,EAAE,IAAI,CAAC;IAgJ1C;;OAEG;YACW,wBAAwB;IAqFtC;;OAEG;IACH,OAAO,CAAC,yBAAyB;IAgCjC;;OAEG;IACH,OAAO,CAAC,uBAAuB;CAuBhC"}
@@ -1,7 +1,8 @@
1
- import { AIMessage, HumanMessage, SystemMessage, } from '@langchain/core/messages';
1
+ import { AIMessage, HumanMessage, SystemMessage, ToolMessage, } from '@langchain/core/messages';
2
2
  import { OutputParserException } from '@langchain/core/output_parsers';
3
3
  import { ChatPromptTemplate, MessagesPlaceholder, } from '@langchain/core/prompts';
4
4
  import { AgentExecutor, createToolCallingAgent, } from 'langchain/agents';
5
+ import { zodToJsonSchema } from 'zod-to-json-schema';
5
6
  import { LangChainAdapter } from '../adapters/langchain_adapter.js';
6
7
  import { logger } from '../logging.js';
7
8
  import { ServerManager } from '../managers/server_manager.js';
@@ -231,6 +232,7 @@ export class MCPAgent {
231
232
  let schemaDescription = '';
232
233
  if (outputSchema) {
233
234
  query = this._enhanceQueryWithSchema(query, outputSchema);
235
+ logger.debug(`🔄 Structured output requested, schema: ${JSON.stringify(zodToJsonSchema(outputSchema), null, 2)}`);
234
236
  // Check if withStructuredOutput method exists
235
237
  if ('withStructuredOutput' in this.llm && typeof this.llm.withStructuredOutput === 'function') {
236
238
  structuredLlm = this.llm.withStructuredOutput(outputSchema);
@@ -239,25 +241,7 @@ export class MCPAgent {
239
241
  // Fallback: use the same LLM but we'll handle structure in our helper method
240
242
  structuredLlm = this.llm;
241
243
  }
242
- // Get schema description for feedback
243
- try {
244
- const schemaType = outputSchema;
245
- if (schemaType._def && schemaType._def.shape) {
246
- const fields = [];
247
- for (const [key, fieldSchema] of Object.entries(schemaType._def.shape)) {
248
- const field = fieldSchema;
249
- const isOptional = field.isOptional?.() ?? field._def?.typeName === 'ZodOptional';
250
- const isNullable = field.isNullable?.() ?? field._def?.typeName === 'ZodNullable';
251
- const description = field._def?.description || field.description || key;
252
- fields.push(`- ${key}: ${description} ${(isOptional || isNullable) ? '(optional)' : '(required)'}`);
253
- }
254
- schemaDescription = fields.join('\n');
255
- }
256
- }
257
- catch (e) {
258
- logger.warn(`Could not extract schema details: ${e}`);
259
- schemaDescription = `Schema: ${outputSchema.constructor.name}`;
260
- }
244
+ schemaDescription = JSON.stringify(zodToJsonSchema(outputSchema), null, 2);
261
245
  }
262
246
  try {
263
247
  if (manageConnector && !this._initialized) {
@@ -312,6 +296,7 @@ export class MCPAgent {
312
296
  try {
313
297
  logger.debug('Starting agent step execution');
314
298
  const nextStepOutput = await this._agentExecutor._takeNextStep(nameToToolMap, inputs, intermediateSteps);
299
+ // Agent finish handling
315
300
  if (nextStepOutput.returnValues) {
316
301
  logger.info(`✅ Agent finished at step ${stepNum + 1}`);
317
302
  result = nextStepOutput.returnValues?.output ?? 'No output generated';
@@ -320,6 +305,7 @@ export class MCPAgent {
320
305
  try {
321
306
  logger.info('🔧 Attempting structured output...');
322
307
  const structuredResult = await this._attemptStructuredOutput(result, structuredLlm, outputSchema, schemaDescription);
308
+ logger.debug(`🔄 Structured result: ${JSON.stringify(structuredResult)}`);
323
309
  // Add the final response to conversation history if memory is enabled
324
310
  if (this.memoryEnabled) {
325
311
  this.addToHistory(new AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
@@ -331,21 +317,21 @@ export class MCPAgent {
331
317
  catch (e) {
332
318
  logger.warn(`⚠️ Structured output failed: ${e}`);
333
319
  // Continue execution to gather missing information
334
- const missingInfoPrompt = `
320
+ const failedStructuredOutputPrompt = `
335
321
  The current result cannot be formatted into the required structure.
336
322
  Error: ${String(e)}
337
323
 
338
324
  Current information: ${result}
339
325
 
340
- Please continue working to gather the missing information needed for:
326
+ If information is missing, please continue working to gather the missing information needed for:
341
327
  ${schemaDescription}
342
-
343
- Focus on finding the specific missing details.
328
+
329
+ If the information is complete, please return the result in the required structure.
344
330
  `;
345
331
  // Add this as feedback and continue the loop
346
- inputs.input = missingInfoPrompt;
332
+ inputs.input = failedStructuredOutputPrompt;
347
333
  if (this.memoryEnabled) {
348
- this.addToHistory(new HumanMessage(missingInfoPrompt));
334
+ this.addToHistory(new HumanMessage(failedStructuredOutputPrompt));
349
335
  }
350
336
  logger.info('🔄 Continuing execution to gather missing information...');
351
337
  continue;
@@ -403,28 +389,6 @@ export class MCPAgent {
403
389
  logger.warn(`⚠️ Agent stopped after reaching max iterations (${steps})`);
404
390
  result = `Agent stopped after reaching the maximum number of steps (${steps}).`;
405
391
  }
406
- // If structured output was requested but not achieved, attempt one final time
407
- if (outputSchema && structuredLlm && !success) {
408
- try {
409
- logger.info('🔧 Final attempt at structured output...');
410
- const structuredResult = await this._attemptStructuredOutput(result, structuredLlm, outputSchema, schemaDescription);
411
- // Add the final response to conversation history if memory is enabled
412
- if (this.memoryEnabled) {
413
- this.addToHistory(new AIMessage(`Structured result: ${JSON.stringify(structuredResult)}`));
414
- }
415
- logger.info('✅ Final structured output successful');
416
- success = true;
417
- return structuredResult;
418
- }
419
- catch (e) {
420
- logger.error(`❌ Final structured output attempt failed: ${e}`);
421
- throw new Error(`Failed to generate structured output after ${steps} steps: ${e}`);
422
- }
423
- }
424
- // Add the final response to conversation history if memory is enabled (regular case)
425
- if (this.memoryEnabled && !outputSchema) {
426
- this.addToHistory(new AIMessage(result));
427
- }
428
392
  logger.info('🎉 Agent execution complete');
429
393
  success = true;
430
394
  // Return regular result
@@ -543,9 +507,12 @@ export class MCPAgent {
543
507
  const historyToUse = externalHistory ?? this.conversationHistory;
544
508
  const langchainHistory = [];
545
509
  for (const msg of historyToUse) {
546
- if (msg instanceof HumanMessage || msg instanceof AIMessage) {
510
+ if (msg instanceof HumanMessage || msg instanceof AIMessage || msg instanceof ToolMessage) {
547
511
  langchainHistory.push(msg);
548
512
  }
513
+ else {
514
+ logger.info(`⚠️ Skipped message of type: ${msg.constructor.name}`);
515
+ }
549
516
  }
550
517
  // Prepare inputs
551
518
  const inputs = { input: query, chat_history: langchainHistory };
@@ -626,24 +593,81 @@ export class MCPAgent {
626
593
  }
627
594
  }
628
595
  /**
629
- * Attempt to create structured output from raw result with validation.
596
+ * Attempt to create structured output from raw result with validation and retry logic.
630
597
  */
631
598
  async _attemptStructuredOutput(rawResult, structuredLlm, outputSchema, schemaDescription) {
632
- const formatPrompt = `
633
- Please format the following information according to the specified schema.
634
- Extract and structure the relevant information from the content below.
635
-
636
- Required schema fields:
637
- ${schemaDescription}
638
-
639
- Content to format:
640
- ${rawResult}
641
-
642
- Please provide the information in the requested structured format.
643
- If any required information is missing, you must indicate this clearly.
644
- `;
645
- const structuredResult = await structuredLlm.invoke(formatPrompt);
646
- // Validate that the result is complete (basic check)
599
+ logger.info(`🔄 Attempting structured output with schema: ${outputSchema}`);
600
+ logger.info(`🔄 Schema description: ${schemaDescription}`);
601
+ logger.info(`🔄 Raw result: ${JSON.stringify(rawResult, null, 2)}`);
602
+ // Handle different input formats - rawResult might be an array or object from the agent
603
+ let textContent = '';
604
+ if (typeof rawResult === 'string') {
605
+ textContent = rawResult;
606
+ }
607
+ else if (rawResult && typeof rawResult === 'object') {
608
+ // Handle object format
609
+ textContent = JSON.stringify(rawResult);
610
+ }
611
+ // If we couldn't extract text, use the stringified version
612
+ if (!textContent) {
613
+ textContent = JSON.stringify(rawResult);
614
+ }
615
+ // Get detailed schema information for better prompting
616
+ const maxRetries = 3;
617
+ let lastError = '';
618
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
619
+ logger.info(`🔄 Structured output attempt ${attempt}/${maxRetries}`);
620
+ let formatPrompt = `
621
+ Please format the following information according to the EXACT schema specified below.
622
+ You must use the exact field names and types as shown in the schema.
623
+
624
+ Required schema format:
625
+ ${schemaDescription}
626
+
627
+ Content to extract from:
628
+ ${textContent}
629
+
630
+ IMPORTANT:
631
+ - Use ONLY the field names specified in the schema
632
+ - Match the data types exactly (string, number, boolean, array, etc.)
633
+ - Include ALL required fields
634
+ - Return valid JSON that matches the schema structure exactly
635
+ `;
636
+ // Add specific error feedback for retry attempts
637
+ if (attempt > 1) {
638
+ formatPrompt += `
639
+
640
+ PREVIOUS ATTEMPT FAILED with error: ${lastError}
641
+ Please fix the issues mentioned above and ensure the output matches the schema exactly.
642
+ `;
643
+ }
644
+ try {
645
+ const structuredResult = await structuredLlm.invoke(formatPrompt);
646
+ logger.info(`🔄 Structured result attempt ${attempt}: ${JSON.stringify(structuredResult, null, 2)}`);
647
+ // Validate the structured result
648
+ const validatedResult = this._validateStructuredResult(structuredResult, outputSchema);
649
+ logger.info(`✅ Structured output successful on attempt ${attempt}`);
650
+ return validatedResult;
651
+ }
652
+ catch (e) {
653
+ lastError = e instanceof Error ? e.message : String(e);
654
+ logger.warn(`⚠️ Structured output attempt ${attempt} failed: ${lastError}`);
655
+ if (attempt === maxRetries) {
656
+ logger.error(`❌ All ${maxRetries} structured output attempts failed`);
657
+ throw new Error(`Failed to generate valid structured output after ${maxRetries} attempts. Last error: ${lastError}`);
658
+ }
659
+ // Continue to next attempt
660
+ continue;
661
+ }
662
+ }
663
+ // This should never be reached, but TypeScript requires it
664
+ throw new Error('Unexpected error in structured output generation');
665
+ }
666
+ /**
667
+ * Validate the structured result against the schema with detailed error reporting
668
+ */
669
+ _validateStructuredResult(structuredResult, outputSchema) {
670
+ // Use Zod to validate the structured result
647
671
  try {
648
672
  // Use Zod to validate the structured result
649
673
  const validatedResult = outputSchema.parse(structuredResult);
@@ -675,20 +699,8 @@ export class MCPAgent {
675
699
  * Enhance the query with schema information to make the agent aware of required fields.
676
700
  */
677
701
  _enhanceQueryWithSchema(query, outputSchema) {
678
- const schemaFields = [];
679
702
  try {
680
- // Get field information from the schema
681
- const schemaType = outputSchema;
682
- if (schemaType._def && schemaType._def.shape) {
683
- for (const [fieldName, fieldSchema] of Object.entries(schemaType._def.shape)) {
684
- const field = fieldSchema;
685
- const description = field._def?.description || field.description || fieldName;
686
- const isOptional = field.isOptional?.() ?? field._def?.typeName === 'ZodOptional';
687
- const isNullable = field.isNullable?.() ?? field._def?.typeName === 'ZodNullable';
688
- schemaFields.push(`- ${fieldName}: ${description} ${(isOptional || isNullable) ? '(optional)' : '(required)'}`);
689
- }
690
- }
691
- const schemaDescription = schemaFields.join('\n');
703
+ const schemaDescription = JSON.stringify(zodToJsonSchema(outputSchema), null, 2);
692
704
  // Enhance the query with schema awareness
693
705
  const enhancedQuery = `
694
706
  ${query}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-use",
3
3
  "type": "module",
4
- "version": "0.1.11",
4
+ "version": "0.1.14",
5
5
  "packageManager": "pnpm@10.6.1",
6
6
  "description": "A utility library for integrating Model Context Protocol (MCP) with LangChain, Zod, and related tools. Provides helpers for schema conversion, event streaming, and SDK usage.",
7
7
  "author": "Zane",
@@ -94,7 +94,7 @@
94
94
  "winston": "^3.17.0",
95
95
  "ws": "^8.18.2",
96
96
  "zod": "^3.25.48",
97
- "zod-to-json-schema": "^3.24.5"
97
+ "zod-to-json-schema": "^3.24.6"
98
98
  },
99
99
  "devDependencies": {
100
100
  "@antfu/eslint-config": "^4.13.2",