import type { StreamEvent } from "@langchain/core/tracers/log_stream"; import { SystemMessage } from "langchain"; import type { ZodSchema } from "zod"; import { ObservabilityManager } from "../observability/index.js"; import type { BaseMessage, MCPAgentOptions } from "./types.js"; /** Tool invocation details yielded by the LangChain agent. */ export interface LangChainAgentAction { /** Tool name. */ tool: string; /** Arguments generated by the model. */ toolInput: any; /** LangChain action log. */ log: string; } /** A completed tool invocation yielded during LangChain agent execution. */ export interface AgentStep { /** Tool invocation requested by the model. */ action: LangChainAgentAction; /** Serialized result returned by the tool. */ observation: string; } import type { RunOptions } from "./run_options.js"; /** Runs a LangChain tool-calling agent against MCP servers. */ export declare class MCPAgent { /** * Get the mcp-use package version. * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.) */ static getPackageVersion(): string; private llm?; private client?; private connectors; private maxSteps; private autoInitialize; private memoryEnabled; private disallowedTools; private additionalTools; /** Names of tools invoked during the current or most recent execution. */ toolsUsedNames: string[]; private exposeResourcesAsTools; private exposePromptsAsTools; private useServerManager; private verbose; private observe; private systemPrompt?; private systemPromptTemplateOverride?; private additionalInstructions?; private _initialized; private conversationHistory; private _agentExecutor; private sessions; private systemMessage; private _tools; private adapter; private serverManager; private telemetry; private modelProvider; private modelName; /** Observability callbacks and trace lifecycle manager. */ observabilityManager: ObservabilityManager; private callbacks; private metadata; private tags; private isRemote; private remoteAgent; private isSimplifiedMode; private llmString?; private llmConfig?; private mcpServersConfig?; private clientOwnedByAgent; /** * Creates a LangChain MCP agent. * * @param options - Model, MCP servers, tools, and execution settings. * @throws Error if local execution does not include a model and MCP client, * connectors, or server configurations. */ constructor(options: MCPAgentOptions); /** * Creates configured clients and models, connects MCP servers, loads tools, * and builds the LangChain executor. * * @throws Error if a configured model or MCP server cannot be initialized. */ initialize(): Promise; private createSystemMessageFromTools; private createAgent; /** @returns A shallow copy of the stored LangChain message history. */ getConversationHistory(): BaseMessage[]; /** Clears stored history, retaining the system message when memory is enabled. */ clearConversationHistory(): void; private addToHistory; /** @returns The current LangChain system message, or `null` before creation. */ getSystemMessage(): SystemMessage | null; /** * Replaces the system instruction and rebuilds an initialized executor. * * @param message - New system instruction. */ setSystemMessage(message: string): void; /** * Replaces the tool denylist for the next initialization. * * @param disallowedTools - MCP tool names to omit. */ setDisallowedTools(disallowedTools: string[]): void; /** @returns The configured MCP tool denylist. */ getDisallowedTools(): string[]; /** * Set metadata for observability traces * @param newMetadata - Key-value pairs to add to metadata. Keys should be strings, values should be serializable. */ setMetadata(newMetadata: Record): void; /** * Get current metadata * @returns A copy of the current metadata object */ getMetadata(): Record; /** * Set tags for observability traces * @param newTags - Array of tag strings to add. Duplicates will be automatically removed. */ setTags(newTags: string[]): void; /** * Get current tags * @returns A copy of the current tags array */ getTags(): string[]; /** * Sanitize metadata to ensure compatibility with observability platforms * @param metadata - Raw metadata object * @returns Sanitized metadata object */ private sanitizeMetadata; /** * Sanitize tags to ensure compatibility with observability platforms * @param tags - Array of tag strings * @returns Array of sanitized tag strings */ private sanitizeTags; /** * Get MCP server information for observability metadata */ private getMCPServerInfo; private _normalizeOutput; /** * Check if a message is AI/assistant-like regardless of whether it's a class instance. * Handles version mismatches, serialization boundaries, and different message formats. * * This method solves the issue where messages from LangChain agents may be plain JavaScript * objects (e.g., `{ type: 'ai', content: '...' }`) instead of AIMessage instances due to * serialization/deserialization across module boundaries or version mismatches. * * @example * ```ts * // Real AIMessage instance (standard case). * _isAIMessageLike(new AIMessage("hello")); // true * ``` * * @example * ```ts * // Plain object after serialization (fixes issue #446). * _isAIMessageLike({ type: "ai", content: "hello" }); // true * ``` * * @example * ```ts * // OpenAI-style format with role. * _isAIMessageLike({ role: "assistant", content: "hello" }); // true * ``` * * @example * ```ts * // Object with getType() method. * _isAIMessageLike({ getType: () => "ai", content: "hello" }); // true * ``` * * @param message - The message object to check * @returns true if the message represents an AI/assistant message */ private _isAIMessageLike; /** * Check if a message has tool calls, handling both class instances and plain objects. * Safely checks for tool_calls array presence. * * @example * ```ts * const message = new AIMessage({ * content: "", * tool_calls: [{ name: "add", args: {} }], * }); * _messageHasToolCalls(message); // true * ``` * * @example * ```ts * _messageHasToolCalls({ * type: "ai", * tool_calls: [{ name: "add" }], * }); // true * ``` * * @example * ```ts * _messageHasToolCalls({ type: "ai", content: "hello" }); // false * ``` * * @param message - The message object to check * @returns true if the message has non-empty tool_calls array */ private _messageHasToolCalls; /** * Check if a message is a HumanMessage-like object. * Handles both class instances and plain objects from serialization. * * @example * ```ts * _isHumanMessageLike(new HumanMessage("hello")); // true * _isHumanMessageLike({ type: "human", content: "hello" }); // true * ``` * * @param message - The message object to check * @returns true if the message represents a human message */ private _isHumanMessageLike; /** * Check if a message is a ToolMessage-like object. * Handles both class instances and plain objects from serialization. * * @example * ```ts * const message = new ToolMessage({ * content: "result", * tool_call_id: "123", * }); * _isToolMessageLike(message); // true * _isToolMessageLike({ type: "tool", content: "result" }); // true * ``` * * @param message - The message object to check * @returns true if the message represents a tool message */ private _isToolMessageLike; /** * Extract content from a message, handling both AIMessage instances and plain objects. * * @example * ```ts * _getMessageContent(new AIMessage("hello")); // "hello" * ``` * * @example * ```ts * _getMessageContent({ type: "ai", content: "hello" }); // "hello" * ``` * * @param message - The message object to extract content from * @returns The content of the message, or undefined if not present */ private _getMessageContent; private _consumeAndReturn; /** * Runs the agent with options object and returns a promise for the final result. */ run(options: RunOptions): Promise; /** * Runs the agent with options object and structured output, returns a promise for the typed result. */ run(options: RunOptions): Promise; /** * Runs the agent and returns a promise for the final result. * @deprecated Use the options object instead: `run({ prompt, maxSteps, ... })`. */ run(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: undefined, signal?: AbortSignal): Promise; /** * Runs the agent with structured output and returns a promise for the typed result. * @deprecated Use the options object instead: `run({ prompt, schema, maxSteps, ... })`. */ run(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema, signal?: AbortSignal): Promise; /** * Streams the agent execution with options object and returns string result. */ stream(options: RunOptions): AsyncGenerator; /** * Streams the agent execution with options object and structured output. */ stream(options: RunOptions): AsyncGenerator; /** * Streams the agent execution and yields agent steps. * @deprecated Use the options object instead: `stream({ prompt, maxSteps, ... })`. */ stream(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema, signal?: AbortSignal): AsyncGenerator; /** * Flush observability traces to the configured observability platform. * Important for serverless environments where traces need to be sent before function termination. */ flush(): Promise; /** * Flushes observability, closes owned MCP resources, and resets the executor. */ close(): Promise; /** * Yields with pretty-printed output for code mode with options object. */ prettyStreamEvents(options: RunOptions): AsyncGenerator; /** * Yields with pretty-printed output for code mode with options object and structured output. */ prettyStreamEvents(options: RunOptions): AsyncGenerator; /** * Yields with pretty-printed output for code mode. * This method formats and displays tool executions in a user-friendly way for the terminal. * @deprecated Use the options object instead: `prettyStreamEvents({ prompt, maxSteps, ... })`. */ prettyStreamEvents(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema): AsyncGenerator; /** * Yields LangChain StreamEvent objects with options object. */ streamEvents(options: RunOptions): AsyncGenerator; /** * Yields LangChain StreamEvent objects with options object and structured output. */ streamEvents(options: RunOptions): AsyncGenerator; /** * Yields LangChain StreamEvent objects from the underlying streamEvents() method. * This provides token-level streaming and fine-grained event updates. * @deprecated Use the options object instead: `streamEvents({ prompt, maxSteps, ... })`. */ streamEvents(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema, signal?: AbortSignal): AsyncGenerator; /** * Attempt to create structured output from raw result with validation and retry logic. * * @param rawResult - The raw text result from the agent * @param llm - LLM to use for structured output * @param outputSchema - The Zod schema to validate against */ private _attemptStructuredOutput; /** * Validate the structured result against the schema with detailed error reporting */ private _validateStructuredResult; /** * Enhance the query with schema information to make the agent aware of required fields. */ private _enhanceQueryWithSchema; } //# sourceMappingURL=mcp_agent_langchain.d.ts.map