UNPKG

mcp-use

Version:

Opinionated MCP Framework for TypeScript (@modelcontextprotocol/sdk compatible) - Build MCP Agents, Clients and Servers with support for ChatGPT Apps, Code Mode, OAuth, Notifications, Sampling, Observability and more.

291 lines • 11.5 kB
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"; export type { LanguageModel, BaseMessage, MCPAgentOptions, MCPServerConfig, } from "./types.js"; export type { LLMConfig } from "./utils/llm_provider.js"; /** * Represents a single step in the agent's execution */ export interface AgentStep { action: { tool: string; toolInput: any; log: string; }; observation: string; } /** * Options for agent run, stream, and streamEvents methods */ export interface RunOptions<T = string> { prompt: string; maxSteps?: number; manageConnector?: boolean; externalHistory?: BaseMessage[]; schema?: ZodSchema<T>; } 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; toolsUsedNames: string[]; 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; observabilityManager: ObservabilityManager; private callbacks; private metadata; private tags; private isRemote; private remoteAgent; private isSimplifiedMode; private llmString?; private llmConfig?; private mcpServersConfig?; private clientOwnedByAgent; constructor(options: MCPAgentOptions); initialize(): Promise<void>; private createSystemMessageFromTools; private createAgent; getConversationHistory(): BaseMessage[]; clearConversationHistory(): void; private addToHistory; getSystemMessage(): SystemMessage | null; setSystemMessage(message: string): void; setDisallowedTools(disallowedTools: string[]): void; 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<string, any>): void; /** * Get current metadata * @returns A copy of the current metadata object */ getMetadata(): Record<string, any>; /** * 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 * // Real AIMessage instance (standard case) * _isAIMessageLike(new AIMessage("hello")) // => true * * @example * // Plain object after serialization (fixes issue #446) * _isAIMessageLike({ type: "ai", content: "hello" }) // => true * * @example * // OpenAI-style format with role * _isAIMessageLike({ role: "assistant", content: "hello" }) // => true * * @example * // 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 * // AIMessage with tool calls * const msg = new AIMessage({ content: "", tool_calls: [{ name: "add", args: {} }] }); * _messageHasToolCalls(msg) // => true * * @example * // Plain object with tool calls * _messageHasToolCalls({ type: "ai", tool_calls: [{ name: "add" }] }) // => true * * @example * // Message without tool calls * _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 * _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 * _isToolMessageLike(new ToolMessage({ content: "result", tool_call_id: "123" })) // => 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 * // From AIMessage instance * _getMessageContent(new AIMessage("hello")) // => "hello" * * @example * // From plain object * _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<string>; /** * Runs the agent with options object and structured output, returns a promise for the typed result. */ run<T>(options: RunOptions<T>): Promise<T>; /** * Runs the agent and returns a promise for the final result. * @deprecated Use options object instead: run({ prompt, maxSteps, ... }) */ run(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[]): Promise<string>; /** * Runs the agent with structured output and returns a promise for the typed result. * @deprecated Use options object instead: run({ prompt, schema, maxSteps, ... }) */ run<T>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): Promise<T>; /** * Streams the agent execution with options object and returns string result. */ stream(options: RunOptions): AsyncGenerator<AgentStep, string, void>; /** * Streams the agent execution with options object and structured output. */ stream<T>(options: RunOptions<T>): AsyncGenerator<AgentStep, T, void>; /** * Streams the agent execution and yields agent steps. * @deprecated Use options object instead: stream({ prompt, maxSteps, ... }) */ stream<T = string>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): AsyncGenerator<AgentStep, string | T, void>; /** * Flush observability traces to the configured observability platform. * Important for serverless environments where traces need to be sent before function termination. */ flush(): Promise<void>; close(): Promise<void>; /** * Yields with pretty-printed output for code mode with options object. */ prettyStreamEvents(options: RunOptions): AsyncGenerator<void, string, void>; /** * Yields with pretty-printed output for code mode with options object and structured output. */ prettyStreamEvents<T>(options: RunOptions<T>): AsyncGenerator<void, string, void>; /** * Yields with pretty-printed output for code mode. * This method formats and displays tool executions in a user-friendly way with syntax highlighting. * @deprecated Use options object instead: prettyStreamEvents({ prompt, maxSteps, ... }) */ prettyStreamEvents<T = string>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): AsyncGenerator<void, string, void>; /** * Yields LangChain StreamEvent objects with options object. */ streamEvents(options: RunOptions): AsyncGenerator<StreamEvent, void, void>; /** * Yields LangChain StreamEvent objects with options object and structured output. */ streamEvents<T>(options: RunOptions<T>): AsyncGenerator<StreamEvent, void, void>; /** * Yields LangChain StreamEvent objects from the underlying streamEvents() method. * This provides token-level streaming and fine-grained event updates. * @deprecated Use options object instead: streamEvents({ prompt, maxSteps, ... }) */ streamEvents<T = string>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): AsyncGenerator<StreamEvent, void, void>; /** * 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.d.ts.map