mcp-use 0.1.10 → 0.1.12

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;IAqEtC;;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
@@ -536,15 +500,19 @@ export class MCPAgent {
536
500
  logger.info(`💬 Received query for streamEvents: '${display_query}'`);
537
501
  // Add user message to history if memory enabled
538
502
  if (this.memoryEnabled) {
503
+ logger.info(`🔄 Adding user message to history: ${query}`);
539
504
  this.addToHistory(new HumanMessage(query));
540
505
  }
541
506
  // Prepare history
542
507
  const historyToUse = externalHistory ?? this.conversationHistory;
543
508
  const langchainHistory = [];
544
509
  for (const msg of historyToUse) {
545
- if (msg instanceof HumanMessage || msg instanceof AIMessage) {
510
+ if (msg instanceof HumanMessage || msg instanceof AIMessage || msg instanceof ToolMessage) {
546
511
  langchainHistory.push(msg);
547
512
  }
513
+ else {
514
+ logger.info(`⚠️ Skipped message of type: ${msg.constructor.name}`);
515
+ }
548
516
  }
549
517
  // Prepare inputs
550
518
  const inputs = { input: query, chat_history: langchainHistory };
@@ -565,11 +533,8 @@ export class MCPAgent {
565
533
  // Capture final response from chain end event
566
534
  if (event.event === 'on_chain_end' && event.data?.output) {
567
535
  const output = event.data.output;
568
- if (typeof output === 'string') {
569
- finalResponse = output;
570
- }
571
- else if (output?.output && typeof output.output === 'string') {
572
- finalResponse = output.output;
536
+ if (Array.isArray(output) && output.length > 0 && output[0]?.text) {
537
+ finalResponse = output[0].text;
573
538
  }
574
539
  }
575
540
  }
@@ -628,24 +593,68 @@ export class MCPAgent {
628
593
  }
629
594
  }
630
595
  /**
631
- * Attempt to create structured output from raw result with validation.
596
+ * Attempt to create structured output from raw result with validation and retry logic.
632
597
  */
633
598
  async _attemptStructuredOutput(rawResult, structuredLlm, outputSchema, schemaDescription) {
634
- const formatPrompt = `
635
- Please format the following information according to the specified schema.
636
- Extract and structure the relevant information from the content below.
637
-
638
- Required schema fields:
639
- ${schemaDescription}
640
-
641
- Content to format:
642
- ${rawResult}
643
-
644
- Please provide the information in the requested structured format.
645
- If any required information is missing, you must indicate this clearly.
646
- `;
647
- const structuredResult = await structuredLlm.invoke(formatPrompt);
648
- // Validate that the result is complete (basic check)
599
+ logger.debug(`🔄 Attempting structured output with schema: ${outputSchema}`);
600
+ logger.debug(`🔄 Schema description: ${schemaDescription}`);
601
+ logger.debug(`🔄 Raw result: ${JSON.stringify(rawResult, null, 2)}`);
602
+ // Get detailed schema information for better prompting
603
+ const maxRetries = 3;
604
+ let lastError = '';
605
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
606
+ logger.info(`🔄 Structured output attempt ${attempt}/${maxRetries}`);
607
+ let formatPrompt = `
608
+ Please format the following information according to the EXACT schema specified below.
609
+ You must use the exact field names and types as shown in the schema.
610
+
611
+ Required schema format:
612
+ ${schemaDescription}
613
+
614
+ Content to format:
615
+ ${rawResult}
616
+
617
+ IMPORTANT:
618
+ - Use ONLY the field names specified in the schema
619
+ - Match the data types exactly (string, number, boolean, array, etc.)
620
+ - Include ALL required fields
621
+ - Return valid JSON that matches the schema structure exactly
622
+ `;
623
+ // Add specific error feedback for retry attempts
624
+ if (attempt > 1) {
625
+ formatPrompt += `
626
+
627
+ PREVIOUS ATTEMPT FAILED with error: ${lastError}
628
+ Please fix the issues mentioned above and ensure the output matches the schema exactly.
629
+ `;
630
+ }
631
+ try {
632
+ const structuredResult = await structuredLlm.invoke(formatPrompt);
633
+ logger.info(`🔄 Structured result attempt ${attempt}: ${JSON.stringify(structuredResult, null, 2)}`);
634
+ // Validate the structured result
635
+ const validatedResult = this._validateStructuredResult(structuredResult, outputSchema);
636
+ logger.info(`✅ Structured output successful on attempt ${attempt}`);
637
+ return validatedResult;
638
+ }
639
+ catch (e) {
640
+ lastError = e instanceof Error ? e.message : String(e);
641
+ logger.warn(`⚠️ Structured output attempt ${attempt} failed: ${lastError}`);
642
+ if (attempt === maxRetries) {
643
+ logger.error(`❌ All ${maxRetries} structured output attempts failed`);
644
+ throw new Error(`Failed to generate valid structured output after ${maxRetries} attempts. Last error: ${lastError}`);
645
+ }
646
+ // Continue to next attempt
647
+ continue;
648
+ }
649
+ }
650
+ // This should never be reached, but TypeScript requires it
651
+ throw new Error('Unexpected error in structured output generation');
652
+ }
653
+ /**
654
+ * Validate the structured result against the schema with detailed error reporting
655
+ */
656
+ _validateStructuredResult(structuredResult, outputSchema) {
657
+ // Use Zod to validate the structured result
649
658
  try {
650
659
  // Use Zod to validate the structured result
651
660
  const validatedResult = outputSchema.parse(structuredResult);
@@ -677,20 +686,8 @@ export class MCPAgent {
677
686
  * Enhance the query with schema information to make the agent aware of required fields.
678
687
  */
679
688
  _enhanceQueryWithSchema(query, outputSchema) {
680
- const schemaFields = [];
681
689
  try {
682
- // Get field information from the schema
683
- const schemaType = outputSchema;
684
- if (schemaType._def && schemaType._def.shape) {
685
- for (const [fieldName, fieldSchema] of Object.entries(schemaType._def.shape)) {
686
- const field = fieldSchema;
687
- const description = field._def?.description || field.description || fieldName;
688
- const isOptional = field.isOptional?.() ?? field._def?.typeName === 'ZodOptional';
689
- const isNullable = field.isNullable?.() ?? field._def?.typeName === 'ZodNullable';
690
- schemaFields.push(`- ${fieldName}: ${description} ${(isOptional || isNullable) ? '(optional)' : '(required)'}`);
691
- }
692
- }
693
- const schemaDescription = schemaFields.join('\n');
690
+ const schemaDescription = JSON.stringify(zodToJsonSchema(outputSchema), null, 2);
694
691
  // Enhance the query with schema awareness
695
692
  const enhancedQuery = `
696
693
  ${query}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-use",
3
3
  "type": "module",
4
- "version": "0.1.10",
4
+ "version": "0.1.12",
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",