@mcp-use/agent 2.0.0-beta.21 → 2.0.0-beta.22
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/.tsbuildinfo +1 -1
- package/dist/index.js +1 -1
- package/dist/langchain.js +5 -3
- package/dist/langchain.js.map +1 -1
- package/dist/observability/langfuse.d.ts.map +1 -1
- package/package.json +5 -5
package/dist/langchain.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/observability/langfuse.ts","../src/agents/display.ts","../src/agents/mcp_agent_langchain.ts","../src/adapters/langchain_adapter.ts","../src/adapters/base.ts","../src/managers/server_manager.ts","../src/managers/tools/acquire_active_mcp_server.ts","../src/managers/tools/base.ts","../src/managers/tools/add_server_from_config.ts","../src/managers/tools/connect_mcp_server.ts","../src/managers/tools/list_mcp_servers.ts","../src/managers/tools/release_mcp_server_connection.ts","../src/observability/index.ts","../src/observability/manager.ts","../src/version.ts","../src/telemetry/utils.ts","../src/agents/prompts/system_prompt_builder.ts","../src/agents/prompts/templates.ts","../src/agents/remote.ts","../src/agents/utils/llm_provider.ts","../src/agents/prompts/index.ts","../src/agents/utils/ai_sdk.ts"],"sourcesContent":["/**\n * Langfuse observability integration for MCP-use.\n *\n * This module provides automatic instrumentation and callback handler\n * for Langfuse observability platform.\n *\n * Note: This module expects environment variables to be loaded before import.\n * Users should load their environment variables using their preferred method\n * (e.g., dotenv, direct process.env assignment, or system environment).\n */\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"./types.d.ts\" />\n\nimport type { BaseCallbackHandler } from \"@langchain/core/callbacks/base\";\nimport { logger } from \"@mcp-use/client\";\n\n/**\n * Retrieve the value of an environment variable when `process.env` is available.\n *\n * @param key - The environment variable name to look up\n * @returns The variable's value if present, `undefined` otherwise\n */\nfunction getEnvVar(key: string): string | undefined {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[key];\n }\n return undefined;\n}\n\n// Check if Langfuse is disabled via environment variable\nconst langfuseDisabled =\n getEnvVar(\"MCP_USE_LANGFUSE\")?.toLowerCase() === \"false\";\n\n// Initialize variables - using const with object to avoid linter issues with mutable exports\nconst langfuseState = {\n handler: null as BaseCallbackHandler | null,\n client: null as any,\n initPromise: null as Promise<void> | null,\n};\n\n/**\n * Initializes Langfuse observability for the application and installs a callback handler that augments traces with optional agent metadata and tags.\n *\n * This will attempt to dynamically load the Langfuse LangChain integration and, if available, create and store a wrapped callback handler (and optionally a Langfuse client) on the module state so tracing can be used elsewhere in the application.\n *\n * @param agentId - Optional identifier for the agent to include in traces\n * @param metadata - Optional static metadata to attach to traces; merged with dynamic metadata if a provider is supplied\n * @param metadataProvider - Optional function that returns dynamic metadata to attach to traces at runtime\n * @param tagsProvider - Optional function that returns an array of tags to attach to traces at runtime\n */\nasync function initializeLangfuse(\n agentId?: string,\n metadata?: Record<string, any>,\n metadataProvider?: () => Record<string, any>,\n tagsProvider?: () => string[]\n): Promise<void> {\n try {\n // Dynamically import to avoid errors if package not installed\n const langfuseModule = await import(\"langfuse-langchain\").catch(() => null);\n if (!langfuseModule) {\n logger.debug(\n \"Langfuse package not installed - tracing disabled. Install with: npm install langfuse-langchain\"\n );\n return;\n }\n\n const { CallbackHandler } = langfuseModule as any;\n // Create a custom CallbackHandler wrapper to add logging and custom metadata\n class LoggingCallbackHandler extends CallbackHandler {\n private agentId?: string;\n private metadata?: Record<string, any>;\n private metadataProvider?: () => Record<string, any>;\n private tagsProvider?: () => string[];\n private verbose: boolean;\n\n constructor(\n config?: any,\n agentId?: string,\n metadata?: Record<string, any>,\n metadataProvider?: () => Record<string, any>,\n tagsProvider?: () => string[]\n ) {\n super(config);\n this.agentId = agentId;\n this.metadata = metadata;\n this.metadataProvider = metadataProvider;\n this.tagsProvider = tagsProvider;\n this.verbose = config?.verbose ?? false;\n }\n\n // Override to add custom metadata to traces\n async handleChainStart(\n chain: any,\n inputs: any,\n runId?: string,\n parentRunId?: string,\n tags?: string[],\n metadata?: any,\n name?: string,\n kwargs?: any\n ): Promise<void> {\n logger.debug(\"Langfuse: Chain start intercepted\");\n\n // Add custom tags and metadata\n const customTags = this.getCustomTags();\n const metadataToAdd = this.getMetadata();\n\n // Merge with existing tags and metadata\n const enhancedTags = [...(tags || []), ...customTags];\n const enhancedMetadata = { ...(metadata || {}), ...metadataToAdd };\n\n if (this.verbose) {\n logger.debug(\n `Langfuse: Chain start with custom tags: ${JSON.stringify(enhancedTags)}`\n );\n logger.debug(\n `Langfuse: Chain start with metadata: ${JSON.stringify(enhancedMetadata)}`\n );\n }\n\n return super.handleChainStart(\n chain,\n inputs,\n runId,\n parentRunId,\n enhancedTags,\n enhancedMetadata,\n name,\n kwargs\n );\n }\n\n // Get custom tags based on environment and agent configuration\n private getCustomTags(): string[] {\n const tags: string[] = [];\n\n // Add environment tag\n const env = this.getEnvironmentTag();\n if (env) {\n tags.push(`env:${env}`);\n }\n\n // Add agent ID tag if available\n if (this.agentId) {\n tags.push(`agent_id:${this.agentId}`);\n }\n\n // Add tags from provider if available\n if (this.tagsProvider) {\n const providerTags = this.tagsProvider();\n if (providerTags && providerTags.length > 0) {\n tags.push(...providerTags);\n }\n }\n\n return tags;\n }\n\n // Get metadata\n private getMetadata(): any {\n const metadata: any = {};\n\n // Add environment metadata\n const env = this.getEnvironmentTag();\n if (env) {\n metadata.env = env;\n }\n\n // Add agent ID metadata if available\n if (this.agentId) {\n metadata.agent_id = this.agentId;\n }\n\n // Add static metadata if provided\n if (this.metadata) {\n Object.assign(metadata, this.metadata);\n }\n\n // Add dynamic metadata from provider if available\n if (this.metadataProvider) {\n const dynamicMetadata = this.metadataProvider();\n if (dynamicMetadata) {\n Object.assign(metadata, dynamicMetadata);\n }\n }\n\n return metadata;\n }\n\n // Determine environment tag based on MCP_USE_AGENT_ENV\n private getEnvironmentTag(): string | null {\n const agentEnv = getEnvVar(\"MCP_USE_AGENT_ENV\");\n if (!agentEnv) {\n // Default to 'unknown' if environment is not explicitly set\n return \"unknown\";\n }\n\n const envLower = agentEnv.toLowerCase();\n if (envLower === \"local\" || envLower === \"development\") {\n return \"local\";\n } else if (envLower === \"production\" || envLower === \"prod\") {\n return \"production\";\n } else if (envLower === \"staging\" || envLower === \"stage\") {\n return \"staging\";\n } else if (envLower === \"hosted\" || envLower === \"cloud\") {\n return \"hosted\";\n }\n\n // For any other values, use the value as-is but sanitized\n return envLower.replace(/[^a-z0-9_-]/g, \"_\");\n }\n\n async handleLLMStart(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: LLM start intercepted\");\n if (this.verbose) {\n logger.debug(`Langfuse: LLM start args: ${JSON.stringify(args)}`);\n }\n return super.handleLLMStart(...args);\n }\n\n async handleToolStart(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: Tool start intercepted\");\n if (this.verbose) {\n logger.debug(`Langfuse: Tool start args: ${JSON.stringify(args)}`);\n }\n return super.handleToolStart(...args);\n }\n\n async handleRetrieverStart(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: Retriever start intercepted\");\n if (this.verbose) {\n logger.debug(\n `Langfuse: Retriever start args: ${JSON.stringify(args)}`\n );\n }\n return super.handleRetrieverStart(...args);\n }\n\n async handleAgentAction(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: Agent action intercepted\");\n if (this.verbose) {\n logger.debug(`Langfuse: Agent action args: ${JSON.stringify(args)}`);\n }\n return super.handleAgentAction(...args);\n }\n\n async handleAgentEnd(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: Agent end intercepted\");\n if (this.verbose) {\n logger.debug(`Langfuse: Agent end args: ${JSON.stringify(args)}`);\n }\n return super.handleAgentEnd(...args);\n }\n }\n\n // Create the handler with configuration\n // Get initial metadata and tags for handler initialization\n const initialMetadata =\n metadata || (metadataProvider ? metadataProvider() : {});\n const initialTags = tagsProvider ? tagsProvider() : [];\n\n const config = {\n publicKey: getEnvVar(\"LANGFUSE_PUBLIC_KEY\"),\n secretKey: getEnvVar(\"LANGFUSE_SECRET_KEY\"),\n baseUrl:\n getEnvVar(\"LANGFUSE_HOST\") ||\n getEnvVar(\"LANGFUSE_BASEURL\") ||\n \"https://cloud.langfuse.com\",\n flushAt: Number.parseInt(getEnvVar(\"LANGFUSE_FLUSH_AT\") || \"15\"),\n flushInterval: Number.parseInt(\n getEnvVar(\"LANGFUSE_FLUSH_INTERVAL\") || \"10000\"\n ),\n release: getEnvVar(\"LANGFUSE_RELEASE\"),\n requestTimeout: Number.parseInt(\n getEnvVar(\"LANGFUSE_REQUEST_TIMEOUT\") || \"10000\"\n ),\n enabled: getEnvVar(\"LANGFUSE_ENABLED\") !== \"false\",\n // Set trace name - can be customized via metadata.trace_name or defaults to 'mcp-use-agent'\n traceName:\n initialMetadata.trace_name ||\n getEnvVar(\"LANGFUSE_TRACE_NAME\") ||\n \"mcp-use-agent\",\n // Pass sessionId, userId, and tags to the handler\n sessionId: initialMetadata.session_id || undefined,\n userId: initialMetadata.user_id || undefined,\n tags: initialTags.length > 0 ? initialTags : undefined,\n metadata: initialMetadata || undefined,\n };\n\n logger.debug(\n \"Langfuse handler config:\",\n JSON.stringify(\n {\n traceName: config.traceName,\n sessionId: config.sessionId,\n userId: config.userId,\n tags: config.tags,\n },\n null,\n 2\n )\n );\n\n langfuseState.handler = new LoggingCallbackHandler(\n config,\n agentId,\n metadata,\n metadataProvider,\n tagsProvider\n ) as unknown as BaseCallbackHandler;\n logger.debug(\n \"Langfuse observability initialized successfully with logging enabled\"\n );\n\n // Also initialize the client for direct usage if needed\n try {\n const langfuseCore = await import(\"langfuse\").catch(() => null);\n if (langfuseCore) {\n const { Langfuse } = langfuseCore as any;\n langfuseState.client = new Langfuse({\n publicKey: getEnvVar(\"LANGFUSE_PUBLIC_KEY\"),\n secretKey: getEnvVar(\"LANGFUSE_SECRET_KEY\"),\n baseUrl: getEnvVar(\"LANGFUSE_HOST\") || \"https://cloud.langfuse.com\",\n });\n logger.debug(\"Langfuse client initialized\");\n }\n } catch (error) {\n logger.debug(`Langfuse client initialization failed: ${error}`);\n }\n } catch (error) {\n logger.debug(`Langfuse initialization error: ${error}`);\n }\n}\n\n// Only initialize if not disabled and required keys are present\nif (langfuseDisabled) {\n logger.debug(\n \"Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable\"\n );\n} else if (\n !getEnvVar(\"LANGFUSE_PUBLIC_KEY\") ||\n !getEnvVar(\"LANGFUSE_SECRET_KEY\")\n) {\n logger.debug(\n \"Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable\"\n );\n} else {\n // Create initialization promise to ensure handlers are ready when needed\n langfuseState.initPromise = initializeLangfuse();\n}\n\n// Export getters to access the state\nexport const langfuseHandler = () => langfuseState.handler;\nexport const langfuseInitPromise = () => langfuseState.initPromise;\nexport { initializeLangfuse };\n","import { stripVTControlCharacters } from \"node:util\";\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\n\n/**\n * Helper functions for pretty-printing code mode tool executions\n */\n\nconst TERMINAL_WIDTH = process.stdout.columns || 120;\n\ninterface ExecuteCodeResult {\n result: unknown;\n logs: string[];\n error: string | null;\n execution_time: number;\n}\n\n/**\n * Whether to emit ANSI escapes: only on a TTY stdout, and never when the\n * `NO_COLOR` convention is set. Edge runtimes without `process.stdout`\n * get plain text.\n */\nfunction colorsEnabled(): boolean {\n if (typeof process === \"undefined\") return false;\n if (process.env?.[\"NO_COLOR\"] !== undefined) return false;\n return process.stdout?.isTTY === true;\n}\n\ntype Style = (text: string) => string;\n\nfunction ansi(open: number, close: number): Style {\n return (text) =>\n colorsEnabled() ? `\\u001B[${open}m${text}\\u001B[${close}m` : text;\n}\n\nconst style = {\n gray: ansi(90, 39),\n bold: ansi(1, 22),\n cyan: ansi(36, 39),\n dim: ansi(2, 22),\n red: ansi(31, 39),\n green: ansi(32, 39),\n};\n\n// Remove ANSI color codes for length calculation\nfunction stripAnsi(str: string): string {\n return stripVTControlCharacters(str);\n}\n\n// wrap lines correctly, preserving ANSI codes\nfunction wrapAnsiLine(line: string, maxWidth: number): string[] {\n const stripped = stripAnsi(line);\n\n if (stripped.length <= maxWidth) return [line];\n\n const result: string[] = [];\n let visibleCount = 0;\n let current = \"\";\n let i = 0;\n\n while (i < line.length) {\n const char = line[i];\n\n if (char === \"\\x1b\") {\n // Start of escape sequence\n let sequence = char;\n i++;\n while (i < line.length) {\n const nextChar = line[i];\n sequence += nextChar;\n i++;\n if (nextChar === \"m\") break;\n }\n current += sequence;\n continue;\n }\n\n // Normal character\n current += char;\n visibleCount++;\n i++;\n\n if (visibleCount >= maxWidth) {\n result.push(current);\n current = \"\";\n visibleCount = 0;\n }\n }\n if (current) result.push(current);\n return result;\n}\n\nfunction printBox(content: string, title?: string) {\n const width = TERMINAL_WIDTH;\n\n const lines = content\n .split(\"\\n\")\n .flatMap((line) => wrapAnsiLine(line, width - 4));\n\n console.log(style.gray(\"┌\" + \"─\".repeat(width - 2) + \"┐\"));\n\n if (title) {\n const stripped = stripAnsi(title);\n const lineText = `${title} `;\n const padding = Math.max(0, width - 4 - stripped.length - 2);\n console.log(\n style.gray(\"│ \") +\n style.bold(lineText) +\n \" \".repeat(padding) +\n style.gray(\" │\")\n );\n console.log(style.gray(\"├\" + \"─\".repeat(width - 2) + \"┤\"));\n }\n\n lines.forEach((line) => {\n const stripped = stripAnsi(line);\n const padding = Math.max(0, width - 4 - stripped.length);\n console.log(\n style.gray(\"│ \") + line + \" \".repeat(padding) + style.gray(\" │\")\n );\n });\n\n console.log(style.gray(\"└\" + \"─\".repeat(width - 2) + \"┘\"));\n}\n\n/**\n * Extract code from tool input if present\n */\nfunction extractCodeFromToolInput(input: unknown): string | null {\n if (typeof input === \"object\" && input !== null && \"code\" in input) {\n const inputObj = input as Record<string, unknown>;\n return typeof inputObj.code === \"string\" ? inputObj.code : null;\n }\n return null;\n}\n\n/**\n * Type guard to check if an object is an ExecuteCodeResult\n */\nfunction isExecuteCodeResult(obj: unknown): obj is ExecuteCodeResult {\n if (typeof obj !== \"object\" || obj === null) return false;\n const result = obj as Record<string, unknown>;\n return (\n \"result\" in result &&\n \"logs\" in result &&\n Array.isArray(result.logs) &&\n \"execution_time\" in result &&\n typeof result.execution_time === \"number\" &&\n \"error\" in result &&\n (typeof result.error === \"string\" || result.error === null)\n );\n}\n\n/**\n * Parse execute_code tool result\n */\nfunction parseExecuteCodeResult(output: unknown): ExecuteCodeResult | null {\n try {\n // If output is a string, try to parse it as JSON\n if (typeof output === \"string\") {\n const parsed = JSON.parse(output);\n if (isExecuteCodeResult(parsed)) {\n return parsed;\n }\n }\n // If output is already an object with the right structure\n if (isExecuteCodeResult(output)) {\n return output;\n }\n } catch (e) {\n // Not a valid execute_code result\n }\n return null;\n}\n\n/**\n * Render content with appropriate formatting\n */\nfunction renderContent(content: unknown): string {\n if (content === null || content === undefined) {\n return \"null\";\n }\n\n if (typeof content === \"object\") {\n return JSON.stringify(content, null, 2);\n }\n\n return String(content);\n}\n\n/**\n * Unwrap tool input if it's wrapped in an \"input\" field with JSON string\n */\nfunction unwrapToolInput(input: unknown): unknown {\n // Check if input has an \"input\" field that's a JSON string\n if (typeof input === \"object\" && input !== null && \"input\" in input) {\n const inputObj = input as Record<string, unknown>;\n if (typeof inputObj.input === \"string\") {\n try {\n // Try to parse the JSON string\n return JSON.parse(inputObj.input);\n } catch (e) {\n // If parsing fails, return the original input field\n return inputObj.input;\n }\n }\n }\n return input;\n}\n\n/**\n * Handle tool start event with pretty printing\n */\nfunction handleToolStart(event: StreamEvent) {\n const toolName = event.name || \"unknown\";\n let input = event.data?.input || {};\n\n // Unwrap input if it's wrapped in a JSON string\n input = unwrapToolInput(input);\n\n // Special handling for execute_code to show the code nicely\n const code = extractCodeFromToolInput(input);\n if (code) {\n printBox(code, `${toolName} - input`);\n\n // Show other parameters if any\n const otherParams = { ...input };\n delete otherParams.code;\n if (Object.keys(otherParams).length > 0) {\n printBox(renderContent(otherParams), \"Other Parameters\");\n }\n } else {\n printBox(renderContent(input), `${toolName} - input`);\n }\n}\n\n/**\n * Extract content from LangChain ToolMessage structure\n */\nfunction extractToolMessageContent(\n output: unknown\n): { toolName: string; status: string; content: unknown } | null {\n try {\n // Check if this is a LangChain ToolMessage object (has name and content properties)\n if (\n typeof output === \"object\" &&\n output !== null &&\n \"name\" in output &&\n \"content\" in output\n ) {\n const outputObj = output as Record<string, unknown>;\n const toolName =\n (typeof outputObj.name === \"string\" ? outputObj.name : null) ||\n \"unknown\";\n // LangChain messages might have status in lc_kwargs or in the content itself\n const lcKwargs = outputObj.lc_kwargs as\n | Record<string, unknown>\n | undefined;\n const status =\n (lcKwargs?.status as string) ||\n (outputObj.status as string) ||\n \"unknown\";\n let content = outputObj.content;\n\n // Try to parse content if it's a JSON string\n if (typeof content === \"string\") {\n try {\n content = JSON.parse(content);\n } catch (e) {\n // Keep as string if not JSON\n }\n }\n\n return { toolName, status, content };\n }\n } catch (e) {\n // Not a valid ToolMessage structure\n }\n return null;\n}\n\n/**\n * Format search_tools result as a tree structure\n */\nfunction formatSearchToolsAsTree(\n tools: Array<{ server: string; name: string; description?: string }>,\n meta?: { total_tools?: number; namespaces?: string[]; result_count?: number },\n query?: string\n): string {\n // Build meta information display\n const metaLines: string[] = [];\n if (meta) {\n if (meta.total_tools !== undefined) {\n metaLines.push(`Total tools: ${meta.total_tools}`);\n }\n if (meta.namespaces && meta.namespaces.length > 0) {\n metaLines.push(`Namespaces: ${meta.namespaces.join(\", \")}`);\n }\n if (meta.result_count !== undefined) {\n metaLines.push(`Results: ${meta.result_count}`);\n }\n }\n\n if (!Array.isArray(tools) || tools.length === 0) {\n const noResultsMsg = query\n ? `No tools found for query \"${query}\"`\n : \"(no tools found)\";\n if (metaLines.length > 0) {\n return `${metaLines.join(\"\\n\")}\\n\\n${noResultsMsg}`;\n }\n return noResultsMsg;\n }\n\n // Group tools by server\n const toolsByServer: Record<\n string,\n Array<{ name: string; description?: string }>\n > = {};\n for (const tool of tools) {\n const server = tool.server || \"unknown\";\n if (!toolsByServer[server]) {\n toolsByServer[server] = [];\n }\n toolsByServer[server].push(tool);\n }\n\n // Build tree structure\n const lines: string[] = [];\n\n // Add meta information at the top if available\n if (meta) {\n if (meta.total_tools !== undefined) {\n lines.push(`Total tools: ${meta.total_tools}`);\n }\n if (meta.namespaces && meta.namespaces.length > 0) {\n lines.push(`Namespaces: ${meta.namespaces.join(\", \")}`);\n }\n if (meta.result_count !== undefined) {\n lines.push(`Results: ${meta.result_count}`);\n }\n if (lines.length > 0) {\n lines.push(\"\"); // Empty line before tree\n }\n }\n\n const servers = Object.keys(toolsByServer).sort();\n\n for (let i = 0; i < servers.length; i++) {\n const server = servers[i];\n const serverTools = toolsByServer[server];\n const isLastServer = i === servers.length - 1;\n const serverPrefix = isLastServer ? \"└─\" : \"├─\";\n\n lines.push(\n `${serverPrefix} ${style.cyan(server)} (${serverTools.length} tools)`\n );\n\n // Add tools under this server\n for (let j = 0; j < serverTools.length; j++) {\n const tool = serverTools[j];\n const isLastTool = j === serverTools.length - 1;\n const indent = isLastServer ? \" \" : \"│ \";\n const toolPrefix = isLastTool ? \"└─\" : \"├─\";\n\n // Tool name line\n const toolLine = `${indent}${toolPrefix} ${tool.name}`;\n lines.push(toolLine);\n\n // Description on new line, aligned with tool name\n if (tool.description) {\n // Calculate indent for description lines\n // Use the same base indent as the tool, then add alignment\n // If not the last tool, add vertical bar to show continuation, otherwise spaces\n const descAlign = isLastTool ? \" \" : \"│ \";\n const descriptionIndent = `${indent}${descAlign}`;\n\n // Calculate available width for description\n // Account for: indent + box padding (4 chars for \"│ \" on each side)\n const indentLength = stripAnsi(descriptionIndent).length;\n const availableWidth = Math.max(40, TERMINAL_WIDTH - indentLength - 4);\n\n // Wrap description at word boundaries\n const words = tool.description.split(/(\\s+)/); // Keep whitespace\n const wrappedLines: string[] = [];\n let currentLine = \"\";\n\n for (const word of words) {\n const testLine = currentLine + word;\n if (stripAnsi(testLine).length <= availableWidth) {\n currentLine = testLine;\n } else {\n if (currentLine) {\n wrappedLines.push(currentLine.trimEnd());\n }\n currentLine = word.trimStart();\n }\n }\n if (currentLine) {\n wrappedLines.push(currentLine.trimEnd());\n }\n\n // Add indent and dim styling to each line\n for (const descLine of wrappedLines) {\n lines.push(`${descriptionIndent}${style.dim(descLine)}`);\n }\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Handle tool end event with pretty printing\n */\nfunction handleToolEnd(event: StreamEvent) {\n const output = event.data?.output;\n\n // First, try to extract from LangChain ToolMessage structure if present\n const toolMessage = extractToolMessageContent(output);\n if (toolMessage) {\n const { toolName, status, content } = toolMessage;\n\n // For execute_code, extract the actual result from the nested structure\n if (toolName === \"execute_code\") {\n // Content might be wrapped in { content: [{ type: \"text\", text: \"...\" }] }\n let actualContent = content;\n if (\n typeof content === \"object\" &&\n content !== null &&\n \"content\" in content\n ) {\n const innerContent = content.content;\n if (Array.isArray(innerContent) && innerContent.length > 0) {\n if (innerContent[0].type === \"text\" && innerContent[0].text) {\n actualContent = innerContent[0].text;\n }\n }\n }\n\n // Now try to parse as execute_code result\n const execResult = parseExecuteCodeResult(actualContent);\n if (execResult) {\n // Format execution time in milliseconds\n const timeMs = execResult.execution_time\n ? Math.round(execResult.execution_time * 1000)\n : 0;\n const timeStr = `${timeMs}ms`;\n\n // Determine status text\n const isError =\n execResult.error !== null &&\n execResult.error !== undefined &&\n execResult.error !== \"\";\n const statusText = isError\n ? style.red(\"error\")\n : style.green(\"success\");\n const title = `${toolName} - ${statusText} - ${timeStr}`;\n\n // Only show the result, not the full object\n if (execResult.result !== null && execResult.result !== undefined) {\n const resultStr = renderContent(execResult.result);\n printBox(resultStr, title);\n } else {\n printBox(\"(no result)\", title);\n }\n\n if (execResult.logs && execResult.logs.length > 0) {\n printBox(execResult.logs.join(\"\\n\"), `Logs`);\n }\n\n if (execResult.error) {\n printBox(execResult.error, style.red(\"Error\"));\n }\n return;\n }\n }\n\n // Special handling for search_tools to display as tree\n if (toolName === \"search_tools\") {\n // Try to get the query from event input\n const toolInput = event.data?.input as\n | Record<string, unknown>\n | undefined;\n const query = toolInput?.query as string | undefined;\n\n // Extract actual content if it's wrapped\n let actualContent = content;\n if (\n typeof content === \"object\" &&\n content !== null &&\n !Array.isArray(content) &&\n \"content\" in content\n ) {\n const innerContent = content.content;\n if (Array.isArray(innerContent) && innerContent.length > 0) {\n if (innerContent[0].type === \"text\" && innerContent[0].text) {\n try {\n actualContent = JSON.parse(innerContent[0].text);\n } catch (e) {\n actualContent = innerContent[0].text;\n }\n }\n }\n }\n\n // Handle new format: object with meta and results\n if (\n typeof actualContent === \"object\" &&\n actualContent !== null &&\n !Array.isArray(actualContent) &&\n \"results\" in actualContent &&\n Array.isArray(actualContent.results)\n ) {\n const results = actualContent.results;\n const contentWithMeta = actualContent as {\n results: unknown[];\n meta?: {\n total_tools?: number;\n namespaces?: string[];\n result_count?: number;\n };\n };\n const meta = contentWithMeta.meta;\n const treeStr = formatSearchToolsAsTree(results, meta, query);\n const statusText =\n status === \"success\" ? style.green(\"Success\") : style.red(\"Error\");\n const title = `${statusText}: ${toolName} - Result`;\n printBox(treeStr, title);\n return;\n }\n\n // Handle old format: direct array (backward compatibility)\n if (Array.isArray(actualContent)) {\n const treeStr = formatSearchToolsAsTree(\n actualContent,\n undefined,\n query\n );\n const statusText =\n status === \"success\" ? style.green(\"Success\") : style.red(\"Error\");\n const title = `${statusText}: ${toolName} - Result`;\n printBox(treeStr, title);\n return;\n }\n }\n\n // Check if content indicates an error\n const contentObj =\n typeof content === \"object\" && content !== null\n ? (content as Record<string, unknown>)\n : null;\n const isError =\n (contentObj && \"isError\" in contentObj && contentObj.isError === true) ||\n status === \"error\";\n\n // Extract the actual content to display\n let displayContent = content;\n if (\n typeof content === \"object\" &&\n content !== null &&\n \"content\" in content\n ) {\n displayContent = content.content;\n\n // If content.content is an array with text items, extract the text\n if (Array.isArray(displayContent) && displayContent.length > 0) {\n if (displayContent[0].type === \"text\" && displayContent[0].text) {\n displayContent = displayContent[0].text;\n }\n }\n }\n\n // Format the content for display\n const contentStr = renderContent(displayContent);\n\n // Create title with tool name\n const statusLabel =\n status === \"success\"\n ? style.green(\"Success\")\n : isError\n ? style.red(\"Error\")\n : \"Result\";\n const title = `${statusLabel}: ${toolName} - Result`;\n\n printBox(contentStr, title);\n return;\n }\n\n // Fallback: Try to parse as direct execute_code result (not wrapped in ToolMessage)\n const execResult = parseExecuteCodeResult(output);\n if (execResult) {\n const timeMs = execResult.execution_time\n ? Math.round(execResult.execution_time * 1000)\n : 0;\n const timeStr = `${timeMs}ms`;\n\n if (execResult.result !== null && execResult.result !== undefined) {\n const resultStr = renderContent(execResult.result);\n printBox(resultStr, `Result - ${timeStr}`);\n }\n\n if (execResult.logs && execResult.logs.length > 0) {\n printBox(execResult.logs.join(\"\\n\"), `Logs`);\n }\n\n if (execResult.error) {\n printBox(execResult.error, style.red(\"Error\"));\n }\n return;\n }\n\n // Ultimate fallback: display raw output\n const outputStr = renderContent(output);\n printBox(outputStr, \"Result\");\n}\n\n/**\n * Stream events with pretty printing\n */\nexport async function* prettyStreamEvents(\n streamEventsGenerator: AsyncGenerator<StreamEvent, void, void>\n): AsyncGenerator<void, string, void> {\n let finalResponse = \"\";\n let isFirstTextChunk = true;\n let hasStreamedText = false;\n\n for await (const event of streamEventsGenerator) {\n if (event.event === \"on_tool_start\") {\n // Add newline after agent thinking if we streamed text\n if (hasStreamedText) {\n process.stdout.write(\"\\n\");\n hasStreamedText = false;\n isFirstTextChunk = true;\n }\n handleToolStart(event);\n } else if (event.event === \"on_tool_end\") {\n handleToolEnd(event);\n } else if (event.event === \"on_chat_model_stream\") {\n if (event.data?.chunk?.text) {\n const text = event.data.chunk.text;\n if (typeof text === \"string\" && text.length > 0) {\n // Add newline and robot emoji before first text chunk\n if (isFirstTextChunk) {\n process.stdout.write(\"\\n🤖 \");\n isFirstTextChunk = false;\n }\n process.stdout.write(text);\n finalResponse += text;\n hasStreamedText = true;\n }\n }\n }\n\n yield;\n }\n\n return finalResponse;\n}\n","import type { BaseCallbackHandler } from \"@langchain/core/callbacks/base\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\nimport {\n AIMessage,\n createAgent,\n HumanMessage,\n modelCallLimitMiddleware,\n SystemMessage,\n ToolMessage,\n type ReactAgent,\n} from \"langchain\";\nimport type { ZodSchema } from \"zod\";\nimport { toJSONSchema } from \"zod\";\nimport { LangChainAdapter } from \"../adapters/langchain_adapter.js\";\nimport type { MCPClient } from \"@mcp-use/client\";\nimport type { BaseConnector } from \"@mcp-use/client\";\nimport { logger } from \"@mcp-use/client\";\nimport { ServerManager } from \"../managers/server_manager.js\";\nimport { ObservabilityManager } from \"../observability/index.js\";\nimport type { MCPSession } from \"@mcp-use/client\";\nimport { extractModelInfo } from \"../telemetry/utils.js\";\nimport { Telemetry } from \"@mcp-use/client\";\nimport { getPackageVersion } from \"../version.js\";\nimport { createSystemMessage } from \"./prompts/system_prompt_builder.js\";\nimport {\n DEFAULT_SYSTEM_PROMPT_TEMPLATE,\n SERVER_MANAGER_SYSTEM_PROMPT_TEMPLATE,\n} from \"./prompts/templates.js\";\nimport { RemoteAgent } from \"./remote.js\";\nimport type {\n BaseMessage,\n LanguageModel,\n MCPAgentOptions,\n MCPServerConfig,\n} from \"./types.js\";\nimport { createLLMFromString, type LLMConfig } from \"./utils/llm_provider.js\";\n\n/** Tool invocation details yielded by the LangChain agent. */\nexport interface LangChainAgentAction {\n /** Tool name. */\n tool: string;\n /** Arguments generated by the model. */\n toolInput: any;\n /** LangChain action log. */\n log: string;\n}\n\n/** A completed tool invocation yielded during LangChain agent execution. */\nexport interface AgentStep {\n /** Tool invocation requested by the model. */\n action: LangChainAgentAction;\n /** Serialized result returned by the tool. */\n observation: string;\n}\n\nimport type { RunOptions } from \"./run_options.js\";\n\nexport type { RunOptions };\n\n/**\n * Helper function to normalize run options from either old-style positional arguments\n * or new-style options object\n */\nfunction normalizeRunOptions<T>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n): {\n query: string;\n maxSteps?: number;\n manageConnector?: boolean;\n externalHistory?: BaseMessage[];\n outputSchema?: ZodSchema<T>;\n signal?: AbortSignal;\n} {\n // Check if first argument is an options object\n if (typeof queryOrOptions === \"object\" && queryOrOptions !== null) {\n const options = queryOrOptions as RunOptions<T>;\n return {\n query: options.prompt ?? \"\",\n maxSteps: options.maxSteps,\n manageConnector: options.manageConnector,\n externalHistory: options.externalHistory,\n outputSchema: options.schema,\n signal: options.signal,\n };\n }\n\n // Old-style positional arguments\n return {\n query: queryOrOptions as string,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n signal,\n };\n}\n\n/** Runs a LangChain tool-calling agent against MCP servers. */\nexport class MCPAgent {\n /**\n * Get the mcp-use package version.\n * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)\n */\n public static getPackageVersion(): string {\n return getPackageVersion();\n }\n\n private llm?: LanguageModel;\n private client?: MCPClient;\n private connectors: BaseConnector[];\n private maxSteps: number;\n private autoInitialize: boolean;\n private memoryEnabled: boolean;\n private disallowedTools: string[];\n private additionalTools: StructuredToolInterface[];\n /** Names of tools invoked during the current or most recent execution. */\n public toolsUsedNames: string[] = [];\n private exposeResourcesAsTools: boolean = true;\n private exposePromptsAsTools: boolean = true;\n private useServerManager: boolean;\n private verbose: boolean;\n private observe: boolean;\n private systemPrompt?: string | null;\n private systemPromptTemplateOverride?: string | null;\n private additionalInstructions?: string | null;\n\n private _initialized = false;\n private conversationHistory: BaseMessage[] = [];\n private _agentExecutor: ReactAgent | null = null;\n private sessions: Record<string, MCPSession> = {};\n private systemMessage: SystemMessage | null = null;\n private _tools: StructuredToolInterface[] = [];\n private adapter: LangChainAdapter;\n private serverManager: ServerManager | null = null;\n private telemetry: Telemetry;\n private modelProvider: string;\n private modelName: string;\n\n // Observability support\n /** Observability callbacks and trace lifecycle manager. */\n public observabilityManager: ObservabilityManager;\n private callbacks: BaseCallbackHandler[] = [];\n private metadata: Record<string, any> = {};\n private tags: string[] = [];\n\n // Remote agent support\n private isRemote = false;\n private remoteAgent: RemoteAgent | null = null;\n\n // Simplified mode support\n private isSimplifiedMode = false;\n private llmString?: string;\n private llmConfig?: LLMConfig;\n private mcpServersConfig?: Record<string, MCPServerConfig>;\n private clientOwnedByAgent = false;\n\n /**\n * Creates a LangChain MCP agent.\n *\n * @param options - Model, MCP servers, tools, and execution settings.\n * @throws Error if local execution does not include a model and MCP client,\n * connectors, or server configurations.\n */\n constructor(options: MCPAgentOptions) {\n // Handle remote execution\n if (options.agentId) {\n this.isRemote = true;\n this.remoteAgent = new RemoteAgent({\n agentId: options.agentId,\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n });\n // Set default values for remote agent\n this.maxSteps = options.maxSteps ?? 5;\n this.memoryEnabled = options.memoryEnabled ?? true;\n this.autoInitialize = options.autoInitialize ?? false;\n this.verbose = options.verbose ?? false;\n this.observe = options.observe ?? true;\n this.connectors = [];\n this.disallowedTools = [];\n this.additionalTools = [];\n this.useServerManager = false;\n this.adapter = new LangChainAdapter();\n this.telemetry = Telemetry.getInstance();\n this.modelProvider = \"remote\";\n this.modelName = \"remote-agent\";\n this.observabilityManager = new ObservabilityManager({\n customCallbacks: options.callbacks,\n agentId: options.agentId,\n });\n this.callbacks = [];\n return;\n }\n\n // Validate requirements for local execution\n if (!options.llm) {\n throw new Error(\n \"llm is required for local execution. For remote execution, provide agentId instead.\"\n );\n }\n\n // Detect mode: simplified (string llm) vs explicit (object llm)\n const isSimplifiedMode = typeof options.llm === \"string\";\n\n if (isSimplifiedMode) {\n // Simplified mode: llm is string, mcpServers must be provided\n this.isSimplifiedMode = true;\n this.llmString = options.llm as string;\n this.llmConfig = (options as any).llmConfig;\n this.mcpServersConfig = (options as any).mcpServers;\n\n if (\n !this.mcpServersConfig ||\n Object.keys(this.mcpServersConfig).length === 0\n ) {\n throw new Error(\n \"Simplified mode requires 'mcpServers' configuration. \" +\n \"Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }\"\n );\n }\n\n // LLM and client will be created during initialize()\n this.llm = undefined;\n this.client = undefined;\n this.clientOwnedByAgent = true; // Mark for cleanup\n this.connectors = [];\n\n logger.debug(\n `🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`\n );\n } else {\n // Explicit mode: llm is object, client or connectors must be provided\n this.isSimplifiedMode = false;\n this.llm = options.llm as LanguageModel;\n this.client = (options as any).client;\n this.connectors = (options as any).connectors ?? [];\n this.clientOwnedByAgent = false;\n\n if (!this.client && this.connectors.length === 0) {\n throw new Error(\n \"Explicit mode requires either 'client' or at least one 'connector'. \" +\n \"Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.\"\n );\n }\n }\n\n // Common configuration for both modes\n this.maxSteps = options.maxSteps ?? 5;\n this.autoInitialize = options.autoInitialize ?? this.isSimplifiedMode;\n this.memoryEnabled = options.memoryEnabled ?? true;\n this.systemPrompt = options.systemPrompt ?? null;\n this.systemPromptTemplateOverride = options.systemPromptTemplate ?? null;\n this.additionalInstructions = options.additionalInstructions ?? null;\n this.disallowedTools = options.disallowedTools ?? [];\n this.additionalTools = options.additionalTools ?? [];\n this.toolsUsedNames = options.toolsUsedNames ?? [];\n this.exposeResourcesAsTools = options.exposeResourcesAsTools ?? true;\n this.exposePromptsAsTools = options.exposePromptsAsTools ?? true;\n this.useServerManager = options.useServerManager ?? false;\n this.verbose = options.verbose ?? false;\n this.observe = options.observe ?? true;\n\n // Set up adapter and server manager (only for explicit mode with client)\n if (!this.isSimplifiedMode) {\n if (this.useServerManager) {\n if (!this.client) {\n throw new Error(\n \"'client' must be provided when 'useServerManager' is true.\"\n );\n }\n this.adapter =\n options.adapter ?? new LangChainAdapter(this.disallowedTools);\n this.serverManager =\n options.serverManagerFactory?.(this.client) ??\n new ServerManager(this.client, this.adapter);\n } else {\n this.adapter =\n options.adapter ?? new LangChainAdapter(this.disallowedTools);\n }\n\n // Initialize telemetry for explicit mode\n this.telemetry = Telemetry.getInstance();\n if (this.llm) {\n const [provider, name] = extractModelInfo(this.llm as any);\n this.modelProvider = provider;\n this.modelName = name;\n } else {\n this.modelProvider = \"unknown\";\n this.modelName = \"unknown\";\n }\n } else {\n // For simplified mode, defer adapter/telemetry initialization\n this.adapter =\n options.adapter ?? new LangChainAdapter(this.disallowedTools);\n this.telemetry = Telemetry.getInstance();\n // Model info will be set during initialize()\n this.modelProvider = \"unknown\";\n this.modelName = \"unknown\";\n }\n\n // Set up observability callbacks using the ObservabilityManager\n this.observabilityManager = new ObservabilityManager({\n customCallbacks: options.callbacks,\n verbose: this.verbose,\n observe: this.observe,\n agentId: options.agentId,\n metadataProvider: () => this.getMetadata(),\n tagsProvider: () => this.getTags(),\n });\n\n // Make getters configurable for test mocking\n Object.defineProperty(this, \"agentExecutor\", {\n get: () => this._agentExecutor,\n configurable: true,\n });\n Object.defineProperty(this, \"tools\", {\n get: () => this._tools,\n configurable: true,\n });\n Object.defineProperty(this, \"initialized\", {\n get: () => this._initialized,\n configurable: true,\n });\n }\n\n /**\n * Creates configured clients and models, connects MCP servers, loads tools,\n * and builds the LangChain executor.\n *\n * @throws Error if a configured model or MCP server cannot be initialized.\n */\n public async initialize(): Promise<void> {\n // Skip initialization for remote agents\n if (this.isRemote) {\n this._initialized = true;\n return;\n }\n\n logger.debug(\"🚀 Initializing MCP agent and connecting to services...\");\n\n // Handle simplified mode: create client and LLM from configuration\n if (this.isSimplifiedMode) {\n logger.debug(\n \"🎯 Simplified mode: Creating client and LLM from configuration...\"\n );\n\n // Create MCPClient from mcpServers configuration\n if (this.mcpServersConfig) {\n logger.debug(\n `Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`\n );\n // Dynamically import MCPClient (Node.js version)\n const { MCPClient } = await import(\"@mcp-use/client\");\n this.client = new MCPClient({ mcpServers: this.mcpServersConfig });\n logger.debug(\"✅ MCPClient created successfully\");\n }\n\n // Create LLM from string specification\n if (this.llmString) {\n logger.debug(`Creating LLM from string: ${this.llmString}...`);\n try {\n this.llm = await createLLMFromString(this.llmString, this.llmConfig);\n logger.debug(\"✅ LLM created successfully\");\n\n // Update model info for telemetry\n const [provider, name] = extractModelInfo(this.llm as any);\n this.modelProvider = provider;\n this.modelName = name;\n } catch (error: any) {\n throw new Error(\n `Failed to create LLM from string '${this.llmString}': ${error?.message || error}`\n );\n }\n }\n\n // Set up server manager if needed\n if (this.useServerManager) {\n if (!this.client) {\n throw new Error(\n \"'client' must be available when 'useServerManager' is true.\"\n );\n }\n this.serverManager = new ServerManager(this.client, this.adapter);\n }\n }\n\n // Initialize observability callbacks\n this.callbacks = await this.observabilityManager.getCallbacks();\n const handlerNames = await this.observabilityManager.getHandlerNames();\n if (handlerNames.length > 0) {\n logger.debug(`📊 Observability enabled with: ${handlerNames.join(\", \")}`);\n }\n\n // If using server manager, initialize it\n if (this.useServerManager && this.serverManager) {\n await this.serverManager.initialize();\n\n // Get server management tools\n const managementTools = this.serverManager.tools;\n this._tools = managementTools;\n this._tools.push(...this.additionalTools);\n logger.debug(\n `🔧 Server manager mode active with ${managementTools.length} management tools`\n );\n\n // Create the system message based on available tools\n await this.createSystemMessageFromTools(this._tools);\n } else {\n // Standard initialization - if using client, get or create sessions\n if (this.client) {\n // First try to get existing sessions\n this.sessions = this.client.getAllActiveSessions();\n logger.debug(\n `🔌 Found ${Object.keys(this.sessions).length} existing sessions`\n );\n\n // Filter out internal code_mode session to check if real MCP servers are connected\n const nonCodeModeSessions = Object.keys(this.sessions).filter(\n (name) => name !== \"code_mode\"\n );\n\n // If no active sessions exist (excluding code_mode), create new ones\n if (nonCodeModeSessions.length === 0) {\n logger.debug(\"🔄 No active sessions found, creating new ones...\");\n this.sessions = await this.client.createAllSessions();\n logger.debug(\n `✅ Created ${Object.keys(this.sessions).length} new sessions`\n );\n }\n\n // Create LangChain tools directly from the client using the adapter\n // In code mode, only expose the code_mode tools (execute_code, search_tools)\n if ((this.client as { codeMode?: boolean }).codeMode) {\n const codeModeSession = this.sessions[\"code_mode\"];\n if (codeModeSession) {\n // Code mode only uses tools, not resources or prompts\n this._tools = await this.adapter.createToolsFromConnectors([\n codeModeSession.connector,\n ]);\n logger.debug(`🛠️ Created ${this._tools.length} code mode tools`);\n } else {\n throw new Error(\n \"Code mode enabled but code_mode session not found\"\n );\n }\n } else {\n // Create tools from the client; resources and prompts are optional\n const connectors = Object.values(this.sessions).map(\n (session) => session.connector\n );\n const tools =\n await this.adapter.createToolsFromConnectors(connectors);\n const resources = this.exposeResourcesAsTools\n ? await this.adapter.createResourcesFromConnectors(connectors)\n : [];\n const prompts = this.exposePromptsAsTools\n ? await this.adapter.createPromptsFromConnectors(connectors)\n : [];\n this._tools = [...tools, ...resources, ...prompts];\n logger.debug(\n `🛠️ Created ${this._tools.length} LangChain items from client: ` +\n `${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`\n );\n }\n this._tools.push(...this.additionalTools);\n } else {\n // Using direct connector - only establish connection\n logger.debug(\n `🔗 Connecting to ${this.connectors.length} direct connectors...`\n );\n for (const connector of this.connectors) {\n if (!connector.isClientConnected) {\n await connector.connect();\n }\n }\n\n // Create LangChain tools, resources, and prompts using the adapter with connectors\n const tools = await this.adapter.createToolsFromConnectors(\n this.connectors\n );\n const resources = await this.adapter.createResourcesFromConnectors(\n this.connectors\n );\n const prompts = await this.adapter.createPromptsFromConnectors(\n this.connectors\n );\n this._tools = [...tools, ...resources, ...prompts];\n this._tools.push(...this.additionalTools);\n logger.debug(\n `🛠️ Created ${this._tools.length} LangChain items from connectors: ` +\n `${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`\n );\n }\n\n // Get all tools for system message generation\n logger.debug(\n `🧰 Found ${this._tools.length} tools across all connectors`\n );\n\n // Create the system message based on available tools\n await this.createSystemMessageFromTools(this._tools);\n }\n\n // Create the agent executor and mark initialized\n this._agentExecutor = this.createAgent();\n this._initialized = true;\n\n // Add MCP server information to observability metadata\n const mcpServerInfo = this.getMCPServerInfo();\n if (Object.keys(mcpServerInfo).length > 0) {\n this.setMetadata(mcpServerInfo);\n logger.debug(\n `MCP server info added to metadata: ${JSON.stringify(mcpServerInfo)}`\n );\n }\n\n logger.debug(\"✨ Agent initialization complete\");\n }\n\n private async createSystemMessageFromTools(\n tools: StructuredToolInterface[]\n ): Promise<void> {\n const systemPromptTemplate =\n this.systemPromptTemplateOverride ?? DEFAULT_SYSTEM_PROMPT_TEMPLATE;\n\n this.systemMessage = createSystemMessage(\n tools,\n systemPromptTemplate,\n SERVER_MANAGER_SYSTEM_PROMPT_TEMPLATE,\n this.useServerManager,\n this.disallowedTools,\n this.systemPrompt ?? undefined,\n this.additionalInstructions ?? undefined\n );\n\n if (this.memoryEnabled) {\n this.conversationHistory = [\n this.systemMessage,\n ...this.conversationHistory.filter(\n (m) => !(m instanceof SystemMessage)\n ),\n ];\n }\n }\n\n private createAgent(): ReactAgent {\n if (!this.llm) {\n throw new Error(\"LLM is required to create agent\");\n }\n\n const systemContent =\n (this.systemMessage?.content as string) ?? \"You are a helpful assistant.\";\n\n const toolNames = this._tools.map((tool) => tool.name);\n logger.debug(`🧠 Agent ready with tools: ${toolNames.join(\", \")}`);\n\n // Create middleware to enforce max_steps\n // modelCallLimitMiddleware limits the number of model calls, which corresponds to agent steps\n const middleware = [modelCallLimitMiddleware({ runLimit: this.maxSteps })];\n\n const agent = createAgent({\n model: this.llm,\n tools: this._tools as any,\n systemPrompt: systemContent,\n middleware,\n });\n\n logger.debug(\n `Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`\n );\n\n return agent;\n }\n\n /** @returns A shallow copy of the stored LangChain message history. */\n public getConversationHistory(): BaseMessage[] {\n return [...this.conversationHistory];\n }\n\n /** Clears stored history, retaining the system message when memory is enabled. */\n public clearConversationHistory(): void {\n this.conversationHistory =\n this.memoryEnabled && this.systemMessage ? [this.systemMessage] : [];\n }\n\n private addToHistory(message: BaseMessage): void {\n if (this.memoryEnabled) this.conversationHistory.push(message);\n }\n\n /** @returns The current LangChain system message, or `null` before creation. */\n public getSystemMessage(): SystemMessage | null {\n return this.systemMessage;\n }\n\n /**\n * Replaces the system instruction and rebuilds an initialized executor.\n *\n * @param message - New system instruction.\n */\n public setSystemMessage(message: string): void {\n this.systemMessage = new SystemMessage(message);\n if (this.memoryEnabled) {\n this.conversationHistory = this.conversationHistory.filter(\n (m) => !(m instanceof SystemMessage)\n );\n this.conversationHistory.unshift(this.systemMessage);\n }\n\n if (this._initialized && this._tools.length) {\n this._agentExecutor = this.createAgent();\n logger.debug(\"Agent recreated with new system message\");\n }\n }\n\n /**\n * Replaces the tool denylist for the next initialization.\n *\n * @param disallowedTools - MCP tool names to omit.\n */\n public setDisallowedTools(disallowedTools: string[]): void {\n this.disallowedTools = disallowedTools;\n this.adapter = new LangChainAdapter(this.disallowedTools);\n if (this._initialized) {\n logger.debug(\n \"Agent already initialized. Changes will take effect on next initialization.\"\n );\n }\n }\n\n /** @returns The configured MCP tool denylist. */\n public getDisallowedTools(): string[] {\n return this.disallowedTools;\n }\n\n /**\n * Set metadata for observability traces\n * @param newMetadata - Key-value pairs to add to metadata. Keys should be strings, values should be serializable.\n */\n public setMetadata(newMetadata: Record<string, any>): void {\n // Validate and sanitize metadata\n const sanitizedMetadata = this.sanitizeMetadata(newMetadata);\n\n // Merge with existing metadata instead of replacing it\n this.metadata = { ...this.metadata, ...sanitizedMetadata };\n logger.debug(`Metadata set: ${JSON.stringify(this.metadata)}`);\n }\n\n /**\n * Get current metadata\n * @returns A copy of the current metadata object\n */\n public getMetadata(): Record<string, any> {\n return { ...this.metadata };\n }\n\n /**\n * Set tags for observability traces\n * @param newTags - Array of tag strings to add. Duplicates will be automatically removed.\n */\n public setTags(newTags: string[]): void {\n // Validate and sanitize tags\n const sanitizedTags = this.sanitizeTags(newTags);\n this.tags = [...new Set([...this.tags, ...sanitizedTags])]; // Remove duplicates\n logger.debug(`Tags set: ${JSON.stringify(this.tags)}`);\n }\n\n /**\n * Get current tags\n * @returns A copy of the current tags array\n */\n public getTags(): string[] {\n return [...this.tags];\n }\n\n /**\n * Sanitize metadata to ensure compatibility with observability platforms\n * @param metadata - Raw metadata object\n * @returns Sanitized metadata object\n */\n private sanitizeMetadata(metadata: Record<string, any>): Record<string, any> {\n const sanitized: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(metadata)) {\n // Validate key\n if (typeof key !== \"string\" || key.length === 0) {\n logger.warn(`Invalid metadata key: ${key}. Skipping.`);\n continue;\n }\n\n // Sanitize key (remove special characters that might cause issues)\n const sanitizedKey = key.replace(/[^\\w-]/g, \"_\");\n\n // Validate and sanitize value\n if (value === null || value === undefined) {\n sanitized[sanitizedKey] = value;\n } else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n sanitized[sanitizedKey] = value;\n } else if (Array.isArray(value)) {\n // Only allow arrays of primitives\n const sanitizedArray = value.filter(\n (item) =>\n typeof item === \"string\" ||\n typeof item === \"number\" ||\n typeof item === \"boolean\"\n );\n if (sanitizedArray.length > 0) {\n sanitized[sanitizedKey] = sanitizedArray;\n }\n } else if (typeof value === \"object\") {\n // Try to serialize objects, but limit depth to prevent circular references\n try {\n const serialized = JSON.stringify(value);\n if (serialized.length > 1000) {\n logger.warn(\n `Metadata value for key '${sanitizedKey}' is too large. Truncating.`\n );\n sanitized[sanitizedKey] = `${serialized.substring(0, 1000)}...`;\n } else {\n sanitized[sanitizedKey] = value;\n }\n } catch (error) {\n logger.warn(\n `Failed to serialize metadata value for key '${sanitizedKey}': ${error}. Skipping.`\n );\n }\n } else {\n logger.warn(\n `Unsupported metadata value type for key '${sanitizedKey}': ${typeof value}. Skipping.`\n );\n }\n }\n\n return sanitized;\n }\n\n /**\n * Sanitize tags to ensure compatibility with observability platforms\n * @param tags - Array of tag strings\n * @returns Array of sanitized tag strings\n */\n private sanitizeTags(tags: string[]): string[] {\n return tags\n .filter((tag) => typeof tag === \"string\" && tag.length > 0)\n .map((tag) => tag.replace(/[^\\w:-]/g, \"_\"))\n .filter((tag) => tag.length <= 50); // Limit tag length\n }\n\n /**\n * Get MCP server information for observability metadata\n */\n private getMCPServerInfo(): Record<string, any> {\n const serverInfo: Record<string, any> = {};\n\n try {\n if (this.client) {\n const serverNames = this.client.getServerNames();\n serverInfo.mcp_servers_count = serverNames.length;\n serverInfo.mcp_server_names = serverNames;\n\n // Get server types and configurations\n const serverConfigs: Record<string, any> = {};\n for (const serverName of serverNames) {\n try {\n const config = this.client.getServerConfig(serverName);\n if (config) {\n // Determine server type based on configuration\n const isStdio = \"command\" in config;\n const serverType = isStdio ? \"command\" : \"http\";\n\n serverConfigs[serverName] = {\n type: serverType,\n // Include safe configuration details (avoid sensitive data)\n has_args: isStdio && !!config.args,\n has_env: isStdio && !!config.env,\n has_headers: !isStdio && !!config.headers,\n url: isStdio ? null : config.url,\n command: isStdio ? config.command : null,\n };\n }\n } catch (error) {\n logger.warn(\n `Failed to get config for server '${serverName}': ${error}`\n );\n serverConfigs[serverName] = {\n type: \"error\",\n error: \"config_unavailable\",\n };\n }\n }\n serverInfo.mcp_server_configs = serverConfigs;\n } else if (this.connectors && this.connectors.length > 0) {\n // Handle direct connectors\n serverInfo.mcp_servers_count = this.connectors.length;\n serverInfo.mcp_server_names = this.connectors.map(\n (c) => c.publicIdentifier\n );\n serverInfo.mcp_server_types = this.connectors.map(\n (c) => c.constructor.name\n );\n }\n } catch (error) {\n logger.warn(`Failed to collect MCP server info: ${error}`);\n serverInfo.error = \"collection_failed\";\n }\n\n return serverInfo;\n }\n\n private _normalizeOutput(value: any): string {\n /**\n * Normalize model outputs into a plain text string.\n * Similar to Python's _normalize_output method.\n */\n try {\n if (typeof value === \"string\") {\n return value;\n }\n\n // LangChain messages may have .content which is str or list-like\n if (value && typeof value === \"object\" && \"content\" in value) {\n return this._normalizeOutput(value.content);\n }\n\n if (Array.isArray(value)) {\n const parts: string[] = [];\n for (const item of value) {\n if (typeof item === \"object\" && item !== null) {\n if (\"text\" in item && typeof item.text === \"string\") {\n parts.push(item.text);\n } else if (\"content\" in item) {\n parts.push(this._normalizeOutput(item.content));\n } else {\n // Fallback to string for unknown shapes\n parts.push(String(item));\n }\n } else {\n // recurse on .text or str\n const partText =\n item && typeof item === \"object\" && \"text\" in item\n ? item.text\n : null;\n if (typeof partText === \"string\") {\n parts.push(partText);\n } else {\n const partContent =\n item && typeof item === \"object\" && \"content\" in item\n ? item.content\n : item;\n parts.push(this._normalizeOutput(partContent));\n }\n }\n }\n return parts.join(\"\");\n }\n\n return String(value);\n } catch (error) {\n return String(value);\n }\n }\n\n /**\n * Check if a message is AI/assistant-like regardless of whether it's a class instance.\n * Handles version mismatches, serialization boundaries, and different message formats.\n *\n * This method solves the issue where messages from LangChain agents may be plain JavaScript\n * objects (e.g., `{ type: 'ai', content: '...' }`) instead of AIMessage instances due to\n * serialization/deserialization across module boundaries or version mismatches.\n *\n * @example\n * ```ts\n * // Real AIMessage instance (standard case).\n * _isAIMessageLike(new AIMessage(\"hello\")); // true\n * ```\n *\n * @example\n * ```ts\n * // Plain object after serialization (fixes issue #446).\n * _isAIMessageLike({ type: \"ai\", content: \"hello\" }); // true\n * ```\n *\n * @example\n * ```ts\n * // OpenAI-style format with role.\n * _isAIMessageLike({ role: \"assistant\", content: \"hello\" }); // true\n * ```\n *\n * @example\n * ```ts\n * // Object with getType() method.\n * _isAIMessageLike({ getType: () => \"ai\", content: \"hello\" }); // true\n * ```\n *\n * @param message - The message object to check\n * @returns true if the message represents an AI/assistant message\n */\n private _isAIMessageLike(message: unknown): message is\n | AIMessage\n | {\n type: \"ai\" | \"assistant\";\n content?: unknown;\n tool_calls?: unknown;\n }\n | {\n role: \"ai\" | \"assistant\";\n content?: unknown;\n tool_calls?: unknown;\n } {\n // Fast path: check if it's an actual AIMessage instance\n if (message instanceof AIMessage) {\n return true;\n }\n\n // Relaxed check: just need to be an object (content is optional as messages might only have tool_calls)\n if (typeof message !== \"object\" || message === null) {\n return false;\n }\n\n // Check for type/role properties that indicate an assistant message\n // Support multiple formats from different LangChain versions\n const msg = message as any;\n\n // Try methods first (for partially deserialized objects)\n if (typeof msg.getType === \"function\") {\n try {\n const type = msg.getType();\n if (type === \"ai\" || type === \"assistant\") {\n return true;\n }\n } catch (error) {\n // If getType() throws, fall through to other checks\n // Note: Silent failure here to avoid performance impact in hot path\n }\n }\n if (typeof msg._getType === \"function\") {\n try {\n const type = msg._getType();\n if (type === \"ai\" || type === \"assistant\") {\n return true;\n }\n } catch (error) {\n // If _getType() throws, fall through to other checks\n // Note: Silent failure here to avoid performance impact in hot path\n }\n }\n\n // Check direct properties\n if (\"type\" in msg) {\n return msg.type === \"ai\" || msg.type === \"assistant\";\n }\n if (\"role\" in msg) {\n return msg.role === \"ai\" || msg.role === \"assistant\";\n }\n\n return false;\n }\n\n /**\n * Check if a message has tool calls, handling both class instances and plain objects.\n * Safely checks for tool_calls array presence.\n *\n * @example\n * ```ts\n * const message = new AIMessage({\n * content: \"\",\n * tool_calls: [{ name: \"add\", args: {} }],\n * });\n * _messageHasToolCalls(message); // true\n * ```\n *\n * @example\n * ```ts\n * _messageHasToolCalls({\n * type: \"ai\",\n * tool_calls: [{ name: \"add\" }],\n * }); // true\n * ```\n *\n * @example\n * ```ts\n * _messageHasToolCalls({ type: \"ai\", content: \"hello\" }); // false\n * ```\n *\n * @param message - The message object to check\n * @returns true if the message has non-empty tool_calls array\n */\n private _messageHasToolCalls(message: unknown): boolean {\n if (\n typeof message === \"object\" &&\n message !== null &&\n \"tool_calls\" in message &&\n Array.isArray((message as { tool_calls?: unknown }).tool_calls)\n ) {\n return (message as { tool_calls: unknown[] }).tool_calls.length > 0;\n }\n\n return false;\n }\n\n /**\n * Check if a message is a HumanMessage-like object.\n * Handles both class instances and plain objects from serialization.\n *\n * @example\n * ```ts\n * _isHumanMessageLike(new HumanMessage(\"hello\")); // true\n * _isHumanMessageLike({ type: \"human\", content: \"hello\" }); // true\n * ```\n *\n * @param message - The message object to check\n * @returns true if the message represents a human message\n */\n private _isHumanMessageLike(message: unknown): boolean {\n if (message instanceof HumanMessage) {\n return true;\n }\n if (typeof message !== \"object\" || message === null) {\n return false;\n }\n const msg = message as any;\n\n // Try methods first\n if (typeof msg.getType === \"function\") {\n try {\n const type = msg.getType();\n if (type === \"human\" || type === \"user\") {\n return true;\n }\n } catch (error) {\n // Silent failure for performance\n }\n }\n\n // Check direct properties\n if (\"type\" in msg && (msg.type === \"human\" || msg.type === \"user\")) {\n return true;\n }\n if (\"role\" in msg && (msg.role === \"human\" || msg.role === \"user\")) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if a message is a ToolMessage-like object.\n * Handles both class instances and plain objects from serialization.\n *\n * @example\n * ```ts\n * const message = new ToolMessage({\n * content: \"result\",\n * tool_call_id: \"123\",\n * });\n * _isToolMessageLike(message); // true\n * _isToolMessageLike({ type: \"tool\", content: \"result\" }); // true\n * ```\n *\n * @param message - The message object to check\n * @returns true if the message represents a tool message\n */\n private _isToolMessageLike(message: unknown): boolean {\n if (message instanceof ToolMessage) {\n return true;\n }\n if (typeof message !== \"object\" || message === null) {\n return false;\n }\n const msg = message as any;\n\n // Try methods first\n if (typeof msg.getType === \"function\") {\n try {\n const type = msg.getType();\n if (type === \"tool\") {\n return true;\n }\n } catch (error) {\n // Silent failure for performance\n }\n }\n\n // Check direct properties\n if (\"type\" in msg && msg.type === \"tool\") {\n return true;\n }\n\n return false;\n }\n\n /**\n * Extract content from a message, handling both AIMessage instances and plain objects.\n *\n * @example\n * ```ts\n * _getMessageContent(new AIMessage(\"hello\")); // \"hello\"\n * ```\n *\n * @example\n * ```ts\n * _getMessageContent({ type: \"ai\", content: \"hello\" }); // \"hello\"\n * ```\n *\n * @param message - The message object to extract content from\n * @returns The content of the message, or undefined if not present\n */\n private _getMessageContent(message: unknown): unknown {\n if (message instanceof AIMessage) {\n return message.content;\n }\n if (message && typeof message === \"object\" && \"content\" in message) {\n return (message as { content: unknown }).content;\n }\n return undefined;\n }\n\n private async _consumeAndReturn<T>(\n generator: AsyncGenerator<AgentStep, string | T, void>\n ): Promise<string | T> {\n // Manually iterate through the generator to consume the steps.\n // The for-await-of loop is not used because it discards the generator's\n // final return value. We need to capture that value when `done` is true.\n while (true) {\n const { done, value } = await generator.next();\n if (done) {\n return value;\n }\n }\n }\n\n /**\n * Runs the agent with options object and returns a promise for the final result.\n */\n public async run(options: RunOptions): Promise<string>;\n\n /**\n * Runs the agent with options object and structured output, returns a promise for the typed result.\n */\n public async run<T>(options: RunOptions<T>): Promise<T>;\n\n /**\n * Runs the agent and returns a promise for the final result.\n * @deprecated Use the options object instead: `run({ prompt, maxSteps, ... })`.\n */\n public async run(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: undefined,\n signal?: AbortSignal\n ): Promise<string>;\n\n /**\n * Runs the agent with structured output and returns a promise for the typed result.\n * @deprecated Use the options object instead: `run({ prompt, schema, maxSteps, ... })`.\n */\n public async run<T>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): Promise<T>;\n\n public async run<T>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): Promise<string | T> {\n // Normalize input to internal parameters\n const {\n query,\n maxSteps: steps,\n manageConnector: manage,\n externalHistory: history,\n outputSchema: schema,\n signal: abortSignal,\n } = normalizeRunOptions(\n queryOrOptions,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n signal\n );\n\n // Delegate to remote agent if in remote mode\n if (this.isRemote && this.remoteAgent) {\n return this.remoteAgent.run(query, steps, manage, history, schema);\n }\n\n const generator = this.stream<T>(\n query,\n steps,\n manage,\n history,\n schema,\n abortSignal\n );\n return this._consumeAndReturn(generator);\n }\n\n /**\n * Streams the agent execution with options object and returns string result.\n */\n public stream(options: RunOptions): AsyncGenerator<AgentStep, string, void>;\n\n /**\n * Streams the agent execution with options object and structured output.\n */\n public stream<T>(options: RunOptions<T>): AsyncGenerator<AgentStep, T, void>;\n\n /**\n * Streams the agent execution and yields agent steps.\n * @deprecated Use the options object instead: `stream({ prompt, maxSteps, ... })`.\n */\n public stream<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): AsyncGenerator<AgentStep, string | T, void>;\n\n public async *stream<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector = true,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): AsyncGenerator<AgentStep, string | T, void> {\n // Normalize input to internal parameters\n const {\n query,\n maxSteps: steps,\n manageConnector: manage,\n externalHistory: history,\n outputSchema: schema,\n signal: abortSignal,\n } = normalizeRunOptions(\n queryOrOptions,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n signal\n );\n\n // Delegate to remote agent if in remote mode\n if (this.isRemote && this.remoteAgent) {\n const result = await this.remoteAgent.run(\n query,\n steps,\n manage,\n history,\n schema\n );\n return result as string | T;\n }\n\n let initializedHere = false;\n const startTime = Date.now();\n let success = false;\n let finalOutput: string | null = null;\n let stepsTaken = 0;\n\n try {\n // 1. Initialize if needed\n if (manage && !this._initialized) {\n await this.initialize();\n initializedHere = true;\n } else if (!this._initialized && this.autoInitialize) {\n await this.initialize();\n initializedHere = true;\n }\n\n if (!this._agentExecutor) {\n throw new Error(\"MCP agent failed to initialize\");\n }\n\n // Check for tool updates before starting execution (if using server manager)\n if (this.useServerManager && this.serverManager) {\n const currentTools = this.serverManager.tools;\n const currentToolNames = new Set(currentTools.map((t) => t.name));\n const existingToolNames = new Set(this._tools.map((t) => t.name));\n\n if (\n currentToolNames.size !== existingToolNames.size ||\n [...currentToolNames].some((n) => !existingToolNames.has(n))\n ) {\n logger.debug(\n `🔄 Tools changed before execution, updating agent. New tools: ${[...currentToolNames].join(\", \")}`\n );\n this._tools = currentTools;\n this._tools.push(...this.additionalTools);\n // Regenerate system message with ALL current tools\n await this.createSystemMessageFromTools(this._tools);\n // Recreate the agent executor with the new tools and system message\n this._agentExecutor = this.createAgent();\n }\n }\n\n // 2. Build inputs for the agent\n const historyToUse = history ?? this.conversationHistory;\n\n // Convert messages to format expected by LangChain agent\n const langchainHistory: BaseMessage[] = [];\n for (const msg of historyToUse) {\n if (\n this._isHumanMessageLike(msg) ||\n this._isAIMessageLike(msg) ||\n this._isToolMessageLike(msg)\n ) {\n langchainHistory.push(msg);\n }\n }\n\n const displayQuery =\n query.length > 50\n ? `${query.slice(0, 50).replace(/\\n/g, \" \")}...`\n : query.replace(/\\n/g, \" \");\n logger.debug(`💬 Received query: '${displayQuery}'`);\n logger.debug(\"🏁 Starting agent execution\");\n\n // 3. Stream using the built-in astream from CompiledStateGraph\n // The agent graph handles the loop internally\n // With dynamic tool reload: if tools change mid-execution, we interrupt and restart\n const maxRestarts = 3; // Prevent infinite restart loops\n let restartCount = 0;\n const accumulatedMessages: BaseMessage[] = [\n ...langchainHistory,\n new HumanMessage(query),\n ];\n\n while (restartCount <= maxRestarts) {\n // Update inputs with accumulated messages\n const inputs = { messages: accumulatedMessages };\n let shouldRestart = false;\n\n // Stream agent updates with observability callbacks\n const stream = await this._agentExecutor.stream(inputs, {\n streamMode: \"updates\", // Get updates as they happen\n callbacks: this.callbacks,\n metadata: this.getMetadata(),\n tags: this.getTags(),\n // Set trace name for LangChain/Langfuse\n runName: this.metadata.trace_name || \"mcp-use-agent\",\n // Set recursion limit to 3x maxSteps to account for model calls + tool executions\n recursionLimit: this.maxSteps * 3,\n // Pass sessionId for Langfuse if present in metadata\n ...(this.metadata.session_id && {\n sessionId: this.metadata.session_id,\n }),\n // Pass abort signal if provided\n ...(abortSignal && { signal: abortSignal }),\n });\n\n for await (const chunk of stream) {\n // Check for abort\n if (abortSignal?.aborted) {\n break;\n }\n\n // chunk is a dict with node names as keys\n // The agent node will have 'messages' with the AI response\n // The tools node will have 'messages' with tool calls and results\n\n for (const [nodeName, nodeOutput] of Object.entries(chunk)) {\n logger.debug(\n `📦 Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`\n );\n\n // Extract messages from the node output and accumulate them\n if (\n nodeOutput &&\n typeof nodeOutput === \"object\" &&\n \"messages\" in nodeOutput\n ) {\n let messages = (nodeOutput as any).messages;\n if (!Array.isArray(messages)) {\n messages = [messages];\n }\n\n // Add new messages to accumulated messages for potential restart\n for (const msg of messages) {\n if (!accumulatedMessages.includes(msg)) {\n accumulatedMessages.push(msg);\n }\n }\n\n for (const message of messages) {\n // Track tool calls\n if (\n \"tool_calls\" in message &&\n Array.isArray(message.tool_calls) &&\n message.tool_calls.length > 0\n ) {\n for (const toolCall of message.tool_calls) {\n const toolName = toolCall.name || \"unknown\";\n const toolInput = toolCall.args || {};\n this.toolsUsedNames.push(toolName);\n stepsTaken++;\n\n let toolInputStr = JSON.stringify(toolInput);\n if (toolInputStr.length > 100) {\n toolInputStr = `${toolInputStr.slice(0, 97)}...`;\n }\n logger.debug(\n `🔧 Tool call: ${toolName} with input: ${toolInputStr}`\n );\n\n // Yield tool call as AgentStep\n yield {\n action: {\n tool: toolName,\n toolInput,\n log: `Calling tool ${toolName}`,\n },\n observation: \"\", // Will be filled in by tool result\n };\n }\n }\n\n // Track tool results (ToolMessage)\n if (this._isToolMessageLike(message)) {\n const observation = message.content;\n let observationStr = String(observation);\n if (observationStr.length > 100) {\n observationStr = `${observationStr.slice(0, 97)}...`;\n }\n observationStr = observationStr.replace(/\\n/g, \" \");\n logger.debug(`📄 Tool result: ${observationStr}`);\n\n // --- Check for tool updates after tool results (safe restart point) ---\n if (this.useServerManager && this.serverManager) {\n const currentTools = this.serverManager.tools;\n const currentToolNames = new Set(\n currentTools.map((t) => t.name)\n );\n const existingToolNames = new Set(\n this._tools.map((t) => t.name)\n );\n\n if (\n currentToolNames.size !== existingToolNames.size ||\n [...currentToolNames].some(\n (n) => !existingToolNames.has(n)\n )\n ) {\n logger.debug(\n `🔄 Tools changed during execution. New tools: ${[...currentToolNames].join(\", \")}`\n );\n this._tools = currentTools;\n this._tools.push(...this.additionalTools);\n // Regenerate system message with ALL current tools\n await this.createSystemMessageFromTools(this._tools);\n // Recreate the agent executor with the new tools and system message\n this._agentExecutor = this.createAgent();\n\n // Set restart flag - safe to restart now after tool results\n shouldRestart = true;\n restartCount++;\n logger.debug(\n `🔃 Restarting execution with updated tools (restart ${restartCount}/${maxRestarts})`\n );\n break; // Break out of the message loop\n }\n }\n }\n\n // Track final AI message (without tool calls = final response)\n if (\n this._isAIMessageLike(message) &&\n !this._messageHasToolCalls(message)\n ) {\n finalOutput = this._normalizeOutput(\n this._getMessageContent(message)\n );\n logger.debug(\"✅ Agent finished with output\");\n }\n }\n\n // Break out of node loop if restarting\n if (shouldRestart) {\n break;\n }\n }\n }\n\n // Break out of chunk loop if restarting\n if (shouldRestart) {\n break;\n }\n }\n\n // Check if we should restart or if execution completed\n if (!shouldRestart) {\n // Execution completed successfully without tool changes\n break;\n }\n\n // If we've hit max restarts, log warning and continue\n if (restartCount > maxRestarts) {\n logger.warn(\n `⚠️ Max restarts (${maxRestarts}) reached. Continuing with current tools.`\n );\n break;\n }\n }\n\n // 4. Update conversation history\n if (this.memoryEnabled) {\n // Store all messages from execution (including tool calls and tool outputs)\n // Extract messages from current execution (skip the messages that were already in history)\n const newMessages = accumulatedMessages.slice(langchainHistory.length);\n for (const msg of newMessages) {\n this.addToHistory(msg);\n }\n }\n\n // 5. Handle structured output if requested\n if (schema && finalOutput) {\n try {\n logger.debug(\"🔧 Attempting structured output...\");\n const structuredResult = await this._attemptStructuredOutput<T>(\n finalOutput,\n this.llm!,\n schema\n );\n\n if (this.memoryEnabled) {\n this.addToHistory(\n new AIMessage(\n `Structured result: ${JSON.stringify(structuredResult)}`\n )\n );\n }\n\n logger.debug(\"✅ Structured output successful\");\n success = true;\n return structuredResult;\n } catch (e) {\n logger.error(`❌ Structured output failed: ${e}`);\n throw new Error(\n `Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n\n // 6. Yield final result\n logger.debug(\n `🎉 Agent execution complete in ${((Date.now() - startTime) / 1000).toFixed(2)} seconds`\n );\n success = true;\n return (finalOutput || \"No output generated\") as string | T;\n } catch (e) {\n logger.error(`❌ Error running query: ${e}`);\n if (initializedHere && manage) {\n logger.debug(\"🧹 Cleaning up resources after error\");\n await this.close();\n }\n throw e;\n } finally {\n // Track comprehensive execution data\n const executionTimeMs = Date.now() - startTime;\n\n let serverCount = 0;\n if (this.client) {\n serverCount = Object.keys(this.client.getAllActiveSessions()).length;\n } else if (this.connectors) {\n serverCount = this.connectors.length;\n }\n\n const conversationHistoryLength = this.memoryEnabled\n ? this.conversationHistory.length\n : 0;\n\n // Safely access _tools in case initialization failed\n const toolsAvailable = this._tools || [];\n\n await this.telemetry.trackAgentExecution({\n executionMethod: \"stream\",\n query,\n success,\n modelProvider: this.modelProvider,\n modelName: this.modelName,\n serverCount,\n serverIdentifiers: this.connectors.map(\n (connector) => connector.publicIdentifier\n ),\n totalToolsAvailable: toolsAvailable.length,\n toolsAvailableNames: toolsAvailable.map((t) => t.name),\n maxStepsConfigured: this.maxSteps,\n memoryEnabled: this.memoryEnabled,\n useServerManager: this.useServerManager,\n maxStepsUsed: steps ?? null,\n manageConnector: manage ?? true,\n externalHistoryUsed: history !== undefined,\n stepsTaken,\n toolsUsedCount: this.toolsUsedNames.length,\n toolsUsedNames: this.toolsUsedNames,\n response: finalOutput || \"\",\n executionTimeMs,\n errorType: success ? null : \"execution_error\",\n conversationHistoryLength,\n });\n\n // Clean up if necessary\n if (manage && !this.client && initializedHere) {\n logger.debug(\"🧹 Closing agent after stream completion\");\n await this.close();\n }\n }\n }\n /**\n * Flush observability traces to the configured observability platform.\n * Important for serverless environments where traces need to be sent before function termination.\n */\n public async flush(): Promise<void> {\n // Delegate to remote agent if in remote mode\n if (this.isRemote && this.remoteAgent) {\n // Remote agents don't have observability manager\n return;\n }\n\n logger.debug(\"Flushing observability traces...\");\n await this.observabilityManager.flush();\n }\n\n /**\n * Flushes observability, closes owned MCP resources, and resets the executor.\n */\n public async close(): Promise<void> {\n // Delegate to remote agent if in remote mode\n if (this.isRemote && this.remoteAgent) {\n await this.remoteAgent.close();\n return;\n }\n\n logger.debug(\"🔌 Closing MCPAgent resources…\");\n\n // Shutdown observability handlers (important for serverless)\n await this.observabilityManager.shutdown();\n try {\n this._agentExecutor = null;\n this._tools = [];\n\n // Clean up client (always close if we own it, or if it exists in explicit mode)\n if (this.client) {\n // In simplified mode, we always own the client and should close it\n // In explicit mode, we only close if explicitly requested (current behavior)\n if (this.clientOwnedByAgent) {\n logger.debug(\n \"🔄 Closing internally-created client (simplified mode) and cleaning up resources\"\n );\n await this.client.close();\n this.sessions = {};\n this.client = undefined;\n } else {\n logger.debug(\"🔄 Closing client and cleaning up resources\");\n await this.client.close();\n this.sessions = {};\n }\n } else {\n for (const connector of this.connectors) {\n logger.debug(\"🔄 Disconnecting connector\");\n await connector.disconnect();\n }\n }\n\n // Clean up LLM reference (important for simplified mode)\n if (this.isSimplifiedMode && this.llm) {\n logger.debug(\"🔄 Clearing LLM reference (simplified mode)\");\n this.llm = undefined;\n }\n\n if (\"connectorToolMap\" in this.adapter) {\n this.adapter = new LangChainAdapter();\n }\n } finally {\n this._initialized = false;\n logger.debug(\"👋 Agent closed successfully\");\n }\n }\n\n /**\n * Yields with pretty-printed output for code mode with options object.\n */\n public prettyStreamEvents(\n options: RunOptions\n ): AsyncGenerator<void, string, void>;\n\n /**\n * Yields with pretty-printed output for code mode with options object and structured output.\n */\n public prettyStreamEvents<T>(\n options: RunOptions<T>\n ): AsyncGenerator<void, string, void>;\n\n /**\n * Yields with pretty-printed output for code mode.\n * This method formats and displays tool executions in a user-friendly way for the terminal.\n * @deprecated Use the options object instead: `prettyStreamEvents({ prompt, maxSteps, ... })`.\n */\n public prettyStreamEvents<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): AsyncGenerator<void, string, void>;\n\n public async *prettyStreamEvents<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector = true,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): AsyncGenerator<void, string, void> {\n const { prettyStreamEvents: prettyStream } = await import(\"./display.js\");\n\n const finalResponse = \"\";\n\n for await (const _ of prettyStream(\n this.streamEvents(\n queryOrOptions as any,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema\n )\n )) {\n yield;\n }\n\n return finalResponse;\n }\n\n /**\n * Yields LangChain StreamEvent objects with options object.\n */\n public streamEvents(\n options: RunOptions\n ): AsyncGenerator<StreamEvent, void, void>;\n\n /**\n * Yields LangChain StreamEvent objects with options object and structured output.\n */\n public streamEvents<T>(\n options: RunOptions<T>\n ): AsyncGenerator<StreamEvent, void, void>;\n\n /**\n * Yields LangChain StreamEvent objects from the underlying streamEvents() method.\n * This provides token-level streaming and fine-grained event updates.\n * @deprecated Use the options object instead: `streamEvents({ prompt, maxSteps, ... })`.\n */\n public streamEvents<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): AsyncGenerator<StreamEvent, void, void>;\n\n public async *streamEvents<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector = true,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): AsyncGenerator<StreamEvent, void, void> {\n // Normalize input to internal parameters\n const normalized = normalizeRunOptions(\n queryOrOptions,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n signal\n );\n let { query } = normalized;\n const {\n maxSteps: steps,\n manageConnector: manage,\n externalHistory: history,\n outputSchema: schema,\n signal: abortSignal,\n } = normalized;\n\n let initializedHere = false;\n const startTime = Date.now();\n let success = false;\n let eventCount = 0;\n let totalResponseLength = 0;\n let finalResponse = \"\";\n\n // Enhance query with schema information if structured output is requested\n if (schema) {\n query = this._enhanceQueryWithSchema(query, schema);\n }\n\n try {\n // Initialize if needed\n if (manage && !this._initialized) {\n await this.initialize();\n initializedHere = true;\n } else if (!this._initialized && this.autoInitialize) {\n await this.initialize();\n initializedHere = true;\n }\n\n const agentExecutor = this._agentExecutor;\n if (!agentExecutor) {\n throw new Error(\"MCP agent failed to initialize\");\n }\n\n // Set max iterations\n this.maxSteps = steps ?? this.maxSteps;\n\n const display_query =\n typeof query === \"string\" && query.length > 50\n ? `${query.slice(0, 50).replace(/\\n/g, \" \")}...`\n : typeof query === \"string\"\n ? query.replace(/\\n/g, \" \")\n : String(query);\n logger.debug(`💬 Received query for streamEvents: '${display_query}'`);\n\n // Add user message to history if memory enabled\n if (this.memoryEnabled) {\n logger.debug(`🔄 Adding user message to history: ${display_query}`);\n this.addToHistory(new HumanMessage({ content: query }));\n }\n\n // Prepare history\n const historyToUse = history ?? this.conversationHistory;\n const langchainHistory: BaseMessage[] = [];\n for (const msg of historyToUse) {\n if (\n this._isHumanMessageLike(msg) ||\n this._isAIMessageLike(msg) ||\n this._isToolMessageLike(msg)\n ) {\n langchainHistory.push(msg);\n } else {\n logger.debug(\n `⚠️ Skipped message of type: ${msg.constructor?.name || typeof msg}`\n );\n }\n }\n\n // Prepare inputs\n const inputs: BaseMessage[] = [\n ...langchainHistory,\n new HumanMessage(query),\n ];\n\n logger.debug(\"callbacks\", this.callbacks);\n\n // Stream events from the agent executor with observability support\n const eventStream = agentExecutor.streamEvents(\n { messages: inputs },\n {\n streamMode: \"messages\",\n version: \"v2\",\n callbacks: this.callbacks,\n metadata: this.getMetadata(),\n tags: this.getTags(),\n // Set trace name for LangChain/Langfuse\n runName: this.metadata.trace_name || \"mcp-use-agent\",\n // Set recursion limit to 3x maxSteps to account for model calls + tool executions\n recursionLimit: this.maxSteps * 3,\n // Pass sessionId for Langfuse if present in metadata\n ...(this.metadata.session_id && {\n sessionId: this.metadata.session_id,\n }),\n // Pass abort signal if provided\n ...(abortSignal && { signal: abortSignal }),\n }\n );\n\n // Yield each event\n for await (const event of eventStream) {\n // Check for abort\n if (abortSignal?.aborted) {\n break;\n }\n\n eventCount++;\n\n // Skip null or invalid events\n if (!event || typeof event !== \"object\") {\n continue;\n }\n\n // Track response length for telemetry\n if (\n event.event === \"on_chat_model_stream\" &&\n event.data?.chunk?.content\n ) {\n totalResponseLength += event.data.chunk.content.length;\n }\n\n // Capture AI message content as it streams\n if (event.event === \"on_chat_model_stream\" && event.data?.chunk) {\n const chunk = event.data.chunk;\n if (chunk.content) {\n if (!finalResponse) {\n finalResponse = \"\";\n }\n // Normalize the content to ensure it's a string\n const normalizedContent = this._normalizeOutput(chunk.content);\n finalResponse += normalizedContent;\n logger.debug(\n `📝 Accumulated response length: ${finalResponse.length}`\n );\n }\n }\n\n yield event;\n\n // Capture final response from chain end event (fallback)\n if (\n event.event === \"on_chain_end\" &&\n event.data?.output &&\n !finalResponse\n ) {\n const output = event.data.output;\n if (Array.isArray(output) && output.length > 0 && output[0]?.text) {\n finalResponse = output[0].text;\n } else if (typeof output === \"string\") {\n finalResponse = output;\n } else if (\n output &&\n typeof output === \"object\" &&\n \"output\" in output\n ) {\n finalResponse = output.output;\n }\n }\n }\n\n // Convert to structured output if requested\n if (schema && finalResponse) {\n logger.debug(\"🔧 Attempting structured output conversion...\");\n\n try {\n // Start the conversion (non-blocking)\n let conversionCompleted = false;\n let conversionResult: T | null = null;\n let conversionError: Error | null = null;\n\n this._attemptStructuredOutput<T>(finalResponse, this.llm!, schema)\n .then((result) => {\n conversionCompleted = true;\n conversionResult = result;\n return result;\n })\n .catch((error) => {\n conversionCompleted = true;\n conversionError = error;\n throw error;\n });\n\n // Yield progress events while conversion is running\n let progressCount = 0;\n\n while (!conversionCompleted) {\n // Wait 2 seconds\n await new Promise((resolve) => setTimeout(resolve, 2000));\n\n if (!conversionCompleted) {\n // Still running - yield progress event\n progressCount++;\n yield {\n event: \"on_structured_output_progress\",\n data: {\n message: `Converting to structured output... (${progressCount * 2}s)`,\n elapsed: progressCount * 2,\n },\n } as unknown as StreamEvent;\n }\n }\n\n // Check if conversion succeeded or failed\n if (conversionError) {\n throw conversionError;\n }\n\n if (conversionResult) {\n // Yield structured result as a custom event\n yield {\n event: \"on_structured_output\",\n data: { output: conversionResult },\n } as unknown as StreamEvent;\n\n if (this.memoryEnabled) {\n this.addToHistory(\n new AIMessage(\n `Structured result: ${JSON.stringify(conversionResult)}`\n )\n );\n }\n\n logger.debug(\"✅ Structured output successful\");\n }\n } catch (e) {\n logger.warn(`⚠️ Structured output failed: ${e}`);\n // Yield error event\n yield {\n event: \"on_structured_output_error\",\n data: { error: e instanceof Error ? e.message : String(e) },\n } as unknown as StreamEvent;\n }\n } else if (this.memoryEnabled && finalResponse) {\n // Add the final AI response to conversation history if memory is enabled\n this.addToHistory(new AIMessage(finalResponse));\n }\n console.log(\"\\n\\n\");\n logger.debug(`🎉 StreamEvents complete - ${eventCount} events emitted`);\n success = true;\n } catch (e) {\n logger.error(`❌ Error during streamEvents: ${e}`);\n if (initializedHere && manage) {\n logger.debug(\n \"🧹 Cleaning up resources after initialization error in streamEvents\"\n );\n await this.close();\n }\n throw e;\n } finally {\n // Track telemetry\n const executionTimeMs = Date.now() - startTime;\n\n let serverCount = 0;\n if (this.client) {\n serverCount = Object.keys(this.client.getAllActiveSessions()).length;\n } else if (this.connectors) {\n serverCount = this.connectors.length;\n }\n\n const conversationHistoryLength = this.memoryEnabled\n ? this.conversationHistory.length\n : 0;\n\n await this.telemetry.trackAgentExecution({\n executionMethod: \"streamEvents\",\n query,\n success,\n modelProvider: this.modelProvider,\n modelName: this.modelName,\n serverCount,\n serverIdentifiers: this.connectors.map(\n (connector) => connector.publicIdentifier\n ),\n totalToolsAvailable: this._tools.length,\n toolsAvailableNames: this._tools.map((t) => t.name),\n maxStepsConfigured: this.maxSteps,\n memoryEnabled: this.memoryEnabled,\n useServerManager: this.useServerManager,\n maxStepsUsed: steps ?? null,\n manageConnector: manage ?? true,\n externalHistoryUsed: history !== undefined,\n response: `[STREAMED RESPONSE - ${totalResponseLength} chars]`,\n executionTimeMs,\n errorType: success ? null : \"streaming_error\",\n conversationHistoryLength,\n });\n\n // Clean up if needed\n if (manage && !this.client && initializedHere) {\n logger.debug(\"🧹 Closing agent after streamEvents completion\");\n await this.close();\n }\n }\n }\n\n /**\n * Attempt to create structured output from raw result with validation and retry logic.\n *\n * @param rawResult - The raw text result from the agent\n * @param llm - LLM to use for structured output\n * @param outputSchema - The Zod schema to validate against\n */\n private async _attemptStructuredOutput<T>(\n rawResult: string | any,\n llm: LanguageModel,\n outputSchema: ZodSchema<T>\n ): Promise<T> {\n logger.debug(\n `🔄 Attempting structured output with schema: ${JSON.stringify(outputSchema, null, 2)}`\n );\n logger.debug(`🔄 Raw result: ${JSON.stringify(rawResult, null, 2)}`);\n\n // Schema-aware setup for structured output\n let structuredLlm: LanguageModel = null;\n let schemaDescription = \"\";\n\n logger.debug(\n `🔄 Structured output requested, schema: ${JSON.stringify(toJSONSchema(outputSchema), null, 2)}`\n );\n // Check if withStructuredOutput method exists\n if (\n llm &&\n \"withStructuredOutput\" in llm &&\n typeof (llm as any).withStructuredOutput === \"function\"\n ) {\n structuredLlm = (llm as any).withStructuredOutput(outputSchema);\n } else if (llm) {\n // Fallback: use the same LLM but we'll handle structure in our helper method\n structuredLlm = llm;\n } else {\n throw new Error(\"LLM is required for structured output\");\n }\n const jsonSchema = toJSONSchema(outputSchema) as any;\n const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;\n schemaDescription = JSON.stringify(cleanSchema, null, 2);\n logger.debug(`🔄 Schema description: ${schemaDescription}`);\n\n // Handle different input formats - rawResult might be an array or object from the agent\n let textContent: string = \"\";\n if (typeof rawResult === \"string\") {\n textContent = rawResult;\n } else if (rawResult && typeof rawResult === \"object\") {\n // Handle object format\n textContent = JSON.stringify(rawResult);\n }\n\n logger.debug(\"rawResult\", rawResult);\n\n // If we couldn't extract text, use the stringified version\n if (!textContent) {\n textContent = JSON.stringify(rawResult);\n }\n\n // Get detailed schema information for better prompting\n const maxRetries = 3;\n let lastError: string = \"\";\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n logger.debug(`🔄 Structured output attempt ${attempt}/${maxRetries}`);\n\n let formatPrompt = `\n Please format the following information according to the EXACT schema specified below.\n You must use the exact field names and types as shown in the schema.\n\n Required schema format:\n ${schemaDescription}\n\n Content to extract from:\n ${textContent}\n\n IMPORTANT:\n - Use ONLY the field names specified in the schema\n - Match the data types exactly (string, number, boolean, array, etc.)\n - Include ALL required fields\n - Return valid JSON that matches the schema structure exactly\n - For missing data: use null for nullable fields, omit optional fields entirely\n - Do NOT use empty strings (\"\") or zero (0) as placeholders for missing data\n `;\n\n // Add specific error feedback for retry attempts\n if (attempt > 1) {\n formatPrompt += `\n\n PREVIOUS ATTEMPT FAILED with error: ${lastError}\n Please fix the issues mentioned above and ensure the output matches the schema exactly.\n `;\n }\n\n try {\n logger.debug(\n `🔄 Structured output attempt ${attempt} - using streaming approach`\n );\n const contentPreview =\n textContent.length > 300\n ? `${textContent.slice(0, 300)}...`\n : textContent;\n logger.debug(\n `🔄 Content being formatted (${textContent.length} chars): ${contentPreview}`\n );\n\n // Log the full prompt being sent to LLM\n logger.debug(\n `🔄 Full format prompt (${formatPrompt.length} chars):\\n${formatPrompt}`\n );\n\n // Use streaming to avoid blocking the event loop\n const stream = await structuredLlm!.stream(formatPrompt);\n let structuredResult = null;\n let chunkCount = 0;\n\n for await (const chunk of stream) {\n chunkCount++;\n\n // Print the chunk for debugging\n logger.debug(\n `Chunk ${chunkCount}: ${JSON.stringify(chunk, null, 2)}`\n );\n\n // Handle different chunk types\n if (typeof chunk === \"string\") {\n // If it's a string, try to parse it as JSON\n try {\n structuredResult = JSON.parse(chunk);\n } catch (e) {\n logger.warn(`🔄 Failed to parse string chunk as JSON: ${chunk}`);\n }\n } else if (chunk && typeof chunk === \"object\") {\n // If it's already an object, use it directly\n structuredResult = chunk;\n } else {\n // Convert other types to string and try to parse\n try {\n structuredResult = JSON.parse(String(chunk));\n } catch (e) {\n logger.warn(`🔄 Failed to parse chunk as JSON: ${chunk}`);\n }\n }\n\n if (chunkCount % 10 === 0) {\n logger.debug(\n `🔄 Structured output streaming: ${chunkCount} chunks`\n );\n }\n }\n\n logger.debug(\n `🔄 Structured result attempt ${attempt}: ${JSON.stringify(structuredResult, null, 2)}`\n );\n\n // Use the structured result directly (no need to parse)\n if (!structuredResult) {\n throw new Error(\"No structured result received from stream\");\n }\n\n // Validate the structured result\n const validatedResult = this._validateStructuredResult(\n structuredResult,\n outputSchema\n );\n logger.debug(`✅ Structured output successful on attempt ${attempt}`);\n return validatedResult;\n } catch (e) {\n lastError = e instanceof Error ? e.message : String(e);\n logger.warn(\n `⚠️ Structured output attempt ${attempt} failed: ${lastError}`\n );\n\n if (attempt === maxRetries) {\n logger.error(\n `❌ All ${maxRetries} structured output attempts failed`\n );\n throw new Error(\n `Failed to generate valid structured output after ${maxRetries} attempts. Last error: ${lastError}`\n );\n }\n\n // Continue to next attempt\n continue;\n }\n }\n\n // This should never be reached, but TypeScript requires it\n throw new Error(\"Unexpected error in structured output generation\");\n }\n\n /**\n * Validate the structured result against the schema with detailed error reporting\n */\n private _validateStructuredResult<T>(\n structuredResult: any,\n outputSchema: ZodSchema<T>\n ): T {\n // Use Zod to validate the structured result\n try {\n // Use Zod to validate the structured result\n const validatedResult = outputSchema.parse(structuredResult);\n\n // Additional validation for required fields\n const schemaType = outputSchema as any;\n if (schemaType._def && schemaType._def.shape) {\n for (const [fieldName, fieldSchema] of Object.entries(\n schemaType._def.shape\n )) {\n const field = fieldSchema as any;\n const isOptional =\n field.isOptional?.() ?? field._def?.typeName === \"ZodOptional\";\n const isNullable =\n field.isNullable?.() ?? field._def?.typeName === \"ZodNullable\";\n if (!isOptional && !isNullable) {\n const value = (validatedResult as any)[fieldName];\n if (\n value === null ||\n value === undefined ||\n (typeof value === \"string\" && !value.trim()) ||\n (Array.isArray(value) && value.length === 0)\n ) {\n throw new Error(\n `Required field '${fieldName}' is missing or empty`\n );\n }\n }\n }\n }\n\n return validatedResult;\n } catch (e) {\n logger.debug(`Validation details: ${e}`);\n throw e; // Re-raise to trigger retry logic\n }\n }\n\n /**\n * Enhance the query with schema information to make the agent aware of required fields.\n */\n private _enhanceQueryWithSchema<T>(\n query: string,\n outputSchema: ZodSchema<T>\n ): string {\n try {\n const jsonSchema = toJSONSchema(outputSchema) as any;\n const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;\n const schemaDescription = JSON.stringify(cleanSchema, null, 2);\n\n // Enhance the query with schema awareness\n const enhancedQuery = `\n ${query}\n\n IMPORTANT: Your response must include sufficient information to populate the following structured output:\n\n ${schemaDescription}\n\n Make sure you gather ALL the required information during your task execution.\n If any required information is missing, continue working to find it.\n `;\n\n return enhancedQuery;\n } catch (e) {\n logger.warn(`Could not extract schema details: ${e}`);\n return query;\n }\n }\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type {\n CallToolResult,\n Tool as MCPTool,\n Resource,\n Prompt,\n} from \"@modelcontextprotocol/client\";\nimport type { BaseConnector } from \"@mcp-use/client\";\n\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\nimport { BaseAdapter } from \"./base.js\";\n\nfunction schemaToZod(schema: unknown): z.ZodType {\n try {\n // MCP tool inputSchema is JSON Schema; Zod 4 converts natively.\n return z.fromJSONSchema(schema as Record<string, unknown>);\n } catch (err) {\n logger.warn(`Failed to convert JSON schema to Zod: ${err}`);\n return z.any();\n }\n}\n\nfunction sanitizeToolName(name: string): string {\n return name\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase()\n .replace(/^_+|_+$/g, \"\");\n}\n\n/** Converts MCP tools, resources, and prompts into LangChain structured tools. */\nexport class LangChainAdapter extends BaseAdapter<StructuredToolInterface> {\n private usedToolNames: Set<string> = new Set();\n\n /**\n * @param disallowedTools - MCP tool names to omit during conversion.\n */\n constructor(disallowedTools: string[] = []) {\n super(disallowedTools);\n }\n\n private reserveName(name: string, kind?: \"resource\" | \"prompt\"): string {\n if (!this.usedToolNames.has(name)) {\n this.usedToolNames.add(name);\n return name;\n }\n if (kind) {\n const prefixed = `${kind}_${name}`;\n if (!this.usedToolNames.has(prefixed)) {\n this.usedToolNames.add(prefixed);\n return prefixed;\n }\n // Both base name and prefixed name are taken; fall back to a numeric suffix.\n let i = 2;\n while (this.usedToolNames.has(`${prefixed}_${i}`)) i++;\n const fallback = `${prefixed}_${i}`;\n this.usedToolNames.add(fallback);\n return fallback;\n }\n // No kind: use a numeric suffix to avoid collision.\n let i = 2;\n while (this.usedToolNames.has(`${name}_${i}`)) i++;\n const fallback = `${name}_${i}`;\n this.usedToolNames.add(fallback);\n return fallback;\n }\n\n /**\n * Converts MCP tools from all connectors and resets name deduplication.\n *\n * @param connectors - Connected MCP connectors.\n * @returns LangChain structured tools.\n */\n public override async createToolsFromConnectors(\n connectors: BaseConnector[]\n ): Promise<StructuredToolInterface[]> {\n // Reset names at the start of each loading cycle.\n this.usedToolNames.clear();\n return super.createToolsFromConnectors(connectors);\n }\n\n /**\n * Convert a single MCP tool specification into a LangChainJS structured tool.\n */\n protected convertTool(\n mcpTool: MCPTool,\n connector: BaseConnector\n ): StructuredToolInterface | null {\n // Filter out disallowed tools early.\n if (this.disallowedTools.includes(mcpTool.name)) {\n return null;\n }\n\n // Derive a strict Zod schema for the tool's arguments.\n const argsSchema: z.ZodType = mcpTool.inputSchema\n ? schemaToZod(mcpTool.inputSchema)\n : z.object({}).optional();\n\n const toolName = this.reserveName(mcpTool.name ?? \"NO NAME\");\n const tool = new DynamicStructuredTool({\n name: toolName,\n description: mcpTool.description ?? \"\", // Blank is acceptable but discouraged.\n schema: argsSchema,\n func: async (input: Record<string, any>): Promise<string> => {\n logger.debug(\n `MCP tool \"${mcpTool.name}\" received input: ${JSON.stringify(input)}`\n );\n try {\n const result: CallToolResult = await connector.callTool(\n mcpTool.name,\n input\n );\n return JSON.stringify(result);\n } catch (err: any) {\n logger.error(`Error executing MCP tool: ${err.message}`);\n return `Error executing MCP tool: ${String(err)}`;\n }\n },\n });\n\n return tool;\n }\n\n /**\n * Convert a single MCP resource into a LangChainJS structured tool.\n * Each resource becomes an async tool that returns its content when called.\n */\n protected convertResource(\n mcpResource: Resource,\n connector: BaseConnector\n ): StructuredToolInterface | null {\n const resourceBaseName =\n sanitizeToolName(mcpResource.name || mcpResource.uri) || \"resource\";\n const resourceName = this.reserveName(resourceBaseName, \"resource\");\n const resourceUri = mcpResource.uri;\n\n const tool = new DynamicStructuredTool({\n name: resourceName,\n description:\n mcpResource.description ||\n `Return the content of the resource located at URI ${resourceUri}.`,\n schema: z.object({}).optional(), // Resources take no arguments\n func: async (): Promise<string> => {\n logger.debug(`Resource tool: \"${resourceName}\" called`);\n try {\n const result = await connector.readResource(resourceUri);\n if (result.contents && result.contents.length > 0) {\n return result.contents\n .map((content: any) => {\n if (typeof content === \"string\") {\n return content;\n }\n if (content.text) {\n return content.text;\n }\n if (content.uri) {\n return content.uri;\n }\n return JSON.stringify(content);\n })\n .join(\"\\n\");\n }\n return \"Resource is empty or unavailable\";\n } catch (err: any) {\n logger.error(`Error reading resource: ${err.message}`);\n return `Error reading resource: ${String(err)}`;\n }\n },\n });\n\n return tool;\n }\n\n /**\n * Convert a single MCP prompt into a LangChainJS structured tool.\n * The resulting tool executes getPrompt on the connector with the prompt's name\n * and the user-provided arguments (if any).\n */\n protected convertPrompt(\n mcpPrompt: Prompt,\n connector: BaseConnector\n ): StructuredToolInterface | null {\n // Build Zod schema from prompt arguments\n let argsSchema: z.ZodType = z.object({}).optional();\n\n if (mcpPrompt.arguments && mcpPrompt.arguments.length > 0) {\n const schemaFields: Record<string, z.ZodType> = {};\n for (const arg of mcpPrompt.arguments) {\n // All arguments default to string type since type is not available in Prompt definition\n // (Note: MCP spec includes type, but SDK TypeScript types don't)\n const zodType: z.ZodType = z.string();\n\n if (arg.required !== false) {\n schemaFields[arg.name] = zodType;\n } else {\n schemaFields[arg.name] = zodType.optional();\n }\n }\n argsSchema =\n Object.keys(schemaFields).length > 0\n ? z.object(schemaFields)\n : z.object({}).optional();\n }\n\n const promptBaseName =\n sanitizeToolName(mcpPrompt.name || \"prompt\") || \"prompt\";\n const promptName = this.reserveName(promptBaseName, \"prompt\");\n const tool = new DynamicStructuredTool({\n name: promptName,\n description: mcpPrompt.description || \"\",\n schema: argsSchema,\n func: async (input: Record<string, any>): Promise<string> => {\n logger.debug(\n `Prompt tool: \"${mcpPrompt.name}\" called with args: ${JSON.stringify(input)}`\n );\n try {\n const result = await connector.getPrompt(mcpPrompt.name, input);\n if (result.messages && result.messages.length > 0) {\n return result.messages\n .map((msg: any) => {\n if (typeof msg === \"string\") {\n return msg;\n }\n if (msg.content) {\n return typeof msg.content === \"string\"\n ? msg.content\n : JSON.stringify(msg.content);\n }\n return JSON.stringify(msg);\n })\n .join(\"\\n\");\n }\n return \"Prompt returned no messages\";\n } catch (err: any) {\n logger.error(`Error getting prompt: ${err.message}`);\n return `Error getting prompt: ${String(err)}`;\n }\n },\n });\n\n return tool;\n }\n}\n","import type { MCPClient } from \"@mcp-use/client\";\nimport type { BaseConnector } from \"@mcp-use/client\";\nimport { logger } from \"@mcp-use/client\";\n\n/**\n * Abstract base class for converting MCP tools to other framework formats.\n *\n * This class defines the common interface that all adapter implementations\n * should follow to ensure consistency across different frameworks.\n */\nexport abstract class BaseAdapter<T> {\n /**\n * List of tool names that should not be available.\n */\n protected readonly disallowedTools: string[];\n\n /**\n * Internal cache that maps a connector instance to the list of tools\n * generated for it.\n */\n private readonly connectorToolMap: Map<BaseConnector, T[]> = new Map();\n\n /**\n * @param disallowedTools - MCP tool names to omit during conversion.\n */\n constructor(disallowedTools?: string[]) {\n this.disallowedTools = disallowedTools ?? [];\n }\n\n /**\n * Create tools from an MCPClient instance.\n *\n * This is the recommended way to create tools from an MCPClient, as it handles\n * session creation and connector extraction automatically.\n *\n * @param client - The MCPClient to extract tools from.\n * @param disallowedTools - Optional list of tool names to exclude.\n * @returns A promise that resolves with a list of converted tools.\n */\n static async createTools<TTool, TAdapter extends BaseAdapter<TTool>>(\n this: new (disallowedTools?: string[]) => TAdapter,\n client: MCPClient,\n disallowedTools?: string[]\n ): Promise<TTool[]> {\n // Create the adapter\n const adapter = new this(disallowedTools);\n\n // Ensure we have active sessions\n if (\n !client.activeSessions ||\n Object.keys(client.activeSessions).length === 0\n ) {\n logger.debug(\"No active sessions found, creating new ones...\");\n await client.createAllSessions();\n }\n\n // Get all active sessions\n const sessions = client.getAllActiveSessions();\n\n // Extract connectors from sessions\n const connectors: BaseConnector[] = Object.values(sessions).map(\n (session) => session.connector\n );\n\n // Create tools from connectors\n return adapter.createToolsFromConnectors(connectors);\n }\n\n /**\n * Dynamically load tools for a specific connector.\n *\n * @param connector - The connector to load tools for.\n * @returns The list of tools that were loaded in the target framework's format.\n */\n async loadToolsForConnector(connector: BaseConnector): Promise<T[]> {\n // Return cached tools if we already processed this connector\n if (this.connectorToolMap.has(connector)) {\n const cached = this.connectorToolMap.get(connector)!;\n logger.debug(`Returning ${cached.length} existing tools for connector`);\n return cached;\n }\n\n const connectorTools: T[] = [];\n\n // Make sure the connector is initialized and has tools\n const success = await this.ensureConnectorInitialized(connector);\n if (!success) {\n return [];\n }\n\n // Convert and collect tools\n for (const tool of connector.tools) {\n const converted = this.convertTool(tool, connector);\n if (converted) {\n connectorTools.push(converted);\n }\n }\n\n // Cache the tools for this connector\n this.connectorToolMap.set(connector, connectorTools);\n\n // Log for debugging purposes\n logger.debug(\n `Loaded ${connectorTools.length} new tools for connector: ${connectorTools\n .map((t: any) => t?.name ?? String(t))\n .join(\", \")}`\n );\n\n return connectorTools;\n }\n\n /**\n * Convert an MCP tool to the target framework's tool format.\n *\n * @param mcpTool - The MCP tool definition to convert.\n * @param connector - The connector that provides this tool.\n * @returns The converted tool, or null / undefined if no tool should be produced.\n */\n protected abstract convertTool(\n mcpTool: Record<string, any>,\n connector: BaseConnector\n ): T | null | undefined;\n\n /**\n * Convert an MCP resource to the target framework's tool format.\n *\n * @param mcpResource - The MCP resource definition to convert.\n * @param connector - The connector that provides this resource.\n * @returns The converted resource as a tool, or null / undefined if no tool should be produced.\n */\n protected abstract convertResource?(\n mcpResource: Record<string, any>,\n connector: BaseConnector\n ): T | null | undefined;\n\n /**\n * Convert an MCP prompt to the target framework's tool format.\n *\n * @param mcpPrompt - The MCP prompt definition to convert.\n * @param connector - The connector that provides this prompt.\n * @returns The converted prompt as a tool, or null / undefined if no tool should be produced.\n */\n protected abstract convertPrompt?(\n mcpPrompt: Record<string, any>,\n connector: BaseConnector\n ): T | null | undefined;\n\n /**\n * Create tools from MCP tools in all provided connectors.\n *\n * @param connectors - List of MCP connectors to create tools from.\n * @returns A promise that resolves with all converted tools.\n */\n public async createToolsFromConnectors(\n connectors: BaseConnector[]\n ): Promise<T[]> {\n const tools: T[] = [];\n for (const connector of connectors) {\n const connectorTools = await this.loadToolsForConnector(connector);\n tools.push(...connectorTools);\n }\n\n logger.debug(`Available tools: ${tools.length}`);\n return tools;\n }\n\n /**\n * Dynamically load resources for a specific connector.\n *\n * @param connector - The connector to load resources for.\n * @returns The list of resources that were loaded in the target framework's format.\n */\n async loadResourcesForConnector(connector: BaseConnector): Promise<T[]> {\n const connectorResources: T[] = [];\n\n // Make sure the connector is initialized\n const success = await this.ensureConnectorInitialized(connector);\n if (!success) {\n return [];\n }\n\n try {\n // Get resources from connector\n const resourcesResult = await connector.listAllResources();\n const resources = resourcesResult?.resources || [];\n\n // Convert and collect resources\n if (this.convertResource) {\n for (const resource of resources) {\n const converted = this.convertResource(resource, connector);\n if (converted) {\n connectorResources.push(converted);\n }\n }\n }\n\n logger.debug(\n `Loaded ${connectorResources.length} new resources for connector: ${connectorResources\n .map((r: any) => r?.name ?? String(r))\n .join(\", \")}`\n );\n } catch (err) {\n logger.warn(`Error loading resources for connector: ${err}`);\n }\n\n return connectorResources;\n }\n\n /**\n * Dynamically load prompts for a specific connector.\n *\n * @param connector - The connector to load prompts for.\n * @returns The list of prompts that were loaded in the target framework's format.\n */\n async loadPromptsForConnector(connector: BaseConnector): Promise<T[]> {\n const connectorPrompts: T[] = [];\n\n // Make sure the connector is initialized\n const success = await this.ensureConnectorInitialized(connector);\n if (!success) {\n return [];\n }\n\n try {\n // Get prompts from connector\n const promptsResult = await connector.listPrompts();\n const prompts = promptsResult?.prompts || [];\n\n // Convert and collect prompts\n if (this.convertPrompt) {\n for (const prompt of prompts) {\n const converted = this.convertPrompt(prompt, connector);\n if (converted) {\n connectorPrompts.push(converted);\n }\n }\n }\n\n logger.debug(\n `Loaded ${connectorPrompts.length} new prompts for connector: ${connectorPrompts\n .map((p: any) => p?.name ?? String(p))\n .join(\", \")}`\n );\n } catch (err) {\n logger.warn(`Error loading prompts for connector: ${err}`);\n }\n\n return connectorPrompts;\n }\n\n /**\n * Create resources from MCP resources in all provided connectors.\n *\n * @param connectors - List of MCP connectors to create resources from.\n * @returns A promise that resolves with all converted resources.\n */\n public async createResourcesFromConnectors(\n connectors: BaseConnector[]\n ): Promise<T[]> {\n const resources: T[] = [];\n for (const connector of connectors) {\n const connectorResources =\n await this.loadResourcesForConnector(connector);\n resources.push(...connectorResources);\n }\n\n logger.debug(`Available resources: ${resources.length}`);\n return resources;\n }\n\n /**\n * Create prompts from MCP prompts in all provided connectors.\n *\n * @param connectors - List of MCP connectors to create prompts from.\n * @returns A promise that resolves with all converted prompts.\n */\n public async createPromptsFromConnectors(\n connectors: BaseConnector[]\n ): Promise<T[]> {\n const prompts: T[] = [];\n for (const connector of connectors) {\n const connectorPrompts = await this.loadPromptsForConnector(connector);\n prompts.push(...connectorPrompts);\n }\n\n logger.debug(`Available prompts: ${prompts.length}`);\n return prompts;\n }\n\n /**\n * Check if a connector is initialized and has tools.\n *\n * @param connector - The connector to check.\n * @returns True if the connector is initialized and has tools, false otherwise.\n */\n private checkConnectorInitialized(connector: BaseConnector): boolean {\n return Boolean(connector.tools && connector.tools.length);\n }\n\n /**\n * Ensure a connector is initialized.\n *\n * @param connector - The connector to initialize.\n * @returns True if initialization succeeded, false otherwise.\n */\n private async ensureConnectorInitialized(\n connector: BaseConnector\n ): Promise<boolean> {\n if (!this.checkConnectorInitialized(connector)) {\n logger.debug(\"Connector doesn't have tools, initializing it\");\n try {\n await connector.initialize();\n return true;\n } catch (err) {\n logger.error(`Error initializing connector: ${err}`);\n return false;\n }\n }\n return true;\n }\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { LangChainAdapter } from \"../adapters/langchain_adapter.js\";\nimport type { MCPClient } from \"@mcp-use/client\";\nimport type { BaseConnector } from \"@mcp-use/client\";\nimport type { MCPSession } from \"@mcp-use/client\";\nimport type { IServerManager } from \"./types.js\";\nimport { logger } from \"@mcp-use/client\";\nimport { AcquireActiveMCPServerTool } from \"./tools/acquire_active_mcp_server.js\";\nimport { AddMCPServerFromConfigTool } from \"./tools/add_server_from_config.js\";\nimport { ConnectMCPServerTool } from \"./tools/connect_mcp_server.js\";\nimport { ListMCPServersTool } from \"./tools/list_mcp_servers.js\";\nimport { ReleaseMCPServerConnectionTool } from \"./tools/release_mcp_server_connection.js\";\n\n/**\n * Deep equality check for comparing objects and arrays\n * Handles nested structures, primitives, arrays, and objects\n */\nfunction isEqual(a: any, b: any): boolean {\n // Handle identical references and primitives\n if (a === b) return true;\n\n // Handle null/undefined cases\n if (a == null || b == null) return false;\n\n // Handle different types\n if (typeof a !== typeof b) return false;\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((item, index) => isEqual(item, b[index]));\n }\n\n // Handle objects\n if (typeof a === \"object\" && typeof b === \"object\") {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n return keysA.every((key) => {\n return (\n Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key])\n );\n });\n }\n\n // For primitives that aren't strictly equal\n return false;\n}\n\n/** Selects an active MCP server and exposes its LangChain tools. */\nexport class ServerManager implements IServerManager {\n /** Whether capabilities have been loaded for each configured server. */\n public readonly initializedServers: Record<string, boolean> = {};\n /** Cached LangChain tools, resources, and prompts by server name. */\n public readonly serverTools: Record<string, StructuredToolInterface[]> = {};\n\n /** MCP client that owns server configurations and sessions. */\n public readonly client: MCPClient;\n /** Adapter used to create LangChain tools. */\n public readonly adapter: LangChainAdapter;\n /** Server whose cached tools are currently exposed. */\n public activeServer: string | null = null;\n private overrideManagementTools?: StructuredToolInterface[];\n\n /**\n * @param client - MCP client that owns the managed servers.\n * @param adapter - Adapter used to convert MCP capabilities.\n * @param managementTools - Optional replacement for the built-in server\n * management tools.\n */\n constructor(\n client: MCPClient,\n adapter: LangChainAdapter,\n managementTools?: StructuredToolInterface[]\n ) {\n this.client = client;\n this.adapter = adapter;\n this.overrideManagementTools = managementTools;\n }\n\n /**\n * Replaces the management tools returned by {@link ServerManager.tools}.\n *\n * @param tools - Complete replacement tool list.\n */\n public setManagementTools(tools: StructuredToolInterface[]): void {\n this.overrideManagementTools = tools;\n logger.debug(\n `Overriding default management tools with a new set of ${tools.length} tools.`\n );\n }\n\n /**\n * Writes current connection and tool-cache state at debug level.\n *\n * @param context - Label describing why the state was logged.\n */\n public logState(context: string): void {\n const allServerNames = this.client.getServerNames();\n const activeSessionNames = Object.keys(this.client.getAllActiveSessions());\n\n if (allServerNames.length === 0) {\n logger.debug(\"Server Manager State: No servers configured.\");\n return;\n }\n\n const tableData = allServerNames.map((name) => ({\n \"Server Name\": name,\n Connected: activeSessionNames.includes(name) ? \"✅\" : \"❌\",\n Initialized: this.initializedServers[name] ? \"✅\" : \"❌\",\n \"Tool Count\": this.serverTools[name]?.length ?? 0,\n Active: this.activeServer === name ? \"✅\" : \"❌\",\n }));\n\n logger.debug(`Server Manager State: [${context}]`);\n console.table(tableData);\n }\n\n /** Validates that the client contains at least one server configuration. */\n initialize(): void {\n const serverNames = this.client.getServerNames?.();\n if (serverNames.length === 0) {\n logger.warn(\"No MCP servers defined in client configuration\");\n }\n }\n\n /**\n * Connects configured servers as needed and caches all tools, resources, and\n * prompts.\n */\n async prefetchServerTools(): Promise<void> {\n const servers: string[] = this.client.getServerNames();\n\n for (const serverName of servers) {\n try {\n let session: MCPSession | null = null;\n\n session = this.client.getSession(serverName);\n logger.debug(\n `Using existing session for server '${serverName}' to prefetch tools.`\n );\n\n if (!session) {\n session = await this.client\n .createSession(serverName)\n .catch((createSessionError) => {\n logger.warn(\n `Could not create session for '${serverName}' during prefetch: ${createSessionError}`\n );\n return null;\n });\n logger.debug(\n `Temporarily created session for '${serverName}' to prefetch tools.`\n );\n }\n\n if (session) {\n const connector: BaseConnector = session.connector;\n let tools: StructuredToolInterface[] = [];\n let resources: StructuredToolInterface[] = [];\n let prompts: StructuredToolInterface[] = [];\n\n try {\n tools = await this.adapter.createToolsFromConnectors([connector]);\n resources = await this.adapter.createResourcesFromConnectors([\n connector,\n ]);\n prompts = await this.adapter.createPromptsFromConnectors([\n connector,\n ]);\n } catch (toolFetchError) {\n logger.error(\n `Failed to create tools/resources/prompts from connector for server '${serverName}': ${toolFetchError}`\n );\n continue;\n }\n\n const allItems = [...tools, ...resources, ...prompts];\n const cachedTools = this.serverTools[serverName];\n const toolsChanged = !cachedTools || !isEqual(cachedTools, allItems);\n\n if (toolsChanged) {\n this.serverTools[serverName] = allItems;\n this.initializedServers[serverName] = true;\n logger.debug(\n `Prefetched ${allItems.length} items for server '${serverName}': ` +\n `${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts.`\n );\n } else {\n logger.debug(\n `Tools for server '${serverName}' unchanged, using cached version.`\n );\n }\n }\n } catch (outerError) {\n logger.error(\n `Error prefetching tools for server '${serverName}': ${outerError}`\n );\n }\n }\n }\n\n /**\n * @returns Management tools plus cached tools from the active server, if any.\n */\n get tools(): StructuredToolInterface[] {\n if (logger.level === \"debug\") {\n this.logState(\"Providing tools to agent\");\n }\n\n const managementTools = this.overrideManagementTools ?? [\n new AddMCPServerFromConfigTool(this),\n new ListMCPServersTool(this),\n new ConnectMCPServerTool(this),\n new AcquireActiveMCPServerTool(this),\n new ReleaseMCPServerConnectionTool(this),\n ];\n\n if (this.activeServer && this.serverTools[this.activeServer]) {\n const activeTools = this.serverTools[this.activeServer];\n logger.debug(\n `Adding ${activeTools.length} tools from active server '${this.activeServer}'`\n );\n return [...managementTools, ...activeTools];\n }\n\n return managementTools;\n }\n}\n","import type { IServerManager } from \"../types.js\";\nimport { z } from \"zod\";\nimport { MCPServerTool } from \"./base.js\";\n\nconst PresentActiveServerSchema = z.object({});\n\n/** Reports the MCP server whose tools are currently active. */\nexport class AcquireActiveMCPServerTool extends MCPServerTool<\n typeof PresentActiveServerSchema\n> {\n /** Tool name exposed to the model. */\n override name = \"get_active_mcp_server\";\n /** Tool description exposed to the model. */\n override description =\n \"Get the currently active MCP (Model Context Protocol) server\";\n /** Empty input schema. */\n override schema = PresentActiveServerSchema;\n\n constructor(manager: IServerManager) {\n super(manager);\n }\n\n /** @returns A message identifying the active server, or stating there is none. */\n async _call(): Promise<string> {\n if (!this.manager.activeServer) {\n return `No MCP server is currently active. Use connect_to_mcp_server to connect to a server.`;\n }\n\n return `Currently active MCP server: ${this.manager.activeServer}`;\n }\n}\n","import type { CallbackManagerForToolRun } from \"@langchain/core/callbacks/manager\";\nimport type { ToolRunnableConfig, ToolSchemaBase } from \"@langchain/core/tools\";\nimport type { JSONSchema } from \"@langchain/core/utils/json_schema\";\nimport type z from \"zod\";\nimport type { IServerManager } from \"../types.js\";\nimport { StructuredTool } from \"@langchain/core/tools\";\n\ntype ToolOutputT = any;\nexport type SchemaOutputT<T extends ToolSchemaBase> = T extends z.ZodSchema\n ? z.output<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\nexport class MCPServerTool<\n SchemaT extends ToolSchemaBase,\n> extends StructuredTool<SchemaT, SchemaOutputT<SchemaT>> {\n /** Default tool name. Subclasses replace this value. */\n override name: string = \"mcp_server_tool\";\n /** Default tool description. Subclasses replace this value. */\n override description: string = \"Base tool for MCP server operations.\";\n /** Input schema supplied by the concrete management tool. */\n override schema!: SchemaT;\n\n private readonly _manager: IServerManager;\n\n /**\n * @param manager - Server manager operated by this tool.\n */\n constructor(manager: IServerManager) {\n super();\n this._manager = manager;\n }\n\n protected async _call(\n _arg: SchemaOutputT<SchemaT>,\n _runManager?: CallbackManagerForToolRun,\n _parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n throw new Error(\"Method not implemented.\");\n }\n\n /** @returns The server manager operated by this tool. */\n get manager(): IServerManager {\n return this._manager;\n }\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { IServerManager } from \"../types.js\";\nimport { StructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\n\n/** Adds, connects, and activates an MCP server from model-supplied config. */\nexport class AddMCPServerFromConfigTool extends StructuredTool {\n /** Tool name exposed to the model. */\n name = \"add_mcp_server_from_config\";\n /** Tool description exposed to the model. */\n description =\n \"Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.\";\n\n /** Input schema for the server name and transport configuration. */\n schema = z.object({\n /** Name used to register the server with the MCP client. */\n serverName: z.string().describe(\"The name for the new MCP server.\"),\n /** MCP transport configuration without a top-level `mcpServers` key. */\n serverConfig: z\n .any()\n .describe(\n 'The configuration object for the server. This should not include the top-level \"mcpServers\" key.'\n ),\n });\n\n private manager: IServerManager;\n\n /**\n * @param manager - Server manager that receives the new server.\n */\n constructor(manager: IServerManager) {\n super();\n this.manager = manager;\n }\n\n /**\n * Adds the server, opens a session, and makes the server active.\n *\n * @returns A success message with loaded tool names, or an error message.\n */\n protected async _call({\n serverName,\n serverConfig,\n }: z.infer<typeof this.schema>): Promise<string> {\n try {\n this.manager.client.addServer(serverName, serverConfig);\n let result = `Server '${serverName}' added to the client.`;\n logger.debug(\n `Connecting to new server '${serverName}' and discovering tools.`\n );\n const session = await this.manager.client.createSession(serverName);\n const connector = session.connector;\n const tools: StructuredToolInterface[] =\n await this.manager.adapter.createToolsFromConnectors([connector]);\n\n this.manager.serverTools[serverName] = tools;\n this.manager.initializedServers[serverName] = true;\n this.manager.activeServer = serverName; // Set as active server\n\n const numTools = tools.length;\n result += ` Session created and connected. '${serverName}' is now the active server with ${numTools} tools available.`;\n result += `\\n\\n${tools.map((t) => t.name).join(\"\\n\")}`;\n logger.debug(result);\n return result;\n } catch (e: any) {\n logger.error(\n `Failed to add or connect to server '${serverName}': ${e.message}`\n );\n return `Failed to add or connect to server '${serverName}': ${e.message}`;\n }\n }\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { BaseConnector } from \"@mcp-use/client\";\nimport type { IServerManager } from \"../types.js\";\nimport type { SchemaOutputT } from \"./base.js\";\nimport { z } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\nimport { MCPServerTool } from \"./base.js\";\n\nconst ConnectMCPServerSchema = z.object({\n /** Name of a configured MCP server. */\n serverName: z.string().describe(\"The name of the MCP server.\"),\n});\n\n/** Activates a configured MCP server and exposes its capabilities. */\nexport class ConnectMCPServerTool extends MCPServerTool<\n typeof ConnectMCPServerSchema\n> {\n /** Tool name exposed to the model. */\n override name = \"connect_to_mcp_server\";\n /** Tool description exposed to the model. */\n override description =\n \"Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.\";\n /** Input schema containing the server name. */\n override schema = ConnectMCPServerSchema;\n\n constructor(manager: IServerManager) {\n super(manager);\n }\n\n /**\n * Activates a configured server and loads its capabilities if needed.\n *\n * @returns A human-readable success or error message.\n */\n async _call({ serverName }: SchemaOutputT<typeof ConnectMCPServerSchema>) {\n const serverNames = this.manager.client.getServerNames();\n\n if (!serverNames.includes(serverName)) {\n const available =\n serverNames.length > 0 ? serverNames.join(\", \") : \"none\";\n return `Server '${serverName}' not found. Available servers: ${available}`;\n }\n\n if (this.manager.activeServer === serverName) {\n return `Already connected to MCP server '${serverName}'`;\n }\n\n try {\n let session = this.manager.client.getSession(serverName);\n logger.debug(`Using existing session for server '${serverName}'`);\n if (!session) {\n logger.debug(`Creating new session for server '${serverName}'`);\n session = await this.manager.client.createSession(serverName);\n }\n this.manager.activeServer = serverName;\n if (!this.manager.serverTools[serverName]) {\n const connector: BaseConnector = session.connector;\n const tools: StructuredToolInterface[] =\n await this.manager.adapter.createToolsFromConnectors([connector]);\n const resources: StructuredToolInterface[] =\n await this.manager.adapter.createResourcesFromConnectors([connector]);\n const prompts: StructuredToolInterface[] =\n await this.manager.adapter.createPromptsFromConnectors([connector]);\n const allItems = [...tools, ...resources, ...prompts];\n this.manager.serverTools[serverName] = allItems;\n this.manager.initializedServers[serverName] = true;\n logger.debug(\n `Loaded ${allItems.length} items for server '${serverName}': ` +\n `${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`\n );\n }\n const serverTools: StructuredToolInterface[] =\n this.manager.serverTools[serverName] || [];\n const numTools: number = serverTools.length;\n return `Connected to MCP server '${serverName}'. ${numTools} tools, resources, and prompts are now available.`;\n } catch (error) {\n logger.error(\n `Error connecting to server '${serverName}': ${String(error)}`\n );\n return `Failed to connect to server '${serverName}': ${String(error)}`;\n }\n }\n}\n","import type { IServerManager } from \"../types.js\";\nimport { z } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\nimport { MCPServerTool } from \"./base.js\";\n\nconst EnumerateServersSchema = z.object({});\n\n/** Lists configured MCP servers and their cached capability counts. */\nexport class ListMCPServersTool extends MCPServerTool<\n typeof EnumerateServersSchema\n> {\n /** Tool name exposed to the model. */\n override name = \"list_mcp_servers\";\n /** Tool description exposed to the model. */\n override description = `Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.`;\n /** Empty input schema. */\n override schema = EnumerateServersSchema;\n\n constructor(manager: IServerManager) {\n super(manager);\n }\n\n /** @returns A formatted list of configured servers and capability counts. */\n async _call(): Promise<string> {\n const serverNames = this.manager.client.getServerNames();\n if (serverNames.length === 0) {\n return `No MCP servers are currently defined.`;\n }\n\n const outputLines: string[] = [\"Available MCP servers:\"];\n\n for (const serverName of serverNames) {\n const isActiveServer = serverName === this.manager.activeServer;\n const activeFlag = isActiveServer ? \" (ACTIVE)\" : \"\";\n outputLines.push(`- ${serverName}${activeFlag}`);\n\n try {\n const serverTools = this.manager.serverTools?.[serverName] ?? [];\n const numberOfTools = Array.isArray(serverTools)\n ? serverTools.length\n : 0;\n outputLines.push(`${numberOfTools} tools available for this server\\n`);\n } catch (error) {\n logger.error(\n `Unexpected error listing tools for server '${serverName}': ${String(error)}`\n );\n }\n }\n return outputLines.join(\"\\n\");\n }\n}\n","import type { IServerManager } from \"../types.js\";\nimport { z } from \"zod\";\nimport { MCPServerTool } from \"./base.js\";\n\nconst ReleaseConnectionSchema = z.object({});\n\n/** Deactivates the current MCP server without closing its client session. */\nexport class ReleaseMCPServerConnectionTool extends MCPServerTool<\n typeof ReleaseConnectionSchema\n> {\n /** Tool name exposed to the model. */\n override name = \"disconnect_from_mcp_server\";\n /** Tool description exposed to the model. */\n override description =\n \"Disconnect from the currently active MCP (Model Context Protocol) server\";\n /** Empty input schema. */\n override schema = ReleaseConnectionSchema;\n\n constructor(manager: IServerManager) {\n super(manager);\n }\n\n /** @returns A message identifying the deactivated server, or stating there is none. */\n async _call(): Promise<string> {\n if (!this.manager.activeServer) {\n return `No MCP server is currently active, so there's nothing to disconnect from.`;\n }\n const serverName = this.manager.activeServer;\n this.manager.activeServer = null;\n return `Successfully disconnected from MCP server '${serverName}'.`;\n }\n}\n","/**\n * Observability module for MCP-use.\n *\n * This module provides centralized observability management for LangChain agents,\n * supporting multiple platforms like Langfuse and Laminar.\n */\n\n// Import observability providers - order matters for initialization\nimport \"./langfuse.js\";\n\n// Export the manager and its utilities\nexport {\n type ObservabilityConfig,\n ObservabilityManager,\n type ObservabilityStatus,\n} from \"./manager.js\";\n","/**\n * Observability callbacks manager for MCP-use.\n *\n * This module provides a centralized manager for handling observability callbacks\n * from various platforms (Langfuse, Laminar, etc.) in a clean and extensible way.\n */\n\nimport type { BaseCallbackHandler } from \"@langchain/core/callbacks/base\";\nimport { logger } from \"@mcp-use/client\";\n\n/** Configures callbacks and trace metadata for an agent. */\nexport interface ObservabilityConfig {\n /** Custom callbacks to use instead of defaults */\n customCallbacks?: BaseCallbackHandler[];\n /** Whether to enable verbose logging */\n verbose?: boolean;\n /** Whether to enable observability (defaults to true) */\n observe?: boolean;\n /** Agent ID for tagging traces */\n agentId?: string;\n /** Metadata to add to traces */\n metadata?: Record<string, any>;\n /** Function to get current metadata from agent */\n metadataProvider?: () => Record<string, any>;\n /** Function to get current tags from agent */\n tagsProvider?: () => string[];\n}\n\n/** Snapshot returned by {@link ObservabilityManager.getStatus}. */\nexport interface ObservabilityStatus {\n /** Whether observability is enabled and has at least one callback. */\n enabled: boolean;\n /** Number of active callbacks. */\n callbackCount: number;\n /** Human-readable callback handler names. */\n handlerNames: string[];\n /** Current trace metadata. */\n metadata: Record<string, any>;\n /** Current trace tags. */\n tags: string[];\n}\n\n/** Discovers, configures, and shuts down LangChain observability callbacks. */\nexport class ObservabilityManager {\n private customCallbacks?: BaseCallbackHandler[];\n private availableHandlers: BaseCallbackHandler[] = [];\n private handlerNames: string[] = [];\n private initialized = false;\n private verbose: boolean;\n private observe: boolean;\n private agentId?: string;\n private metadata?: Record<string, any>;\n private metadataProvider?: () => Record<string, any>;\n private tagsProvider?: () => string[];\n\n /**\n * @param config - Callback selection and trace metadata settings.\n */\n constructor(config: ObservabilityConfig = {}) {\n this.customCallbacks = config.customCallbacks;\n this.verbose = config.verbose ?? false;\n this.observe = config.observe ?? true;\n this.agentId = config.agentId;\n this.metadata = config.metadata;\n this.metadataProvider = config.metadataProvider;\n this.tagsProvider = config.tagsProvider;\n }\n\n /**\n * Collect all available observability handlers from configured platforms.\n */\n private async collectAvailableHandlers(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n // Import handlers lazily to avoid circular imports\n try {\n const { langfuseHandler, langfuseInitPromise } =\n await import(\"./langfuse.js\");\n\n // If we have an agent ID, metadata, or providers, we need to reinitialize Langfuse\n if (\n this.agentId ||\n this.metadata ||\n this.metadataProvider ||\n this.tagsProvider\n ) {\n // Import the initialization function directly\n const { initializeLangfuse } = await import(\"./langfuse.js\");\n await initializeLangfuse(\n this.agentId,\n this.metadata,\n this.metadataProvider,\n this.tagsProvider\n );\n logger.debug(\n `ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`\n );\n } else {\n // Wait for existing initialization to complete\n const initPromise = langfuseInitPromise();\n if (initPromise) {\n await initPromise;\n }\n }\n\n const handler = langfuseHandler();\n if (handler) {\n this.availableHandlers.push(handler);\n this.handlerNames.push(\"Langfuse\");\n logger.debug(\"ObservabilityManager: Langfuse handler available\");\n }\n } catch {\n logger.debug(\"ObservabilityManager: Langfuse module not available\");\n }\n\n // Future: Add more platforms here...\n\n this.initialized = true;\n }\n\n /**\n * Get the list of callbacks to use.\n * @returns List of callbacks - either custom callbacks if provided, or all available observability handlers.\n */\n async getCallbacks(): Promise<BaseCallbackHandler[]> {\n // If observability is disabled, return empty array\n if (!this.observe) {\n logger.debug(\n \"ObservabilityManager: Observability disabled via observe=false\"\n );\n return [];\n }\n\n // If custom callbacks were provided, use those\n if (this.customCallbacks) {\n logger.debug(\n `ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`\n );\n return this.customCallbacks;\n }\n\n // Otherwise, collect and return all available handlers\n await this.collectAvailableHandlers();\n\n if (this.availableHandlers.length > 0) {\n logger.debug(\n `ObservabilityManager: Using ${this.availableHandlers.length} handlers`\n );\n } else {\n logger.debug(\"ObservabilityManager: No callbacks configured\");\n }\n\n return this.availableHandlers;\n }\n\n /**\n * Get the names of available handlers.\n * @returns List of handler names (e.g., [\"Langfuse\", \"Laminar\"])\n */\n async getHandlerNames(): Promise<string[]> {\n // If observability is disabled, return empty array\n if (!this.observe) {\n return [];\n }\n\n if (this.customCallbacks) {\n // For custom callbacks, try to get their class names\n return this.customCallbacks.map((cb) => cb.constructor.name);\n }\n\n await this.collectAvailableHandlers();\n return this.handlerNames;\n }\n\n /**\n * Check if any callbacks are available.\n * @returns True if callbacks are available, False otherwise.\n */\n async hasCallbacks(): Promise<boolean> {\n // If observability is disabled, no callbacks are available\n if (!this.observe) {\n return false;\n }\n\n const callbacks = await this.getCallbacks();\n return callbacks.length > 0;\n }\n\n /**\n * Get the current observability status including metadata and tags.\n * @returns Object containing enabled status, callback count, handler names, metadata, and tags.\n */\n async getStatus(): Promise<ObservabilityStatus> {\n const callbacks = await this.getCallbacks();\n const handlerNames = await this.getHandlerNames();\n\n // Get current metadata from provider if available\n const currentMetadata = this.metadataProvider\n ? this.metadataProvider()\n : this.metadata || {};\n\n // Get current tags from provider if available\n const currentTags = this.tagsProvider ? this.tagsProvider() : [];\n\n return {\n enabled: this.observe && callbacks.length > 0,\n callbackCount: callbacks.length,\n handlerNames,\n metadata: currentMetadata,\n tags: currentTags,\n };\n }\n\n /**\n * Add a callback to the custom callbacks list.\n * @param callback - The callback to add.\n */\n addCallback(callback: BaseCallbackHandler): void {\n if (!this.customCallbacks) {\n this.customCallbacks = [];\n }\n this.customCallbacks.push(callback);\n logger.debug(\n `ObservabilityManager: Added custom callback: ${callback.constructor.name}`\n );\n }\n\n /**\n * Clear all custom callbacks.\n */\n clearCallbacks(): void {\n this.customCallbacks = [];\n logger.debug(\"ObservabilityManager: Cleared all custom callbacks\");\n }\n\n /**\n * Flush all pending traces to observability platforms.\n * Important for serverless environments and short-lived processes.\n */\n async flush(): Promise<void> {\n // Flush Langfuse traces\n const callbacks = await this.getCallbacks();\n for (const callback of callbacks) {\n if (\n \"flushAsync\" in callback &&\n typeof callback.flushAsync === \"function\"\n ) {\n await callback.flushAsync();\n }\n }\n logger.debug(\"ObservabilityManager: All traces flushed\");\n }\n\n /**\n * Shutdown all handlers gracefully (for serverless environments).\n */\n async shutdown(): Promise<void> {\n // Flush before shutdown\n await this.flush();\n\n // Shutdown other callbacks\n const callbacks = await this.getCallbacks();\n for (const callback of callbacks) {\n // Check if the callback has a shutdown method (like Langfuse)\n if (\n \"shutdownAsync\" in callback &&\n typeof callback.shutdownAsync === \"function\"\n ) {\n await callback.shutdownAsync();\n } else if (\n \"shutdown\" in callback &&\n typeof callback.shutdown === \"function\"\n ) {\n await (callback as any).shutdown();\n }\n }\n logger.debug(\"ObservabilityManager: All handlers shutdown\");\n }\n\n /**\n * String representation of the ObservabilityManager.\n */\n toString(): string {\n const names = this.handlerNames;\n if (names.length > 0) {\n return `ObservabilityManager(handlers=${names.join(\", \")})`;\n }\n return \"ObservabilityManager(no handlers)\";\n }\n}\n","declare const __MCP_USE_PACKAGE_VERSION__: string;\n\nexport const VERSION = __MCP_USE_PACKAGE_VERSION__;\n\nexport function getPackageVersion(): string {\n return VERSION;\n}\n","import type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nexport { getPackageVersion } from \"../version.js\";\n\nfunction getModelProvider(llm: BaseLanguageModel): string {\n // Use LangChain's standard _llm_type property for identification\n return (llm as any)._llm_type || llm.constructor.name.toLowerCase();\n}\n\nfunction getModelName(llm: BaseLanguageModel): string {\n // First try _identifying_params which may contain model info\n if (\"_identifyingParams\" in llm) {\n const identifyingParams = (llm as any)._identifyingParams;\n if (typeof identifyingParams === \"object\" && identifyingParams !== null) {\n // Common keys that contain model names\n for (const key of [\n \"model\",\n \"modelName\",\n \"model_name\",\n \"modelId\",\n \"model_id\",\n \"deploymentName\",\n \"deployment_name\",\n ]) {\n if (key in identifyingParams) {\n return String(identifyingParams[key]);\n }\n }\n }\n }\n\n // Fallback to direct model attributes\n return (llm as any).model || (llm as any).modelName || llm.constructor.name;\n}\n\nexport function extractModelInfo(llm: BaseLanguageModel): [string, string] {\n return [getModelProvider(llm), getModelName(llm)];\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { SystemMessage } from \"langchain\";\n\nfunction generateToolDescriptions(\n tools: StructuredToolInterface[],\n disallowedTools?: string[]\n): string[] {\n const disallowedSet = new Set(disallowedTools ?? []);\n const descriptions: string[] = [];\n\n for (const tool of tools) {\n if (disallowedSet.has(tool.name)) continue;\n const escaped = tool.description.replace(/\\{/g, \"{{\").replace(/\\}/g, \"}}\");\n descriptions.push(`- ${tool.name}: ${escaped}`);\n }\n\n return descriptions;\n}\n\nfunction buildSystemPromptContent(\n template: string,\n toolDescriptionLines: string[],\n additionalInstructions?: string\n): string {\n const block = toolDescriptionLines.join(\"\\n\");\n\n let content: string;\n if (template.includes(\"{tool_descriptions}\")) {\n content = template.replace(\"{tool_descriptions}\", block);\n } else {\n console.warn(\n \"`{tool_descriptions}` placeholder not found; appending at end.\"\n );\n content = `${template}\\n\\nAvailable tools:\\n${block}`;\n }\n\n if (additionalInstructions) {\n content += `\\n\\n${additionalInstructions}`;\n }\n\n return content;\n}\n\nexport function createSystemMessage(\n tools: StructuredToolInterface[],\n systemPromptTemplate: string,\n serverManagerTemplate: string,\n useServerManager: boolean,\n disallowedTools?: string[],\n userProvidedPrompt?: string,\n additionalInstructions?: string\n): SystemMessage {\n if (userProvidedPrompt) {\n return new SystemMessage({ content: userProvidedPrompt });\n }\n\n const template = useServerManager\n ? serverManagerTemplate\n : systemPromptTemplate;\n\n const toolLines = generateToolDescriptions(tools, disallowedTools);\n const finalContent = buildSystemPromptContent(\n template,\n toolLines,\n additionalInstructions\n );\n\n return new SystemMessage({ content: finalContent });\n}\n","export const DEFAULT_SYSTEM_PROMPT_TEMPLATE = `You are a helpful AI assistant.\nYou have access to the following tools:\n\n{tool_descriptions}\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of the available tools\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question`;\n\nexport const SERVER_MANAGER_SYSTEM_PROMPT_TEMPLATE = `You are a helpful assistant designed to interact with MCP\n (Model Context Protocol) servers. You can manage connections to different servers and use the tools\n provided by the currently active server.\n\nImportant: The available tools change depending on which server is active.\nIf a request requires tools not listed below (e.g., file operations, web browsing,\n image manipulation), you MUST first connect to the appropriate server using\n 'connect_to_mcp_server'.\nUse 'list_mcp_servers' to find the relevant server if you are unsure.\nOnly after successfully connecting and seeing the new tools listed in\nthe response should you attempt to use those server-specific tools.\nBefore attempting a task that requires specific tools, you should\nensure you are connected to the correct server and aware of its\navailable tools. If unsure, use 'list_mcp_servers' to see options\nor 'get_active_mcp_server' to check the current connection.\n\nWhen you connect to a server using 'connect_to_mcp_server',\n you will be informed about the new tools that become available.\nYou can then use these server-specific tools in subsequent steps.\n\nHere are the tools *currently* available to you (this list includes server management tools and will\n change when you connect to a server):\n{tool_descriptions}\n`;\n","/** Remote execution support for hosted MCP agents. */\n\nimport type { ZodSchema } from \"zod\";\nimport { toJSONSchema } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\nimport type { RunOptions } from \"./run_options.js\";\nimport type { BaseMessage } from \"./types.js\";\n\n// API endpoint constants\nconst API_CHATS_ENDPOINT = \"/api/v1/chats\";\nconst API_CHAT_EXECUTE_ENDPOINT = \"/api/v1/chats/{chat_id}/execute\";\n\n/**\n * Helper function to normalize run options for remote agent\n */\nfunction normalizeRemoteRunOptions<T>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n): {\n query: string;\n maxSteps?: number;\n manageConnector?: boolean;\n externalHistory?: BaseMessage[];\n outputSchema?: ZodSchema<T>;\n} {\n // Check if first argument is an options object\n if (typeof queryOrOptions === \"object\" && queryOrOptions !== null) {\n const options = queryOrOptions as RunOptions<T>;\n return {\n query: options.prompt ?? \"\",\n maxSteps: options.maxSteps,\n manageConnector: options.manageConnector,\n externalHistory: options.externalHistory,\n outputSchema: options.schema,\n };\n }\n\n // Old-style positional arguments\n return {\n query: queryOrOptions as string,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n };\n}\n\n/** Configures a {@link RemoteAgent}. */\nexport interface RemoteAgentOptions {\n /** Hosted agent identifier. */\n agentId: string;\n /** API key. Defaults to `MCP_USE_API_KEY`. */\n apiKey?: string;\n /** API origin. Defaults to `https://cloud.manufact.com`. */\n baseUrl?: string;\n}\n\n/** Executes a hosted MCP agent through the mcp-use remote API. */\nexport class RemoteAgent {\n private agentId: string;\n private apiKey: string;\n private baseUrl: string;\n private chatId: string | null = null;\n\n /**\n * @param options - Hosted agent identifier and API connection settings.\n * @throws Error if no API key is supplied or available from\n * `MCP_USE_API_KEY`.\n */\n constructor(options: RemoteAgentOptions) {\n this.agentId = options.agentId;\n this.baseUrl = options.baseUrl ?? \"https://cloud.manufact.com\";\n\n // Handle API key validation\n const apiKey =\n options.apiKey ??\n (typeof process !== \"undefined\" && process.env?.MCP_USE_API_KEY);\n if (!apiKey) {\n throw new Error(\n \"API key is required for remote execution. \" +\n \"Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. \" +\n \"You can get an API key from https://cloud.manufact.com\"\n );\n }\n this.apiKey = apiKey;\n }\n\n private pydanticToJsonSchema<T>(schema: ZodSchema<T>): any {\n /**\n * Convert a Zod schema to JSON schema for API transmission.\n */\n return toJSONSchema(schema);\n }\n\n private parseStructuredResponse<T>(\n responseData: any,\n outputSchema: ZodSchema<T>\n ): T {\n /**\n * Parse the API response into the structured output format.\n */\n let resultData: any;\n\n // Handle different response formats\n if (typeof responseData === \"object\" && responseData !== null) {\n if (\"result\" in responseData) {\n const outerResult = responseData.result;\n // Check if this is a nested result structure (agent execution response)\n if (\n typeof outerResult === \"object\" &&\n outerResult !== null &&\n \"result\" in outerResult\n ) {\n // Extract the actual structured output from the nested result\n resultData = outerResult.result;\n } else {\n // Use the outer result directly\n resultData = outerResult;\n }\n } else {\n resultData = responseData;\n }\n } else if (typeof responseData === \"string\") {\n try {\n resultData = JSON.parse(responseData);\n } catch {\n // If it's not valid JSON, try to create the model from the string content\n resultData = { content: responseData };\n }\n } else {\n resultData = responseData;\n }\n\n // Parse into the Zod schema\n try {\n return outputSchema.parse(resultData);\n } catch (e) {\n logger.warn(`Failed to parse structured output: ${e}`);\n // Fallback: try to parse it as raw content if the schema has a content field\n const schemaShape = (outputSchema as any)._def?.shape();\n if (schemaShape && \"content\" in schemaShape) {\n return outputSchema.parse({ content: String(resultData) });\n }\n throw e;\n }\n }\n\n private async createChatSession(): Promise<string> {\n /**\n * Create a persistent chat session for the agent.\n */\n const chatPayload = {\n title: `Remote Agent Session - ${this.agentId}`,\n agent_id: this.agentId,\n type: \"agent_execution\",\n };\n\n const headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n };\n const chatUrl = `${this.baseUrl}${API_CHATS_ENDPOINT}`;\n\n logger.debug(`📝 Creating chat session for agent ${this.agentId}`);\n\n try {\n const response = await fetch(chatUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify(chatPayload),\n });\n\n if (!response.ok) {\n const responseText = await response.text();\n const statusCode = response.status;\n\n if (statusCode === 404) {\n throw new Error(\n `Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. ` +\n \"Please verify the agent ID and ensure it exists in your account.\"\n );\n }\n throw new Error(\n `Failed to create chat session: ${statusCode} - ${responseText}`\n );\n }\n\n const chatData = await response.json();\n const chatId = chatData.id;\n logger.debug(`✅ Chat session created: ${chatId}`);\n return chatId;\n } catch (e) {\n if (e instanceof Error) {\n throw new TypeError(`Failed to create chat session: ${e.message}`);\n }\n throw new Error(`Failed to create chat session: ${String(e)}`);\n }\n }\n\n /**\n * Runs the remote agent and returns its final text.\n *\n * @param options - Input and per-run execution settings.\n * @returns Final agent text.\n */\n public async run(options: RunOptions): Promise<string>;\n\n /**\n * Runs the remote agent and parses its result with `options.schema`.\n *\n * @param options - Input, schema, and per-run execution settings.\n * @returns The schema-validated result.\n */\n public async run<T>(options: RunOptions<T>): Promise<T>;\n\n /**\n * Runs the remote agent and returns a promise for the final result.\n * @deprecated Use the options object instead: `run({ prompt, maxSteps, ... })`.\n */\n public async run<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): Promise<T>;\n\n public async run<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): Promise<T> {\n /**\n * Run a query on the remote agent.\n */\n // Normalize input to internal parameters\n const {\n query,\n maxSteps: steps,\n externalHistory: history,\n outputSchema: schema,\n } = normalizeRemoteRunOptions(\n queryOrOptions,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema\n );\n\n if (history !== undefined) {\n logger.warn(\"External history is not yet supported for remote execution\");\n }\n\n try {\n logger.debug(`🌐 Executing query on remote agent ${this.agentId}`);\n\n // Step 1: Create a chat session for this agent (only if we don't have one)\n if (this.chatId === null) {\n this.chatId = await this.createChatSession();\n }\n\n const chatId = this.chatId;\n\n // Step 2: Execute the agent within the chat context\n const executionPayload: any = {\n query,\n max_steps: steps ?? 10,\n };\n\n // Add structured output schema if provided\n if (schema) {\n executionPayload.output_schema = this.pydanticToJsonSchema(schema);\n logger.debug(`🔧 Using structured output with schema`);\n }\n\n const headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n };\n const executionUrl = `${this.baseUrl}${API_CHAT_EXECUTE_ENDPOINT.replace(\"{chat_id}\", chatId)}`;\n logger.debug(`🚀 Executing agent in chat ${chatId}`);\n\n const response = await fetch(executionUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify(executionPayload),\n signal: AbortSignal.timeout(300000), // 5 minute timeout\n });\n\n if (!response.ok) {\n const responseText = await response.text();\n const statusCode = response.status;\n\n // Provide specific error messages based on status code\n if (statusCode === 401) {\n logger.error(`❌ Authentication failed: ${responseText}`);\n throw new Error(\n \"Authentication failed: Invalid or missing API key. \" +\n \"Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.\"\n );\n } else if (statusCode === 403) {\n logger.error(`❌ Access forbidden: ${responseText}`);\n throw new Error(\n `Access denied: You don't have permission to execute agent '${this.agentId}'. ` +\n \"Check if the agent exists and you have the necessary permissions.\"\n );\n } else if (statusCode === 404) {\n logger.error(`❌ Agent not found: ${responseText}`);\n throw new Error(\n `Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. ` +\n \"Please verify the agent ID and ensure it exists in your account.\"\n );\n } else if (statusCode === 422) {\n logger.error(`❌ Validation error: ${responseText}`);\n throw new Error(\n `Request validation failed: ${responseText}. ` +\n \"Please check your query parameters and output schema format.\"\n );\n } else if (statusCode === 500) {\n logger.error(`❌ Server error: ${responseText}`);\n throw new Error(\n \"Internal server error occurred during agent execution. \" +\n \"Please try again later or contact support if the issue persists.\"\n );\n } else {\n logger.error(\n `❌ Remote execution failed with status ${statusCode}: ${responseText}`\n );\n throw new Error(\n `Remote agent execution failed: ${statusCode} - ${responseText}`\n );\n }\n }\n\n const result = await response.json();\n logger.debug(`🔧 Response: ${JSON.stringify(result)}`);\n logger.debug(\"✅ Remote execution completed successfully\");\n\n // Check for error responses (even with 200 status)\n if (typeof result === \"object\" && result !== null) {\n // Check for actual error conditions (not just presence of error field)\n if (result.status === \"error\" || result.error !== null) {\n const errorMsg = result.error ?? String(result);\n logger.error(`❌ Remote agent execution failed: ${errorMsg}`);\n throw new Error(`Remote agent execution failed: ${errorMsg}`);\n }\n\n // Check if the response indicates agent initialization failure\n if (String(result).includes(\"failed to initialize\")) {\n logger.error(`❌ Agent initialization failed: ${result}`);\n throw new Error(\n \"Agent initialization failed on remote server. \" +\n \"This usually indicates:\\n\" +\n \"• Invalid agent configuration (LLM model, system prompt)\\n\" +\n \"• Missing or invalid MCP server configurations\\n\" +\n \"• Network connectivity issues with MCP servers\\n\" +\n \"• Missing environment variables or credentials\\n\" +\n `Raw error: ${result}`\n );\n }\n }\n\n // Handle structured output\n if (schema) {\n return this.parseStructuredResponse(result, schema);\n }\n\n // Regular string output\n if (typeof result === \"object\" && result !== null && \"result\" in result) {\n return result.result as T;\n } else if (typeof result === \"string\") {\n return result as T;\n } else {\n return String(result) as T;\n }\n } catch (e) {\n if (e instanceof Error) {\n // Check for specific error types\n if (e.name === \"AbortError\") {\n logger.error(`❌ Remote execution timed out: ${e}`);\n throw new Error(\n \"Remote agent execution timed out. The server may be overloaded or the query is taking too long to \" +\n \"process. Try again or use a simpler query.\"\n );\n }\n logger.error(`❌ Remote execution error: ${e}`);\n throw new Error(`Remote agent execution failed: ${e.message}`);\n }\n logger.error(`❌ Remote execution error: ${e}`);\n throw new Error(`Remote agent execution failed: ${String(e)}`);\n }\n }\n\n /**\n * Runs the remote agent through an async-generator interface.\n *\n * The current remote API does not emit intermediate values. Read the\n * generator's return value for the final result.\n *\n * @param options - Input and per-run execution settings.\n * @returns An async generator whose return value is the final text.\n */\n public stream(options: RunOptions): AsyncGenerator<any, string, void>;\n\n /**\n * Runs structured remote execution through an async-generator interface.\n *\n * @param options - Input, schema, and per-run execution settings.\n * @returns An async generator whose return value is schema validated.\n */\n public stream<T>(options: RunOptions<T>): AsyncGenerator<any, T, void>;\n\n /**\n * Streams the remote agent execution.\n * @deprecated Use the options object instead: `stream({ prompt, maxSteps, ... })`.\n */\n public stream<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): AsyncGenerator<any, T, void>;\n\n // eslint-disable-next-line require-yield\n public async *stream<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): AsyncGenerator<any, T, void> {\n /**\n * Stream implementation for remote agent - currently just wraps run.\n * In the future, this could be enhanced to support actual streaming from the API.\n */\n const result = await this.run(\n queryOrOptions as any,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema\n );\n return result;\n }\n\n /** Releases local remote-agent state. */\n public async close(): Promise<void> {\n /**\n * Close the remote agent connection.\n */\n logger.debug(\"🔌 Remote agent client closed\");\n // In the future, we might want to delete the chat session here\n // if (this.chatId) {\n // await this.deleteChatSession(this.chatId)\n // }\n }\n}\n","import type { LanguageModel } from \"../types.js\";\nimport { logger } from \"@mcp-use/client\";\n\n/** Constructor settings forwarded to a dynamically loaded LangChain model. */\nexport interface LLMConfig {\n /** Provider API key. When omitted, the provider environment variable is used. */\n apiKey?: string;\n /** Sampling temperature. */\n temperature?: number;\n /** Maximum number of output tokens. */\n maxTokens?: number;\n /** Nucleus sampling probability. */\n topP?: number;\n /** Additional provider-specific constructor settings. */\n [key: string]: any; // Allow additional provider-specific config\n}\n\n/** LangChain providers supported by {@link createLLMFromString}. */\nexport type LLMProvider = \"openai\" | \"anthropic\" | \"google\" | \"groq\";\n\n/** Parsed components of a LangChain model identifier. */\nexport interface ParsedLLMString {\n /** Normalized provider name. */\n provider: LLMProvider;\n /** Provider-specific model name. */\n model: string;\n}\n\n/**\n * Provider configuration mapping\n */\nconst PROVIDER_CONFIG = {\n openai: {\n package: \"@langchain/openai\",\n className: \"ChatOpenAI\",\n envVars: [\"OPENAI_API_KEY\"],\n defaultModel: \"gpt-4o\",\n },\n anthropic: {\n package: \"@langchain/anthropic\",\n className: \"ChatAnthropic\",\n envVars: [\"ANTHROPIC_API_KEY\"],\n defaultModel: \"claude-sonnet-4-6\",\n },\n google: {\n package: \"@langchain/google-genai\",\n className: \"ChatGoogleGenerativeAI\",\n envVars: [\"GOOGLE_API_KEY\", \"GOOGLE_GENERATIVE_AI_API_KEY\"],\n defaultModel: \"gemini-pro\",\n },\n groq: {\n package: \"@langchain/groq\",\n className: \"ChatGroq\",\n envVars: [\"GROQ_API_KEY\"],\n defaultModel: \"llama-3.1-70b-versatile\",\n },\n} as const;\n\n/**\n * Parses an LLM identifier in `\"provider/model\"` format.\n *\n * @param llmString - Provider and model separated by one slash.\n * @returns The normalized provider and model.\n * @throws Error if the format is invalid or the provider is unsupported.\n */\nexport function parseLLMString(llmString: string): ParsedLLMString {\n const parts = llmString.split(\"/\");\n\n if (parts.length !== 2) {\n throw new Error(\n `Invalid LLM string format. Expected 'provider/model', got '${llmString}'. ` +\n `Examples: 'openai/gpt-4', 'anthropic/claude-sonnet-4-6', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`\n );\n }\n\n const [provider, model] = parts;\n\n if (!provider || !model) {\n throw new Error(\n `Invalid LLM string format. Both provider and model must be non-empty. Got '${llmString}'`\n );\n }\n\n const normalizedProvider = provider.toLowerCase() as LLMProvider;\n\n if (!(normalizedProvider in PROVIDER_CONFIG)) {\n const supportedProviders = Object.keys(PROVIDER_CONFIG).join(\", \");\n throw new Error(\n `Unsupported LLM provider '${provider}'. Supported providers: ${supportedProviders}`\n );\n }\n\n return { provider: normalizedProvider, model };\n}\n\n/**\n * Determine the API key to use for a given provider by checking `llmConfig` then provider-specific environment variables.\n *\n * @param provider - The LLM provider identifier (e.g., \"openai\").\n * @param config - Optional LLM configuration; if `config.apiKey` is present it is returned.\n * @returns The resolved API key string.\n * @throws Error if no API key is found in `config.apiKey` or any of the provider's expected environment variables.\n */\nfunction getAPIKey(provider: LLMProvider, config?: LLMConfig): string {\n // First check if provided in config\n if (config?.apiKey) {\n return config.apiKey;\n }\n\n // Get provider config for error message\n const providerConfig = PROVIDER_CONFIG[provider];\n\n // Check environment variables (only if process.env is available)\n if (typeof process !== \"undefined\" && process.env) {\n for (const envVar of providerConfig.envVars) {\n const apiKey = process.env[envVar];\n if (apiKey) {\n logger.debug(\n `Using API key from environment variable ${envVar} for provider ${provider}`\n );\n return apiKey;\n }\n }\n }\n\n // No API key found\n const envVarsStr = providerConfig.envVars.join(\" or \");\n throw new Error(\n `API key not found for provider '${provider}'. ` +\n `Set ${envVarsStr} environment variable or pass apiKey in llmConfig. ` +\n `Example: new MCPAgent({ llm: '${provider}/model', llmConfig: { apiKey: 'your-key' } })`\n );\n}\n\n/**\n * Dynamically imports and instantiates a LangChain chat model.\n *\n * @param llmString - LLM specification in format \"provider/model\" (e.g., \"openai/gpt-4\")\n * @param config - Optional configuration for the LLM (apiKey, temperature, etc.)\n * @returns The instantiated LangChain model.\n * @throws Error if credentials are unavailable, the provider package is not\n * installed, or the model cannot be constructed.\n *\n * @example\n * ```ts\n * const llm = await createLLMFromString('openai/gpt-4', { temperature: 0.7 });\n * ```\n *\n * @example\n * ```ts\n * const llm = await createLLMFromString('anthropic/claude-sonnet-4-6');\n * ```\n */\nexport async function createLLMFromString(\n llmString: string,\n config?: LLMConfig\n): Promise<LanguageModel> {\n logger.debug(`Creating LLM from string: ${llmString}`);\n\n const { provider, model } = parseLLMString(llmString);\n const providerConfig = PROVIDER_CONFIG[provider];\n\n // Get API key\n const apiKey = getAPIKey(provider, config);\n\n // Dynamically import the provider package\n let providerModule: any;\n try {\n logger.debug(`Importing package ${providerConfig.package}...`);\n providerModule = await import(providerConfig.package);\n } catch (error: any) {\n // Check if it's a module not found error\n if (\n error?.code === \"MODULE_NOT_FOUND\" ||\n error?.message?.includes(\"Cannot find module\") ||\n error?.message?.includes(\"Cannot find package\")\n ) {\n throw new Error(\n `Package '${providerConfig.package}' is not installed. ` +\n `Install it with: npm install ${providerConfig.package}, pnpm add ${providerConfig.package}, or bun add ${providerConfig.package}`\n );\n }\n throw new Error(\n `Failed to import ${providerConfig.package}: ${error?.message || error}`\n );\n }\n\n // Get the class from the module\n const LLMClass = providerModule[providerConfig.className];\n if (!LLMClass) {\n throw new Error(\n `Could not find ${providerConfig.className} in package ${providerConfig.package}. ` +\n `This might be a version compatibility issue.`\n );\n }\n\n // Build configuration object\n const llmConfig: Record<string, any> = {\n model,\n apiKey,\n ...config,\n };\n\n // Remove apiKey from the spread to avoid duplication\n if (config?.apiKey) {\n delete llmConfig.apiKey;\n llmConfig.apiKey = apiKey;\n }\n\n // Provider-specific configuration mapping\n if (provider === \"anthropic\") {\n // Anthropic uses 'model' parameter\n llmConfig.model = model;\n } else if (provider === \"google\") {\n // Google uses 'model' parameter\n llmConfig.model = model;\n } else if (provider === \"openai\") {\n // OpenAI uses 'model' parameter\n llmConfig.model = model;\n } else if (provider === \"groq\") {\n // Groq uses 'model' parameter\n llmConfig.model = model;\n }\n\n // Instantiate the LLM\n try {\n const llmInstance = new LLMClass(llmConfig);\n logger.debug(`Successfully created ${provider} LLM with model ${model}`);\n return llmInstance as LanguageModel;\n } catch (error: any) {\n throw new Error(\n `Failed to instantiate ${providerConfig.className} with model '${model}': ${error?.message || error}`\n );\n }\n}\n\n/**\n * Tests whether an LLM identifier has a supported provider and valid format.\n *\n * @param llmString - Candidate `\"provider/model\"` identifier.\n * @returns `true` when {@link parseLLMString} accepts the identifier.\n */\nexport function isValidLLMString(llmString: string): boolean {\n try {\n parseLLMString(llmString);\n return true;\n } catch {\n return false;\n }\n}\n\n/** @returns A new array containing every supported LangChain provider. */\nexport function getSupportedProviders(): LLMProvider[] {\n return Object.keys(PROVIDER_CONFIG) as LLMProvider[];\n}\n","/**\n * Prompt templates for MCP agents.\n *\n * This module provides prompt templates to guide agents on how to use\n * MCP tools, including code execution mode.\n */\n\n// ponytail: CODE_MODE_AGENT_PROMPT may be absent on older @mcp-use/client builds\nconst CODE_MODE_PROMPT =\n \"Use code execution mode to discover and call MCP tools programmatically.\";\n\n/**\n * Built-in prompt fragments for agent features.\n *\n * `CODE_MODE` instructs a model to discover and invoke MCP tools through the\n * code execution interface.\n */\nexport const PROMPTS = {\n /** Instruction used to enable code-based MCP tool discovery and calls. */\n CODE_MODE: CODE_MODE_PROMPT,\n} as const;\n","/**\n * AI SDK Integration Utilities\n *\n * Utility functions for integrating MCPAgent's streamEvents with Vercel AI SDK.\n * These utilities help convert stream events to AI SDK compatible formats.\n */\n\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\n\n/**\n * Converts LangChain model stream events to text chunks.\n *\n * @param streamEvents - Events returned by the LangChain agent's\n * `streamEvents` method.\n * @returns An async generator containing only model text chunks.\n */\nexport async function* streamEventsToAISDK(\n streamEvents: AsyncGenerator<StreamEvent, void, void>\n): AsyncGenerator<string, void, void> {\n for await (const event of streamEvents) {\n if (event.event === \"on_chat_model_stream\" && event.data?.chunk?.text) {\n const textContent = event.data.chunk.text;\n if (typeof textContent === \"string\" && textContent.length > 0) {\n yield textContent;\n }\n }\n }\n}\n\n/**\n * Wraps an async text generator in a web `ReadableStream`.\n *\n * @param generator - Async text generator to consume.\n * @returns A stream that enqueues each generated string and forwards errors.\n */\nexport function createReadableStreamFromGenerator(\n generator: AsyncGenerator<string, void, void>\n): ReadableStream<string> {\n return new ReadableStream({\n async start(controller) {\n try {\n for await (const chunk of generator) {\n controller.enqueue(chunk);\n }\n controller.close();\n } catch (error) {\n controller.error(error);\n }\n },\n });\n}\n\n/**\n * Converts LangChain events to text and inserts tool lifecycle messages.\n *\n * @param streamEvents - Events returned by the LangChain agent's\n * `streamEvents` method.\n * @returns Model text interleaved with human-readable tool start/end messages.\n */\nexport async function* streamEventsToAISDKWithTools(\n streamEvents: AsyncGenerator<StreamEvent, void, void>\n): AsyncGenerator<string, void, void> {\n for await (const event of streamEvents) {\n switch (event.event) {\n case \"on_chat_model_stream\":\n if (event.data?.chunk?.text) {\n const textContent = event.data.chunk.text;\n if (typeof textContent === \"string\" && textContent.length > 0) {\n yield textContent;\n }\n }\n break;\n\n case \"on_tool_start\":\n yield `\\n🔧 Using tool: ${event.name}\\n`;\n break;\n\n case \"on_tool_end\":\n yield `\\n✅ Tool completed: ${event.name}\\n`;\n break;\n default:\n break;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,SAAS,UAAAA,eAAc;AAQvB,SAAS,UAAU,KAAiC;AAClD,MA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KAAK;AACH,cAAM;AAAA,yBAAuB,MAAM,IAAI;AAAA;AACvC;AAAA,MACF;AACE;AAAA,IACJ;AAAA,EACF;AACF;","names":["logger","config","agentId","metadata","metadataProvider","tagsProvider","execResult","isError","title","SystemMessage","toJSONSchema","logger","logger","i","fallback","logger","logger","z","z","StructuredTool","z","logger","z","logger","z","logger","z","logger","z","logger","z","z","logger","logger","langfuseHandler","langfuseInitPromise","initializeLangfuse","logger","logger","logger","SystemMessage","toJSONSchema"]}
|
|
1
|
+
{"version":3,"sources":["../src/observability/langfuse.ts","../src/agents/display.ts","../src/agents/mcp_agent_langchain.ts","../src/adapters/langchain_adapter.ts","../src/adapters/base.ts","../src/managers/server_manager.ts","../src/managers/tools/acquire_active_mcp_server.ts","../src/managers/tools/base.ts","../src/managers/tools/add_server_from_config.ts","../src/managers/tools/connect_mcp_server.ts","../src/managers/tools/list_mcp_servers.ts","../src/managers/tools/release_mcp_server_connection.ts","../src/observability/index.ts","../src/observability/manager.ts","../src/version.ts","../src/telemetry/utils.ts","../src/agents/prompts/system_prompt_builder.ts","../src/agents/prompts/templates.ts","../src/agents/remote.ts","../src/agents/utils/llm_provider.ts","../src/agents/prompts/index.ts","../src/agents/utils/ai_sdk.ts"],"sourcesContent":["/**\n * Langfuse observability integration for MCP-use.\n *\n * This module provides automatic instrumentation and callback handler\n * for Langfuse observability platform.\n *\n * Note: This module expects environment variables to be loaded before import.\n * Users should load their environment variables using their preferred method\n * (e.g., dotenv, direct process.env assignment, or system environment).\n */\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"./types.d.ts\" />\n\nimport type { BaseCallbackHandler } from \"@langchain/core/callbacks/base\";\nimport { logger } from \"@mcp-use/client\";\n\n/**\n * Retrieve the value of an environment variable when `process.env` is available.\n *\n * @param key - The environment variable name to look up\n * @returns The variable's value if present, `undefined` otherwise\n */\nfunction getEnvVar(key: string): string | undefined {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[key];\n }\n return undefined;\n}\n\n// Check if Langfuse is disabled via environment variable\nconst langfuseDisabled =\n getEnvVar(\"MCP_USE_LANGFUSE\")?.toLowerCase() === \"false\";\n\n// Initialize variables - using const with object to avoid linter issues with mutable exports\nconst langfuseState = {\n handler: null as BaseCallbackHandler | null,\n client: null as any,\n initPromise: null as Promise<void> | null,\n};\n\n/**\n * Initializes Langfuse observability for the application and installs a callback handler that augments traces with optional agent metadata and tags.\n *\n * This will attempt to dynamically load the Langfuse LangChain integration and, if available, create and store a wrapped callback handler (and optionally a Langfuse client) on the module state so tracing can be used elsewhere in the application.\n *\n * @param agentId - Optional identifier for the agent to include in traces\n * @param metadata - Optional static metadata to attach to traces; merged with dynamic metadata if a provider is supplied\n * @param metadataProvider - Optional function that returns dynamic metadata to attach to traces at runtime\n * @param tagsProvider - Optional function that returns an array of tags to attach to traces at runtime\n */\nasync function initializeLangfuse(\n agentId?: string,\n metadata?: Record<string, any>,\n metadataProvider?: () => Record<string, any>,\n tagsProvider?: () => string[]\n): Promise<void> {\n try {\n // Dynamically import to avoid errors if package not installed\n const langfuseModule = await import(\"@langfuse/langchain\").catch(\n () => null\n );\n if (!langfuseModule) {\n logger.debug(\n \"Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain\"\n );\n return;\n }\n\n const { CallbackHandler } = langfuseModule as any;\n // Create a custom CallbackHandler wrapper to add logging and custom metadata\n class LoggingCallbackHandler extends CallbackHandler {\n private agentId?: string;\n private metadata?: Record<string, any>;\n private metadataProvider?: () => Record<string, any>;\n private tagsProvider?: () => string[];\n private verbose: boolean;\n\n constructor(\n config?: any,\n agentId?: string,\n metadata?: Record<string, any>,\n metadataProvider?: () => Record<string, any>,\n tagsProvider?: () => string[]\n ) {\n super(config);\n this.agentId = agentId;\n this.metadata = metadata;\n this.metadataProvider = metadataProvider;\n this.tagsProvider = tagsProvider;\n this.verbose = config?.verbose ?? false;\n }\n\n // Override to add custom metadata to traces\n async handleChainStart(\n chain: any,\n inputs: any,\n runId?: string,\n parentRunId?: string,\n tags?: string[],\n metadata?: any,\n name?: string,\n kwargs?: any\n ): Promise<void> {\n logger.debug(\"Langfuse: Chain start intercepted\");\n\n // Add custom tags and metadata\n const customTags = this.getCustomTags();\n const metadataToAdd = this.getMetadata();\n\n // Merge with existing tags and metadata\n const enhancedTags = [...(tags || []), ...customTags];\n const enhancedMetadata = { ...(metadata || {}), ...metadataToAdd };\n\n if (this.verbose) {\n logger.debug(\n `Langfuse: Chain start with custom tags: ${JSON.stringify(enhancedTags)}`\n );\n logger.debug(\n `Langfuse: Chain start with metadata: ${JSON.stringify(enhancedMetadata)}`\n );\n }\n\n return super.handleChainStart(\n chain,\n inputs,\n runId,\n parentRunId,\n enhancedTags,\n enhancedMetadata,\n name,\n kwargs\n );\n }\n\n // Get custom tags based on environment and agent configuration\n private getCustomTags(): string[] {\n const tags: string[] = [];\n\n // Add environment tag\n const env = this.getEnvironmentTag();\n if (env) {\n tags.push(`env:${env}`);\n }\n\n // Add agent ID tag if available\n if (this.agentId) {\n tags.push(`agent_id:${this.agentId}`);\n }\n\n // Add tags from provider if available\n if (this.tagsProvider) {\n const providerTags = this.tagsProvider();\n if (providerTags && providerTags.length > 0) {\n tags.push(...providerTags);\n }\n }\n\n return tags;\n }\n\n // Get metadata\n private getMetadata(): any {\n const metadata: any = {};\n\n // Add environment metadata\n const env = this.getEnvironmentTag();\n if (env) {\n metadata.env = env;\n }\n\n // Add agent ID metadata if available\n if (this.agentId) {\n metadata.agent_id = this.agentId;\n }\n\n // Add static metadata if provided\n if (this.metadata) {\n Object.assign(metadata, this.metadata);\n }\n\n // Add dynamic metadata from provider if available\n if (this.metadataProvider) {\n const dynamicMetadata = this.metadataProvider();\n if (dynamicMetadata) {\n Object.assign(metadata, dynamicMetadata);\n }\n }\n\n return metadata;\n }\n\n // Determine environment tag based on MCP_USE_AGENT_ENV\n private getEnvironmentTag(): string | null {\n const agentEnv = getEnvVar(\"MCP_USE_AGENT_ENV\");\n if (!agentEnv) {\n // Default to 'unknown' if environment is not explicitly set\n return \"unknown\";\n }\n\n const envLower = agentEnv.toLowerCase();\n if (envLower === \"local\" || envLower === \"development\") {\n return \"local\";\n } else if (envLower === \"production\" || envLower === \"prod\") {\n return \"production\";\n } else if (envLower === \"staging\" || envLower === \"stage\") {\n return \"staging\";\n } else if (envLower === \"hosted\" || envLower === \"cloud\") {\n return \"hosted\";\n }\n\n // For any other values, use the value as-is but sanitized\n return envLower.replace(/[^a-z0-9_-]/g, \"_\");\n }\n\n async handleLLMStart(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: LLM start intercepted\");\n if (this.verbose) {\n logger.debug(`Langfuse: LLM start args: ${JSON.stringify(args)}`);\n }\n return super.handleLLMStart(...args);\n }\n\n async handleToolStart(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: Tool start intercepted\");\n if (this.verbose) {\n logger.debug(`Langfuse: Tool start args: ${JSON.stringify(args)}`);\n }\n return super.handleToolStart(...args);\n }\n\n async handleRetrieverStart(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: Retriever start intercepted\");\n if (this.verbose) {\n logger.debug(\n `Langfuse: Retriever start args: ${JSON.stringify(args)}`\n );\n }\n return super.handleRetrieverStart(...args);\n }\n\n async handleAgentAction(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: Agent action intercepted\");\n if (this.verbose) {\n logger.debug(`Langfuse: Agent action args: ${JSON.stringify(args)}`);\n }\n return super.handleAgentAction(...args);\n }\n\n async handleAgentEnd(...args: any[]): Promise<void> {\n logger.debug(\"Langfuse: Agent end intercepted\");\n if (this.verbose) {\n logger.debug(`Langfuse: Agent end args: ${JSON.stringify(args)}`);\n }\n return super.handleAgentEnd(...args);\n }\n }\n\n // Create the handler with configuration\n // Get initial metadata and tags for handler initialization\n const initialMetadata =\n metadata || (metadataProvider ? metadataProvider() : {});\n const initialTags = tagsProvider ? tagsProvider() : [];\n\n const config = {\n publicKey: getEnvVar(\"LANGFUSE_PUBLIC_KEY\"),\n secretKey: getEnvVar(\"LANGFUSE_SECRET_KEY\"),\n baseUrl:\n getEnvVar(\"LANGFUSE_HOST\") ||\n getEnvVar(\"LANGFUSE_BASEURL\") ||\n \"https://cloud.langfuse.com\",\n flushAt: Number.parseInt(getEnvVar(\"LANGFUSE_FLUSH_AT\") || \"15\"),\n flushInterval: Number.parseInt(\n getEnvVar(\"LANGFUSE_FLUSH_INTERVAL\") || \"10000\"\n ),\n release: getEnvVar(\"LANGFUSE_RELEASE\"),\n requestTimeout: Number.parseInt(\n getEnvVar(\"LANGFUSE_REQUEST_TIMEOUT\") || \"10000\"\n ),\n enabled: getEnvVar(\"LANGFUSE_ENABLED\") !== \"false\",\n // Set trace name - can be customized via metadata.trace_name or defaults to 'mcp-use-agent'\n traceName:\n initialMetadata.trace_name ||\n getEnvVar(\"LANGFUSE_TRACE_NAME\") ||\n \"mcp-use-agent\",\n // Pass sessionId, userId, and tags to the handler\n sessionId: initialMetadata.session_id || undefined,\n userId: initialMetadata.user_id || undefined,\n tags: initialTags.length > 0 ? initialTags : undefined,\n metadata: initialMetadata || undefined,\n };\n\n logger.debug(\n \"Langfuse handler config:\",\n JSON.stringify(\n {\n traceName: config.traceName,\n sessionId: config.sessionId,\n userId: config.userId,\n tags: config.tags,\n },\n null,\n 2\n )\n );\n\n langfuseState.handler = new LoggingCallbackHandler(\n config,\n agentId,\n metadata,\n metadataProvider,\n tagsProvider\n ) as unknown as BaseCallbackHandler;\n logger.debug(\n \"Langfuse observability initialized successfully with logging enabled\"\n );\n\n // Also initialize the client for direct usage if needed\n try {\n const langfuseCore = await import(\"langfuse\").catch(() => null);\n if (langfuseCore) {\n const { Langfuse } = langfuseCore as any;\n langfuseState.client = new Langfuse({\n publicKey: getEnvVar(\"LANGFUSE_PUBLIC_KEY\"),\n secretKey: getEnvVar(\"LANGFUSE_SECRET_KEY\"),\n baseUrl: getEnvVar(\"LANGFUSE_HOST\") || \"https://cloud.langfuse.com\",\n });\n logger.debug(\"Langfuse client initialized\");\n }\n } catch (error) {\n logger.debug(`Langfuse client initialization failed: ${error}`);\n }\n } catch (error) {\n logger.debug(`Langfuse initialization error: ${error}`);\n }\n}\n\n// Only initialize if not disabled and required keys are present\nif (langfuseDisabled) {\n logger.debug(\n \"Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable\"\n );\n} else if (\n !getEnvVar(\"LANGFUSE_PUBLIC_KEY\") ||\n !getEnvVar(\"LANGFUSE_SECRET_KEY\")\n) {\n logger.debug(\n \"Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable\"\n );\n} else {\n // Create initialization promise to ensure handlers are ready when needed\n langfuseState.initPromise = initializeLangfuse();\n}\n\n// Export getters to access the state\nexport const langfuseHandler = () => langfuseState.handler;\nexport const langfuseInitPromise = () => langfuseState.initPromise;\nexport { initializeLangfuse };\n","import { stripVTControlCharacters } from \"node:util\";\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\n\n/**\n * Helper functions for pretty-printing code mode tool executions\n */\n\nconst TERMINAL_WIDTH = process.stdout.columns || 120;\n\ninterface ExecuteCodeResult {\n result: unknown;\n logs: string[];\n error: string | null;\n execution_time: number;\n}\n\n/**\n * Whether to emit ANSI escapes: only on a TTY stdout, and never when the\n * `NO_COLOR` convention is set. Edge runtimes without `process.stdout`\n * get plain text.\n */\nfunction colorsEnabled(): boolean {\n if (typeof process === \"undefined\") return false;\n if (process.env?.[\"NO_COLOR\"] !== undefined) return false;\n return process.stdout?.isTTY === true;\n}\n\ntype Style = (text: string) => string;\n\nfunction ansi(open: number, close: number): Style {\n return (text) =>\n colorsEnabled() ? `\\u001B[${open}m${text}\\u001B[${close}m` : text;\n}\n\nconst style = {\n gray: ansi(90, 39),\n bold: ansi(1, 22),\n cyan: ansi(36, 39),\n dim: ansi(2, 22),\n red: ansi(31, 39),\n green: ansi(32, 39),\n};\n\n// Remove ANSI color codes for length calculation\nfunction stripAnsi(str: string): string {\n return stripVTControlCharacters(str);\n}\n\n// wrap lines correctly, preserving ANSI codes\nfunction wrapAnsiLine(line: string, maxWidth: number): string[] {\n const stripped = stripAnsi(line);\n\n if (stripped.length <= maxWidth) return [line];\n\n const result: string[] = [];\n let visibleCount = 0;\n let current = \"\";\n let i = 0;\n\n while (i < line.length) {\n const char = line[i];\n\n if (char === \"\\x1b\") {\n // Start of escape sequence\n let sequence = char;\n i++;\n while (i < line.length) {\n const nextChar = line[i];\n sequence += nextChar;\n i++;\n if (nextChar === \"m\") break;\n }\n current += sequence;\n continue;\n }\n\n // Normal character\n current += char;\n visibleCount++;\n i++;\n\n if (visibleCount >= maxWidth) {\n result.push(current);\n current = \"\";\n visibleCount = 0;\n }\n }\n if (current) result.push(current);\n return result;\n}\n\nfunction printBox(content: string, title?: string) {\n const width = TERMINAL_WIDTH;\n\n const lines = content\n .split(\"\\n\")\n .flatMap((line) => wrapAnsiLine(line, width - 4));\n\n console.log(style.gray(\"┌\" + \"─\".repeat(width - 2) + \"┐\"));\n\n if (title) {\n const stripped = stripAnsi(title);\n const lineText = `${title} `;\n const padding = Math.max(0, width - 4 - stripped.length - 2);\n console.log(\n style.gray(\"│ \") +\n style.bold(lineText) +\n \" \".repeat(padding) +\n style.gray(\" │\")\n );\n console.log(style.gray(\"├\" + \"─\".repeat(width - 2) + \"┤\"));\n }\n\n lines.forEach((line) => {\n const stripped = stripAnsi(line);\n const padding = Math.max(0, width - 4 - stripped.length);\n console.log(\n style.gray(\"│ \") + line + \" \".repeat(padding) + style.gray(\" │\")\n );\n });\n\n console.log(style.gray(\"└\" + \"─\".repeat(width - 2) + \"┘\"));\n}\n\n/**\n * Extract code from tool input if present\n */\nfunction extractCodeFromToolInput(input: unknown): string | null {\n if (typeof input === \"object\" && input !== null && \"code\" in input) {\n const inputObj = input as Record<string, unknown>;\n return typeof inputObj.code === \"string\" ? inputObj.code : null;\n }\n return null;\n}\n\n/**\n * Type guard to check if an object is an ExecuteCodeResult\n */\nfunction isExecuteCodeResult(obj: unknown): obj is ExecuteCodeResult {\n if (typeof obj !== \"object\" || obj === null) return false;\n const result = obj as Record<string, unknown>;\n return (\n \"result\" in result &&\n \"logs\" in result &&\n Array.isArray(result.logs) &&\n \"execution_time\" in result &&\n typeof result.execution_time === \"number\" &&\n \"error\" in result &&\n (typeof result.error === \"string\" || result.error === null)\n );\n}\n\n/**\n * Parse execute_code tool result\n */\nfunction parseExecuteCodeResult(output: unknown): ExecuteCodeResult | null {\n try {\n // If output is a string, try to parse it as JSON\n if (typeof output === \"string\") {\n const parsed = JSON.parse(output);\n if (isExecuteCodeResult(parsed)) {\n return parsed;\n }\n }\n // If output is already an object with the right structure\n if (isExecuteCodeResult(output)) {\n return output;\n }\n } catch (e) {\n // Not a valid execute_code result\n }\n return null;\n}\n\n/**\n * Render content with appropriate formatting\n */\nfunction renderContent(content: unknown): string {\n if (content === null || content === undefined) {\n return \"null\";\n }\n\n if (typeof content === \"object\") {\n return JSON.stringify(content, null, 2);\n }\n\n return String(content);\n}\n\n/**\n * Unwrap tool input if it's wrapped in an \"input\" field with JSON string\n */\nfunction unwrapToolInput(input: unknown): unknown {\n // Check if input has an \"input\" field that's a JSON string\n if (typeof input === \"object\" && input !== null && \"input\" in input) {\n const inputObj = input as Record<string, unknown>;\n if (typeof inputObj.input === \"string\") {\n try {\n // Try to parse the JSON string\n return JSON.parse(inputObj.input);\n } catch (e) {\n // If parsing fails, return the original input field\n return inputObj.input;\n }\n }\n }\n return input;\n}\n\n/**\n * Handle tool start event with pretty printing\n */\nfunction handleToolStart(event: StreamEvent) {\n const toolName = event.name || \"unknown\";\n let input = event.data?.input || {};\n\n // Unwrap input if it's wrapped in a JSON string\n input = unwrapToolInput(input);\n\n // Special handling for execute_code to show the code nicely\n const code = extractCodeFromToolInput(input);\n if (code) {\n printBox(code, `${toolName} - input`);\n\n // Show other parameters if any\n const otherParams = { ...input };\n delete otherParams.code;\n if (Object.keys(otherParams).length > 0) {\n printBox(renderContent(otherParams), \"Other Parameters\");\n }\n } else {\n printBox(renderContent(input), `${toolName} - input`);\n }\n}\n\n/**\n * Extract content from LangChain ToolMessage structure\n */\nfunction extractToolMessageContent(\n output: unknown\n): { toolName: string; status: string; content: unknown } | null {\n try {\n // Check if this is a LangChain ToolMessage object (has name and content properties)\n if (\n typeof output === \"object\" &&\n output !== null &&\n \"name\" in output &&\n \"content\" in output\n ) {\n const outputObj = output as Record<string, unknown>;\n const toolName =\n (typeof outputObj.name === \"string\" ? outputObj.name : null) ||\n \"unknown\";\n // LangChain messages might have status in lc_kwargs or in the content itself\n const lcKwargs = outputObj.lc_kwargs as\n | Record<string, unknown>\n | undefined;\n const status =\n (lcKwargs?.status as string) ||\n (outputObj.status as string) ||\n \"unknown\";\n let content = outputObj.content;\n\n // Try to parse content if it's a JSON string\n if (typeof content === \"string\") {\n try {\n content = JSON.parse(content);\n } catch (e) {\n // Keep as string if not JSON\n }\n }\n\n return { toolName, status, content };\n }\n } catch (e) {\n // Not a valid ToolMessage structure\n }\n return null;\n}\n\n/**\n * Format search_tools result as a tree structure\n */\nfunction formatSearchToolsAsTree(\n tools: Array<{ server: string; name: string; description?: string }>,\n meta?: { total_tools?: number; namespaces?: string[]; result_count?: number },\n query?: string\n): string {\n // Build meta information display\n const metaLines: string[] = [];\n if (meta) {\n if (meta.total_tools !== undefined) {\n metaLines.push(`Total tools: ${meta.total_tools}`);\n }\n if (meta.namespaces && meta.namespaces.length > 0) {\n metaLines.push(`Namespaces: ${meta.namespaces.join(\", \")}`);\n }\n if (meta.result_count !== undefined) {\n metaLines.push(`Results: ${meta.result_count}`);\n }\n }\n\n if (!Array.isArray(tools) || tools.length === 0) {\n const noResultsMsg = query\n ? `No tools found for query \"${query}\"`\n : \"(no tools found)\";\n if (metaLines.length > 0) {\n return `${metaLines.join(\"\\n\")}\\n\\n${noResultsMsg}`;\n }\n return noResultsMsg;\n }\n\n // Group tools by server\n const toolsByServer: Record<\n string,\n Array<{ name: string; description?: string }>\n > = {};\n for (const tool of tools) {\n const server = tool.server || \"unknown\";\n if (!toolsByServer[server]) {\n toolsByServer[server] = [];\n }\n toolsByServer[server].push(tool);\n }\n\n // Build tree structure\n const lines: string[] = [];\n\n // Add meta information at the top if available\n if (meta) {\n if (meta.total_tools !== undefined) {\n lines.push(`Total tools: ${meta.total_tools}`);\n }\n if (meta.namespaces && meta.namespaces.length > 0) {\n lines.push(`Namespaces: ${meta.namespaces.join(\", \")}`);\n }\n if (meta.result_count !== undefined) {\n lines.push(`Results: ${meta.result_count}`);\n }\n if (lines.length > 0) {\n lines.push(\"\"); // Empty line before tree\n }\n }\n\n const servers = Object.keys(toolsByServer).sort();\n\n for (let i = 0; i < servers.length; i++) {\n const server = servers[i];\n const serverTools = toolsByServer[server];\n const isLastServer = i === servers.length - 1;\n const serverPrefix = isLastServer ? \"└─\" : \"├─\";\n\n lines.push(\n `${serverPrefix} ${style.cyan(server)} (${serverTools.length} tools)`\n );\n\n // Add tools under this server\n for (let j = 0; j < serverTools.length; j++) {\n const tool = serverTools[j];\n const isLastTool = j === serverTools.length - 1;\n const indent = isLastServer ? \" \" : \"│ \";\n const toolPrefix = isLastTool ? \"└─\" : \"├─\";\n\n // Tool name line\n const toolLine = `${indent}${toolPrefix} ${tool.name}`;\n lines.push(toolLine);\n\n // Description on new line, aligned with tool name\n if (tool.description) {\n // Calculate indent for description lines\n // Use the same base indent as the tool, then add alignment\n // If not the last tool, add vertical bar to show continuation, otherwise spaces\n const descAlign = isLastTool ? \" \" : \"│ \";\n const descriptionIndent = `${indent}${descAlign}`;\n\n // Calculate available width for description\n // Account for: indent + box padding (4 chars for \"│ \" on each side)\n const indentLength = stripAnsi(descriptionIndent).length;\n const availableWidth = Math.max(40, TERMINAL_WIDTH - indentLength - 4);\n\n // Wrap description at word boundaries\n const words = tool.description.split(/(\\s+)/); // Keep whitespace\n const wrappedLines: string[] = [];\n let currentLine = \"\";\n\n for (const word of words) {\n const testLine = currentLine + word;\n if (stripAnsi(testLine).length <= availableWidth) {\n currentLine = testLine;\n } else {\n if (currentLine) {\n wrappedLines.push(currentLine.trimEnd());\n }\n currentLine = word.trimStart();\n }\n }\n if (currentLine) {\n wrappedLines.push(currentLine.trimEnd());\n }\n\n // Add indent and dim styling to each line\n for (const descLine of wrappedLines) {\n lines.push(`${descriptionIndent}${style.dim(descLine)}`);\n }\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Handle tool end event with pretty printing\n */\nfunction handleToolEnd(event: StreamEvent) {\n const output = event.data?.output;\n\n // First, try to extract from LangChain ToolMessage structure if present\n const toolMessage = extractToolMessageContent(output);\n if (toolMessage) {\n const { toolName, status, content } = toolMessage;\n\n // For execute_code, extract the actual result from the nested structure\n if (toolName === \"execute_code\") {\n // Content might be wrapped in { content: [{ type: \"text\", text: \"...\" }] }\n let actualContent = content;\n if (\n typeof content === \"object\" &&\n content !== null &&\n \"content\" in content\n ) {\n const innerContent = content.content;\n if (Array.isArray(innerContent) && innerContent.length > 0) {\n if (innerContent[0].type === \"text\" && innerContent[0].text) {\n actualContent = innerContent[0].text;\n }\n }\n }\n\n // Now try to parse as execute_code result\n const execResult = parseExecuteCodeResult(actualContent);\n if (execResult) {\n // Format execution time in milliseconds\n const timeMs = execResult.execution_time\n ? Math.round(execResult.execution_time * 1000)\n : 0;\n const timeStr = `${timeMs}ms`;\n\n // Determine status text\n const isError =\n execResult.error !== null &&\n execResult.error !== undefined &&\n execResult.error !== \"\";\n const statusText = isError\n ? style.red(\"error\")\n : style.green(\"success\");\n const title = `${toolName} - ${statusText} - ${timeStr}`;\n\n // Only show the result, not the full object\n if (execResult.result !== null && execResult.result !== undefined) {\n const resultStr = renderContent(execResult.result);\n printBox(resultStr, title);\n } else {\n printBox(\"(no result)\", title);\n }\n\n if (execResult.logs && execResult.logs.length > 0) {\n printBox(execResult.logs.join(\"\\n\"), `Logs`);\n }\n\n if (execResult.error) {\n printBox(execResult.error, style.red(\"Error\"));\n }\n return;\n }\n }\n\n // Special handling for search_tools to display as tree\n if (toolName === \"search_tools\") {\n // Try to get the query from event input\n const toolInput = event.data?.input as\n | Record<string, unknown>\n | undefined;\n const query = toolInput?.query as string | undefined;\n\n // Extract actual content if it's wrapped\n let actualContent = content;\n if (\n typeof content === \"object\" &&\n content !== null &&\n !Array.isArray(content) &&\n \"content\" in content\n ) {\n const innerContent = content.content;\n if (Array.isArray(innerContent) && innerContent.length > 0) {\n if (innerContent[0].type === \"text\" && innerContent[0].text) {\n try {\n actualContent = JSON.parse(innerContent[0].text);\n } catch (e) {\n actualContent = innerContent[0].text;\n }\n }\n }\n }\n\n // Handle new format: object with meta and results\n if (\n typeof actualContent === \"object\" &&\n actualContent !== null &&\n !Array.isArray(actualContent) &&\n \"results\" in actualContent &&\n Array.isArray(actualContent.results)\n ) {\n const results = actualContent.results;\n const contentWithMeta = actualContent as {\n results: unknown[];\n meta?: {\n total_tools?: number;\n namespaces?: string[];\n result_count?: number;\n };\n };\n const meta = contentWithMeta.meta;\n const treeStr = formatSearchToolsAsTree(results, meta, query);\n const statusText =\n status === \"success\" ? style.green(\"Success\") : style.red(\"Error\");\n const title = `${statusText}: ${toolName} - Result`;\n printBox(treeStr, title);\n return;\n }\n\n // Handle old format: direct array (backward compatibility)\n if (Array.isArray(actualContent)) {\n const treeStr = formatSearchToolsAsTree(\n actualContent,\n undefined,\n query\n );\n const statusText =\n status === \"success\" ? style.green(\"Success\") : style.red(\"Error\");\n const title = `${statusText}: ${toolName} - Result`;\n printBox(treeStr, title);\n return;\n }\n }\n\n // Check if content indicates an error\n const contentObj =\n typeof content === \"object\" && content !== null\n ? (content as Record<string, unknown>)\n : null;\n const isError =\n (contentObj && \"isError\" in contentObj && contentObj.isError === true) ||\n status === \"error\";\n\n // Extract the actual content to display\n let displayContent = content;\n if (\n typeof content === \"object\" &&\n content !== null &&\n \"content\" in content\n ) {\n displayContent = content.content;\n\n // If content.content is an array with text items, extract the text\n if (Array.isArray(displayContent) && displayContent.length > 0) {\n if (displayContent[0].type === \"text\" && displayContent[0].text) {\n displayContent = displayContent[0].text;\n }\n }\n }\n\n // Format the content for display\n const contentStr = renderContent(displayContent);\n\n // Create title with tool name\n const statusLabel =\n status === \"success\"\n ? style.green(\"Success\")\n : isError\n ? style.red(\"Error\")\n : \"Result\";\n const title = `${statusLabel}: ${toolName} - Result`;\n\n printBox(contentStr, title);\n return;\n }\n\n // Fallback: Try to parse as direct execute_code result (not wrapped in ToolMessage)\n const execResult = parseExecuteCodeResult(output);\n if (execResult) {\n const timeMs = execResult.execution_time\n ? Math.round(execResult.execution_time * 1000)\n : 0;\n const timeStr = `${timeMs}ms`;\n\n if (execResult.result !== null && execResult.result !== undefined) {\n const resultStr = renderContent(execResult.result);\n printBox(resultStr, `Result - ${timeStr}`);\n }\n\n if (execResult.logs && execResult.logs.length > 0) {\n printBox(execResult.logs.join(\"\\n\"), `Logs`);\n }\n\n if (execResult.error) {\n printBox(execResult.error, style.red(\"Error\"));\n }\n return;\n }\n\n // Ultimate fallback: display raw output\n const outputStr = renderContent(output);\n printBox(outputStr, \"Result\");\n}\n\n/**\n * Stream events with pretty printing\n */\nexport async function* prettyStreamEvents(\n streamEventsGenerator: AsyncGenerator<StreamEvent, void, void>\n): AsyncGenerator<void, string, void> {\n let finalResponse = \"\";\n let isFirstTextChunk = true;\n let hasStreamedText = false;\n\n for await (const event of streamEventsGenerator) {\n if (event.event === \"on_tool_start\") {\n // Add newline after agent thinking if we streamed text\n if (hasStreamedText) {\n process.stdout.write(\"\\n\");\n hasStreamedText = false;\n isFirstTextChunk = true;\n }\n handleToolStart(event);\n } else if (event.event === \"on_tool_end\") {\n handleToolEnd(event);\n } else if (event.event === \"on_chat_model_stream\") {\n if (event.data?.chunk?.text) {\n const text = event.data.chunk.text;\n if (typeof text === \"string\" && text.length > 0) {\n // Add newline and robot emoji before first text chunk\n if (isFirstTextChunk) {\n process.stdout.write(\"\\n🤖 \");\n isFirstTextChunk = false;\n }\n process.stdout.write(text);\n finalResponse += text;\n hasStreamedText = true;\n }\n }\n }\n\n yield;\n }\n\n return finalResponse;\n}\n","import type { BaseCallbackHandler } from \"@langchain/core/callbacks/base\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\nimport {\n AIMessage,\n createAgent,\n HumanMessage,\n modelCallLimitMiddleware,\n SystemMessage,\n ToolMessage,\n type ReactAgent,\n} from \"langchain\";\nimport type { ZodSchema } from \"zod\";\nimport { toJSONSchema } from \"zod\";\nimport { LangChainAdapter } from \"../adapters/langchain_adapter.js\";\nimport type { MCPClient } from \"@mcp-use/client\";\nimport type { BaseConnector } from \"@mcp-use/client\";\nimport { logger } from \"@mcp-use/client\";\nimport { ServerManager } from \"../managers/server_manager.js\";\nimport { ObservabilityManager } from \"../observability/index.js\";\nimport type { MCPSession } from \"@mcp-use/client\";\nimport { extractModelInfo } from \"../telemetry/utils.js\";\nimport { Telemetry } from \"@mcp-use/client\";\nimport { getPackageVersion } from \"../version.js\";\nimport { createSystemMessage } from \"./prompts/system_prompt_builder.js\";\nimport {\n DEFAULT_SYSTEM_PROMPT_TEMPLATE,\n SERVER_MANAGER_SYSTEM_PROMPT_TEMPLATE,\n} from \"./prompts/templates.js\";\nimport { RemoteAgent } from \"./remote.js\";\nimport type {\n BaseMessage,\n LanguageModel,\n MCPAgentOptions,\n MCPServerConfig,\n} from \"./types.js\";\nimport { createLLMFromString, type LLMConfig } from \"./utils/llm_provider.js\";\n\n/** Tool invocation details yielded by the LangChain agent. */\nexport interface LangChainAgentAction {\n /** Tool name. */\n tool: string;\n /** Arguments generated by the model. */\n toolInput: any;\n /** LangChain action log. */\n log: string;\n}\n\n/** A completed tool invocation yielded during LangChain agent execution. */\nexport interface AgentStep {\n /** Tool invocation requested by the model. */\n action: LangChainAgentAction;\n /** Serialized result returned by the tool. */\n observation: string;\n}\n\nimport type { RunOptions } from \"./run_options.js\";\n\nexport type { RunOptions };\n\n/**\n * Helper function to normalize run options from either old-style positional arguments\n * or new-style options object\n */\nfunction normalizeRunOptions<T>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n): {\n query: string;\n maxSteps?: number;\n manageConnector?: boolean;\n externalHistory?: BaseMessage[];\n outputSchema?: ZodSchema<T>;\n signal?: AbortSignal;\n} {\n // Check if first argument is an options object\n if (typeof queryOrOptions === \"object\" && queryOrOptions !== null) {\n const options = queryOrOptions as RunOptions<T>;\n return {\n query: options.prompt ?? \"\",\n maxSteps: options.maxSteps,\n manageConnector: options.manageConnector,\n externalHistory: options.externalHistory,\n outputSchema: options.schema,\n signal: options.signal,\n };\n }\n\n // Old-style positional arguments\n return {\n query: queryOrOptions as string,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n signal,\n };\n}\n\n/** Runs a LangChain tool-calling agent against MCP servers. */\nexport class MCPAgent {\n /**\n * Get the mcp-use package version.\n * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)\n */\n public static getPackageVersion(): string {\n return getPackageVersion();\n }\n\n private llm?: LanguageModel;\n private client?: MCPClient;\n private connectors: BaseConnector[];\n private maxSteps: number;\n private autoInitialize: boolean;\n private memoryEnabled: boolean;\n private disallowedTools: string[];\n private additionalTools: StructuredToolInterface[];\n /** Names of tools invoked during the current or most recent execution. */\n public toolsUsedNames: string[] = [];\n private exposeResourcesAsTools: boolean = true;\n private exposePromptsAsTools: boolean = true;\n private useServerManager: boolean;\n private verbose: boolean;\n private observe: boolean;\n private systemPrompt?: string | null;\n private systemPromptTemplateOverride?: string | null;\n private additionalInstructions?: string | null;\n\n private _initialized = false;\n private conversationHistory: BaseMessage[] = [];\n private _agentExecutor: ReactAgent | null = null;\n private sessions: Record<string, MCPSession> = {};\n private systemMessage: SystemMessage | null = null;\n private _tools: StructuredToolInterface[] = [];\n private adapter: LangChainAdapter;\n private serverManager: ServerManager | null = null;\n private telemetry: Telemetry;\n private modelProvider: string;\n private modelName: string;\n\n // Observability support\n /** Observability callbacks and trace lifecycle manager. */\n public observabilityManager: ObservabilityManager;\n private callbacks: BaseCallbackHandler[] = [];\n private metadata: Record<string, any> = {};\n private tags: string[] = [];\n\n // Remote agent support\n private isRemote = false;\n private remoteAgent: RemoteAgent | null = null;\n\n // Simplified mode support\n private isSimplifiedMode = false;\n private llmString?: string;\n private llmConfig?: LLMConfig;\n private mcpServersConfig?: Record<string, MCPServerConfig>;\n private clientOwnedByAgent = false;\n\n /**\n * Creates a LangChain MCP agent.\n *\n * @param options - Model, MCP servers, tools, and execution settings.\n * @throws Error if local execution does not include a model and MCP client,\n * connectors, or server configurations.\n */\n constructor(options: MCPAgentOptions) {\n // Handle remote execution\n if (options.agentId) {\n this.isRemote = true;\n this.remoteAgent = new RemoteAgent({\n agentId: options.agentId,\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n });\n // Set default values for remote agent\n this.maxSteps = options.maxSteps ?? 5;\n this.memoryEnabled = options.memoryEnabled ?? true;\n this.autoInitialize = options.autoInitialize ?? false;\n this.verbose = options.verbose ?? false;\n this.observe = options.observe ?? true;\n this.connectors = [];\n this.disallowedTools = [];\n this.additionalTools = [];\n this.useServerManager = false;\n this.adapter = new LangChainAdapter();\n this.telemetry = Telemetry.getInstance();\n this.modelProvider = \"remote\";\n this.modelName = \"remote-agent\";\n this.observabilityManager = new ObservabilityManager({\n customCallbacks: options.callbacks,\n agentId: options.agentId,\n });\n this.callbacks = [];\n return;\n }\n\n // Validate requirements for local execution\n if (!options.llm) {\n throw new Error(\n \"llm is required for local execution. For remote execution, provide agentId instead.\"\n );\n }\n\n // Detect mode: simplified (string llm) vs explicit (object llm)\n const isSimplifiedMode = typeof options.llm === \"string\";\n\n if (isSimplifiedMode) {\n // Simplified mode: llm is string, mcpServers must be provided\n this.isSimplifiedMode = true;\n this.llmString = options.llm as string;\n this.llmConfig = (options as any).llmConfig;\n this.mcpServersConfig = (options as any).mcpServers;\n\n if (\n !this.mcpServersConfig ||\n Object.keys(this.mcpServersConfig).length === 0\n ) {\n throw new Error(\n \"Simplified mode requires 'mcpServers' configuration. \" +\n \"Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }\"\n );\n }\n\n // LLM and client will be created during initialize()\n this.llm = undefined;\n this.client = undefined;\n this.clientOwnedByAgent = true; // Mark for cleanup\n this.connectors = [];\n\n logger.debug(\n `🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`\n );\n } else {\n // Explicit mode: llm is object, client or connectors must be provided\n this.isSimplifiedMode = false;\n this.llm = options.llm as LanguageModel;\n this.client = (options as any).client;\n this.connectors = (options as any).connectors ?? [];\n this.clientOwnedByAgent = false;\n\n if (!this.client && this.connectors.length === 0) {\n throw new Error(\n \"Explicit mode requires either 'client' or at least one 'connector'. \" +\n \"Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.\"\n );\n }\n }\n\n // Common configuration for both modes\n this.maxSteps = options.maxSteps ?? 5;\n this.autoInitialize = options.autoInitialize ?? this.isSimplifiedMode;\n this.memoryEnabled = options.memoryEnabled ?? true;\n this.systemPrompt = options.systemPrompt ?? null;\n this.systemPromptTemplateOverride = options.systemPromptTemplate ?? null;\n this.additionalInstructions = options.additionalInstructions ?? null;\n this.disallowedTools = options.disallowedTools ?? [];\n this.additionalTools = options.additionalTools ?? [];\n this.toolsUsedNames = options.toolsUsedNames ?? [];\n this.exposeResourcesAsTools = options.exposeResourcesAsTools ?? true;\n this.exposePromptsAsTools = options.exposePromptsAsTools ?? true;\n this.useServerManager = options.useServerManager ?? false;\n this.verbose = options.verbose ?? false;\n this.observe = options.observe ?? true;\n\n // Set up adapter and server manager (only for explicit mode with client)\n if (!this.isSimplifiedMode) {\n if (this.useServerManager) {\n if (!this.client) {\n throw new Error(\n \"'client' must be provided when 'useServerManager' is true.\"\n );\n }\n this.adapter =\n options.adapter ?? new LangChainAdapter(this.disallowedTools);\n this.serverManager =\n options.serverManagerFactory?.(this.client) ??\n new ServerManager(this.client, this.adapter);\n } else {\n this.adapter =\n options.adapter ?? new LangChainAdapter(this.disallowedTools);\n }\n\n // Initialize telemetry for explicit mode\n this.telemetry = Telemetry.getInstance();\n if (this.llm) {\n const [provider, name] = extractModelInfo(this.llm as any);\n this.modelProvider = provider;\n this.modelName = name;\n } else {\n this.modelProvider = \"unknown\";\n this.modelName = \"unknown\";\n }\n } else {\n // For simplified mode, defer adapter/telemetry initialization\n this.adapter =\n options.adapter ?? new LangChainAdapter(this.disallowedTools);\n this.telemetry = Telemetry.getInstance();\n // Model info will be set during initialize()\n this.modelProvider = \"unknown\";\n this.modelName = \"unknown\";\n }\n\n // Set up observability callbacks using the ObservabilityManager\n this.observabilityManager = new ObservabilityManager({\n customCallbacks: options.callbacks,\n verbose: this.verbose,\n observe: this.observe,\n agentId: options.agentId,\n metadataProvider: () => this.getMetadata(),\n tagsProvider: () => this.getTags(),\n });\n\n // Make getters configurable for test mocking\n Object.defineProperty(this, \"agentExecutor\", {\n get: () => this._agentExecutor,\n configurable: true,\n });\n Object.defineProperty(this, \"tools\", {\n get: () => this._tools,\n configurable: true,\n });\n Object.defineProperty(this, \"initialized\", {\n get: () => this._initialized,\n configurable: true,\n });\n }\n\n /**\n * Creates configured clients and models, connects MCP servers, loads tools,\n * and builds the LangChain executor.\n *\n * @throws Error if a configured model or MCP server cannot be initialized.\n */\n public async initialize(): Promise<void> {\n // Skip initialization for remote agents\n if (this.isRemote) {\n this._initialized = true;\n return;\n }\n\n logger.debug(\"🚀 Initializing MCP agent and connecting to services...\");\n\n // Handle simplified mode: create client and LLM from configuration\n if (this.isSimplifiedMode) {\n logger.debug(\n \"🎯 Simplified mode: Creating client and LLM from configuration...\"\n );\n\n // Create MCPClient from mcpServers configuration\n if (this.mcpServersConfig) {\n logger.debug(\n `Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`\n );\n // Dynamically import MCPClient (Node.js version)\n const { MCPClient } = await import(\"@mcp-use/client\");\n this.client = new MCPClient({ mcpServers: this.mcpServersConfig });\n logger.debug(\"✅ MCPClient created successfully\");\n }\n\n // Create LLM from string specification\n if (this.llmString) {\n logger.debug(`Creating LLM from string: ${this.llmString}...`);\n try {\n this.llm = await createLLMFromString(this.llmString, this.llmConfig);\n logger.debug(\"✅ LLM created successfully\");\n\n // Update model info for telemetry\n const [provider, name] = extractModelInfo(this.llm as any);\n this.modelProvider = provider;\n this.modelName = name;\n } catch (error: any) {\n throw new Error(\n `Failed to create LLM from string '${this.llmString}': ${error?.message || error}`\n );\n }\n }\n\n // Set up server manager if needed\n if (this.useServerManager) {\n if (!this.client) {\n throw new Error(\n \"'client' must be available when 'useServerManager' is true.\"\n );\n }\n this.serverManager = new ServerManager(this.client, this.adapter);\n }\n }\n\n // Initialize observability callbacks\n this.callbacks = await this.observabilityManager.getCallbacks();\n const handlerNames = await this.observabilityManager.getHandlerNames();\n if (handlerNames.length > 0) {\n logger.debug(`📊 Observability enabled with: ${handlerNames.join(\", \")}`);\n }\n\n // If using server manager, initialize it\n if (this.useServerManager && this.serverManager) {\n await this.serverManager.initialize();\n\n // Get server management tools\n const managementTools = this.serverManager.tools;\n this._tools = managementTools;\n this._tools.push(...this.additionalTools);\n logger.debug(\n `🔧 Server manager mode active with ${managementTools.length} management tools`\n );\n\n // Create the system message based on available tools\n await this.createSystemMessageFromTools(this._tools);\n } else {\n // Standard initialization - if using client, get or create sessions\n if (this.client) {\n // First try to get existing sessions\n this.sessions = this.client.getAllActiveSessions();\n logger.debug(\n `🔌 Found ${Object.keys(this.sessions).length} existing sessions`\n );\n\n // Filter out internal code_mode session to check if real MCP servers are connected\n const nonCodeModeSessions = Object.keys(this.sessions).filter(\n (name) => name !== \"code_mode\"\n );\n\n // If no active sessions exist (excluding code_mode), create new ones\n if (nonCodeModeSessions.length === 0) {\n logger.debug(\"🔄 No active sessions found, creating new ones...\");\n this.sessions = await this.client.createAllSessions();\n logger.debug(\n `✅ Created ${Object.keys(this.sessions).length} new sessions`\n );\n }\n\n // Create LangChain tools directly from the client using the adapter\n // In code mode, only expose the code_mode tools (execute_code, search_tools)\n if ((this.client as { codeMode?: boolean }).codeMode) {\n const codeModeSession = this.sessions[\"code_mode\"];\n if (codeModeSession) {\n // Code mode only uses tools, not resources or prompts\n this._tools = await this.adapter.createToolsFromConnectors([\n codeModeSession.connector,\n ]);\n logger.debug(`🛠️ Created ${this._tools.length} code mode tools`);\n } else {\n throw new Error(\n \"Code mode enabled but code_mode session not found\"\n );\n }\n } else {\n // Create tools from the client; resources and prompts are optional\n const connectors = Object.values(this.sessions).map(\n (session) => session.connector\n );\n const tools =\n await this.adapter.createToolsFromConnectors(connectors);\n const resources = this.exposeResourcesAsTools\n ? await this.adapter.createResourcesFromConnectors(connectors)\n : [];\n const prompts = this.exposePromptsAsTools\n ? await this.adapter.createPromptsFromConnectors(connectors)\n : [];\n this._tools = [...tools, ...resources, ...prompts];\n logger.debug(\n `🛠️ Created ${this._tools.length} LangChain items from client: ` +\n `${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`\n );\n }\n this._tools.push(...this.additionalTools);\n } else {\n // Using direct connector - only establish connection\n logger.debug(\n `🔗 Connecting to ${this.connectors.length} direct connectors...`\n );\n for (const connector of this.connectors) {\n if (!connector.isClientConnected) {\n await connector.connect();\n }\n }\n\n // Create LangChain tools, resources, and prompts using the adapter with connectors\n const tools = await this.adapter.createToolsFromConnectors(\n this.connectors\n );\n const resources = await this.adapter.createResourcesFromConnectors(\n this.connectors\n );\n const prompts = await this.adapter.createPromptsFromConnectors(\n this.connectors\n );\n this._tools = [...tools, ...resources, ...prompts];\n this._tools.push(...this.additionalTools);\n logger.debug(\n `🛠️ Created ${this._tools.length} LangChain items from connectors: ` +\n `${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`\n );\n }\n\n // Get all tools for system message generation\n logger.debug(\n `🧰 Found ${this._tools.length} tools across all connectors`\n );\n\n // Create the system message based on available tools\n await this.createSystemMessageFromTools(this._tools);\n }\n\n // Create the agent executor and mark initialized\n this._agentExecutor = this.createAgent();\n this._initialized = true;\n\n // Add MCP server information to observability metadata\n const mcpServerInfo = this.getMCPServerInfo();\n if (Object.keys(mcpServerInfo).length > 0) {\n this.setMetadata(mcpServerInfo);\n logger.debug(\n `MCP server info added to metadata: ${JSON.stringify(mcpServerInfo)}`\n );\n }\n\n logger.debug(\"✨ Agent initialization complete\");\n }\n\n private async createSystemMessageFromTools(\n tools: StructuredToolInterface[]\n ): Promise<void> {\n const systemPromptTemplate =\n this.systemPromptTemplateOverride ?? DEFAULT_SYSTEM_PROMPT_TEMPLATE;\n\n this.systemMessage = createSystemMessage(\n tools,\n systemPromptTemplate,\n SERVER_MANAGER_SYSTEM_PROMPT_TEMPLATE,\n this.useServerManager,\n this.disallowedTools,\n this.systemPrompt ?? undefined,\n this.additionalInstructions ?? undefined\n );\n\n if (this.memoryEnabled) {\n this.conversationHistory = [\n this.systemMessage,\n ...this.conversationHistory.filter(\n (m) => !(m instanceof SystemMessage)\n ),\n ];\n }\n }\n\n private createAgent(): ReactAgent {\n if (!this.llm) {\n throw new Error(\"LLM is required to create agent\");\n }\n\n const systemContent =\n (this.systemMessage?.content as string) ?? \"You are a helpful assistant.\";\n\n const toolNames = this._tools.map((tool) => tool.name);\n logger.debug(`🧠 Agent ready with tools: ${toolNames.join(\", \")}`);\n\n // Create middleware to enforce max_steps\n // modelCallLimitMiddleware limits the number of model calls, which corresponds to agent steps\n const middleware = [modelCallLimitMiddleware({ runLimit: this.maxSteps })];\n\n const agent = createAgent({\n model: this.llm,\n tools: this._tools as any,\n systemPrompt: systemContent,\n middleware,\n });\n\n logger.debug(\n `Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`\n );\n\n return agent;\n }\n\n /** @returns A shallow copy of the stored LangChain message history. */\n public getConversationHistory(): BaseMessage[] {\n return [...this.conversationHistory];\n }\n\n /** Clears stored history, retaining the system message when memory is enabled. */\n public clearConversationHistory(): void {\n this.conversationHistory =\n this.memoryEnabled && this.systemMessage ? [this.systemMessage] : [];\n }\n\n private addToHistory(message: BaseMessage): void {\n if (this.memoryEnabled) this.conversationHistory.push(message);\n }\n\n /** @returns The current LangChain system message, or `null` before creation. */\n public getSystemMessage(): SystemMessage | null {\n return this.systemMessage;\n }\n\n /**\n * Replaces the system instruction and rebuilds an initialized executor.\n *\n * @param message - New system instruction.\n */\n public setSystemMessage(message: string): void {\n this.systemMessage = new SystemMessage(message);\n if (this.memoryEnabled) {\n this.conversationHistory = this.conversationHistory.filter(\n (m) => !(m instanceof SystemMessage)\n );\n this.conversationHistory.unshift(this.systemMessage);\n }\n\n if (this._initialized && this._tools.length) {\n this._agentExecutor = this.createAgent();\n logger.debug(\"Agent recreated with new system message\");\n }\n }\n\n /**\n * Replaces the tool denylist for the next initialization.\n *\n * @param disallowedTools - MCP tool names to omit.\n */\n public setDisallowedTools(disallowedTools: string[]): void {\n this.disallowedTools = disallowedTools;\n this.adapter = new LangChainAdapter(this.disallowedTools);\n if (this._initialized) {\n logger.debug(\n \"Agent already initialized. Changes will take effect on next initialization.\"\n );\n }\n }\n\n /** @returns The configured MCP tool denylist. */\n public getDisallowedTools(): string[] {\n return this.disallowedTools;\n }\n\n /**\n * Set metadata for observability traces\n * @param newMetadata - Key-value pairs to add to metadata. Keys should be strings, values should be serializable.\n */\n public setMetadata(newMetadata: Record<string, any>): void {\n // Validate and sanitize metadata\n const sanitizedMetadata = this.sanitizeMetadata(newMetadata);\n\n // Merge with existing metadata instead of replacing it\n this.metadata = { ...this.metadata, ...sanitizedMetadata };\n logger.debug(`Metadata set: ${JSON.stringify(this.metadata)}`);\n }\n\n /**\n * Get current metadata\n * @returns A copy of the current metadata object\n */\n public getMetadata(): Record<string, any> {\n return { ...this.metadata };\n }\n\n /**\n * Set tags for observability traces\n * @param newTags - Array of tag strings to add. Duplicates will be automatically removed.\n */\n public setTags(newTags: string[]): void {\n // Validate and sanitize tags\n const sanitizedTags = this.sanitizeTags(newTags);\n this.tags = [...new Set([...this.tags, ...sanitizedTags])]; // Remove duplicates\n logger.debug(`Tags set: ${JSON.stringify(this.tags)}`);\n }\n\n /**\n * Get current tags\n * @returns A copy of the current tags array\n */\n public getTags(): string[] {\n return [...this.tags];\n }\n\n /**\n * Sanitize metadata to ensure compatibility with observability platforms\n * @param metadata - Raw metadata object\n * @returns Sanitized metadata object\n */\n private sanitizeMetadata(metadata: Record<string, any>): Record<string, any> {\n const sanitized: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(metadata)) {\n // Validate key\n if (typeof key !== \"string\" || key.length === 0) {\n logger.warn(`Invalid metadata key: ${key}. Skipping.`);\n continue;\n }\n\n // Sanitize key (remove special characters that might cause issues)\n const sanitizedKey = key.replace(/[^\\w-]/g, \"_\");\n\n // Validate and sanitize value\n if (value === null || value === undefined) {\n sanitized[sanitizedKey] = value;\n } else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n sanitized[sanitizedKey] = value;\n } else if (Array.isArray(value)) {\n // Only allow arrays of primitives\n const sanitizedArray = value.filter(\n (item) =>\n typeof item === \"string\" ||\n typeof item === \"number\" ||\n typeof item === \"boolean\"\n );\n if (sanitizedArray.length > 0) {\n sanitized[sanitizedKey] = sanitizedArray;\n }\n } else if (typeof value === \"object\") {\n // Try to serialize objects, but limit depth to prevent circular references\n try {\n const serialized = JSON.stringify(value);\n if (serialized.length > 1000) {\n logger.warn(\n `Metadata value for key '${sanitizedKey}' is too large. Truncating.`\n );\n sanitized[sanitizedKey] = `${serialized.substring(0, 1000)}...`;\n } else {\n sanitized[sanitizedKey] = value;\n }\n } catch (error) {\n logger.warn(\n `Failed to serialize metadata value for key '${sanitizedKey}': ${error}. Skipping.`\n );\n }\n } else {\n logger.warn(\n `Unsupported metadata value type for key '${sanitizedKey}': ${typeof value}. Skipping.`\n );\n }\n }\n\n return sanitized;\n }\n\n /**\n * Sanitize tags to ensure compatibility with observability platforms\n * @param tags - Array of tag strings\n * @returns Array of sanitized tag strings\n */\n private sanitizeTags(tags: string[]): string[] {\n return tags\n .filter((tag) => typeof tag === \"string\" && tag.length > 0)\n .map((tag) => tag.replace(/[^\\w:-]/g, \"_\"))\n .filter((tag) => tag.length <= 50); // Limit tag length\n }\n\n /**\n * Get MCP server information for observability metadata\n */\n private getMCPServerInfo(): Record<string, any> {\n const serverInfo: Record<string, any> = {};\n\n try {\n if (this.client) {\n const serverNames = this.client.getServerNames();\n serverInfo.mcp_servers_count = serverNames.length;\n serverInfo.mcp_server_names = serverNames;\n\n // Get server types and configurations\n const serverConfigs: Record<string, any> = {};\n for (const serverName of serverNames) {\n try {\n const config = this.client.getServerConfig(serverName);\n if (config) {\n // Determine server type based on configuration\n const isStdio = \"command\" in config;\n const serverType = isStdio ? \"command\" : \"http\";\n\n serverConfigs[serverName] = {\n type: serverType,\n // Include safe configuration details (avoid sensitive data)\n has_args: isStdio && !!config.args,\n has_env: isStdio && !!config.env,\n has_headers: !isStdio && !!config.headers,\n url: isStdio ? null : config.url,\n command: isStdio ? config.command : null,\n };\n }\n } catch (error) {\n logger.warn(\n `Failed to get config for server '${serverName}': ${error}`\n );\n serverConfigs[serverName] = {\n type: \"error\",\n error: \"config_unavailable\",\n };\n }\n }\n serverInfo.mcp_server_configs = serverConfigs;\n } else if (this.connectors && this.connectors.length > 0) {\n // Handle direct connectors\n serverInfo.mcp_servers_count = this.connectors.length;\n serverInfo.mcp_server_names = this.connectors.map(\n (c) => c.publicIdentifier\n );\n serverInfo.mcp_server_types = this.connectors.map(\n (c) => c.constructor.name\n );\n }\n } catch (error) {\n logger.warn(`Failed to collect MCP server info: ${error}`);\n serverInfo.error = \"collection_failed\";\n }\n\n return serverInfo;\n }\n\n private _normalizeOutput(value: any): string {\n /**\n * Normalize model outputs into a plain text string.\n * Similar to Python's _normalize_output method.\n */\n try {\n if (typeof value === \"string\") {\n return value;\n }\n\n // LangChain messages may have .content which is str or list-like\n if (value && typeof value === \"object\" && \"content\" in value) {\n return this._normalizeOutput(value.content);\n }\n\n if (Array.isArray(value)) {\n const parts: string[] = [];\n for (const item of value) {\n if (typeof item === \"object\" && item !== null) {\n if (\"text\" in item && typeof item.text === \"string\") {\n parts.push(item.text);\n } else if (\"content\" in item) {\n parts.push(this._normalizeOutput(item.content));\n } else {\n // Fallback to string for unknown shapes\n parts.push(String(item));\n }\n } else {\n // recurse on .text or str\n const partText =\n item && typeof item === \"object\" && \"text\" in item\n ? item.text\n : null;\n if (typeof partText === \"string\") {\n parts.push(partText);\n } else {\n const partContent =\n item && typeof item === \"object\" && \"content\" in item\n ? item.content\n : item;\n parts.push(this._normalizeOutput(partContent));\n }\n }\n }\n return parts.join(\"\");\n }\n\n return String(value);\n } catch (error) {\n return String(value);\n }\n }\n\n /**\n * Check if a message is AI/assistant-like regardless of whether it's a class instance.\n * Handles version mismatches, serialization boundaries, and different message formats.\n *\n * This method solves the issue where messages from LangChain agents may be plain JavaScript\n * objects (e.g., `{ type: 'ai', content: '...' }`) instead of AIMessage instances due to\n * serialization/deserialization across module boundaries or version mismatches.\n *\n * @example\n * ```ts\n * // Real AIMessage instance (standard case).\n * _isAIMessageLike(new AIMessage(\"hello\")); // true\n * ```\n *\n * @example\n * ```ts\n * // Plain object after serialization (fixes issue #446).\n * _isAIMessageLike({ type: \"ai\", content: \"hello\" }); // true\n * ```\n *\n * @example\n * ```ts\n * // OpenAI-style format with role.\n * _isAIMessageLike({ role: \"assistant\", content: \"hello\" }); // true\n * ```\n *\n * @example\n * ```ts\n * // Object with getType() method.\n * _isAIMessageLike({ getType: () => \"ai\", content: \"hello\" }); // true\n * ```\n *\n * @param message - The message object to check\n * @returns true if the message represents an AI/assistant message\n */\n private _isAIMessageLike(message: unknown): message is\n | AIMessage\n | {\n type: \"ai\" | \"assistant\";\n content?: unknown;\n tool_calls?: unknown;\n }\n | {\n role: \"ai\" | \"assistant\";\n content?: unknown;\n tool_calls?: unknown;\n } {\n // Fast path: check if it's an actual AIMessage instance\n if (message instanceof AIMessage) {\n return true;\n }\n\n // Relaxed check: just need to be an object (content is optional as messages might only have tool_calls)\n if (typeof message !== \"object\" || message === null) {\n return false;\n }\n\n // Check for type/role properties that indicate an assistant message\n // Support multiple formats from different LangChain versions\n const msg = message as any;\n\n // Try methods first (for partially deserialized objects)\n if (typeof msg.getType === \"function\") {\n try {\n const type = msg.getType();\n if (type === \"ai\" || type === \"assistant\") {\n return true;\n }\n } catch (error) {\n // If getType() throws, fall through to other checks\n // Note: Silent failure here to avoid performance impact in hot path\n }\n }\n if (typeof msg._getType === \"function\") {\n try {\n const type = msg._getType();\n if (type === \"ai\" || type === \"assistant\") {\n return true;\n }\n } catch (error) {\n // If _getType() throws, fall through to other checks\n // Note: Silent failure here to avoid performance impact in hot path\n }\n }\n\n // Check direct properties\n if (\"type\" in msg) {\n return msg.type === \"ai\" || msg.type === \"assistant\";\n }\n if (\"role\" in msg) {\n return msg.role === \"ai\" || msg.role === \"assistant\";\n }\n\n return false;\n }\n\n /**\n * Check if a message has tool calls, handling both class instances and plain objects.\n * Safely checks for tool_calls array presence.\n *\n * @example\n * ```ts\n * const message = new AIMessage({\n * content: \"\",\n * tool_calls: [{ name: \"add\", args: {} }],\n * });\n * _messageHasToolCalls(message); // true\n * ```\n *\n * @example\n * ```ts\n * _messageHasToolCalls({\n * type: \"ai\",\n * tool_calls: [{ name: \"add\" }],\n * }); // true\n * ```\n *\n * @example\n * ```ts\n * _messageHasToolCalls({ type: \"ai\", content: \"hello\" }); // false\n * ```\n *\n * @param message - The message object to check\n * @returns true if the message has non-empty tool_calls array\n */\n private _messageHasToolCalls(message: unknown): boolean {\n if (\n typeof message === \"object\" &&\n message !== null &&\n \"tool_calls\" in message &&\n Array.isArray((message as { tool_calls?: unknown }).tool_calls)\n ) {\n return (message as { tool_calls: unknown[] }).tool_calls.length > 0;\n }\n\n return false;\n }\n\n /**\n * Check if a message is a HumanMessage-like object.\n * Handles both class instances and plain objects from serialization.\n *\n * @example\n * ```ts\n * _isHumanMessageLike(new HumanMessage(\"hello\")); // true\n * _isHumanMessageLike({ type: \"human\", content: \"hello\" }); // true\n * ```\n *\n * @param message - The message object to check\n * @returns true if the message represents a human message\n */\n private _isHumanMessageLike(message: unknown): boolean {\n if (message instanceof HumanMessage) {\n return true;\n }\n if (typeof message !== \"object\" || message === null) {\n return false;\n }\n const msg = message as any;\n\n // Try methods first\n if (typeof msg.getType === \"function\") {\n try {\n const type = msg.getType();\n if (type === \"human\" || type === \"user\") {\n return true;\n }\n } catch (error) {\n // Silent failure for performance\n }\n }\n\n // Check direct properties\n if (\"type\" in msg && (msg.type === \"human\" || msg.type === \"user\")) {\n return true;\n }\n if (\"role\" in msg && (msg.role === \"human\" || msg.role === \"user\")) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if a message is a ToolMessage-like object.\n * Handles both class instances and plain objects from serialization.\n *\n * @example\n * ```ts\n * const message = new ToolMessage({\n * content: \"result\",\n * tool_call_id: \"123\",\n * });\n * _isToolMessageLike(message); // true\n * _isToolMessageLike({ type: \"tool\", content: \"result\" }); // true\n * ```\n *\n * @param message - The message object to check\n * @returns true if the message represents a tool message\n */\n private _isToolMessageLike(message: unknown): boolean {\n if (message instanceof ToolMessage) {\n return true;\n }\n if (typeof message !== \"object\" || message === null) {\n return false;\n }\n const msg = message as any;\n\n // Try methods first\n if (typeof msg.getType === \"function\") {\n try {\n const type = msg.getType();\n if (type === \"tool\") {\n return true;\n }\n } catch (error) {\n // Silent failure for performance\n }\n }\n\n // Check direct properties\n if (\"type\" in msg && msg.type === \"tool\") {\n return true;\n }\n\n return false;\n }\n\n /**\n * Extract content from a message, handling both AIMessage instances and plain objects.\n *\n * @example\n * ```ts\n * _getMessageContent(new AIMessage(\"hello\")); // \"hello\"\n * ```\n *\n * @example\n * ```ts\n * _getMessageContent({ type: \"ai\", content: \"hello\" }); // \"hello\"\n * ```\n *\n * @param message - The message object to extract content from\n * @returns The content of the message, or undefined if not present\n */\n private _getMessageContent(message: unknown): unknown {\n if (message instanceof AIMessage) {\n return message.content;\n }\n if (message && typeof message === \"object\" && \"content\" in message) {\n return (message as { content: unknown }).content;\n }\n return undefined;\n }\n\n private async _consumeAndReturn<T>(\n generator: AsyncGenerator<AgentStep, string | T, void>\n ): Promise<string | T> {\n // Manually iterate through the generator to consume the steps.\n // The for-await-of loop is not used because it discards the generator's\n // final return value. We need to capture that value when `done` is true.\n while (true) {\n const { done, value } = await generator.next();\n if (done) {\n return value;\n }\n }\n }\n\n /**\n * Runs the agent with options object and returns a promise for the final result.\n */\n public async run(options: RunOptions): Promise<string>;\n\n /**\n * Runs the agent with options object and structured output, returns a promise for the typed result.\n */\n public async run<T>(options: RunOptions<T>): Promise<T>;\n\n /**\n * Runs the agent and returns a promise for the final result.\n * @deprecated Use the options object instead: `run({ prompt, maxSteps, ... })`.\n */\n public async run(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: undefined,\n signal?: AbortSignal\n ): Promise<string>;\n\n /**\n * Runs the agent with structured output and returns a promise for the typed result.\n * @deprecated Use the options object instead: `run({ prompt, schema, maxSteps, ... })`.\n */\n public async run<T>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): Promise<T>;\n\n public async run<T>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): Promise<string | T> {\n // Normalize input to internal parameters\n const {\n query,\n maxSteps: steps,\n manageConnector: manage,\n externalHistory: history,\n outputSchema: schema,\n signal: abortSignal,\n } = normalizeRunOptions(\n queryOrOptions,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n signal\n );\n\n // Delegate to remote agent if in remote mode\n if (this.isRemote && this.remoteAgent) {\n return this.remoteAgent.run(query, steps, manage, history, schema);\n }\n\n const generator = this.stream<T>(\n query,\n steps,\n manage,\n history,\n schema,\n abortSignal\n );\n return this._consumeAndReturn(generator);\n }\n\n /**\n * Streams the agent execution with options object and returns string result.\n */\n public stream(options: RunOptions): AsyncGenerator<AgentStep, string, void>;\n\n /**\n * Streams the agent execution with options object and structured output.\n */\n public stream<T>(options: RunOptions<T>): AsyncGenerator<AgentStep, T, void>;\n\n /**\n * Streams the agent execution and yields agent steps.\n * @deprecated Use the options object instead: `stream({ prompt, maxSteps, ... })`.\n */\n public stream<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): AsyncGenerator<AgentStep, string | T, void>;\n\n public async *stream<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector = true,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): AsyncGenerator<AgentStep, string | T, void> {\n // Normalize input to internal parameters\n const {\n query,\n maxSteps: steps,\n manageConnector: manage,\n externalHistory: history,\n outputSchema: schema,\n signal: abortSignal,\n } = normalizeRunOptions(\n queryOrOptions,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n signal\n );\n\n // Delegate to remote agent if in remote mode\n if (this.isRemote && this.remoteAgent) {\n const result = await this.remoteAgent.run(\n query,\n steps,\n manage,\n history,\n schema\n );\n return result as string | T;\n }\n\n let initializedHere = false;\n const startTime = Date.now();\n let success = false;\n let finalOutput: string | null = null;\n let stepsTaken = 0;\n\n try {\n // 1. Initialize if needed\n if (manage && !this._initialized) {\n await this.initialize();\n initializedHere = true;\n } else if (!this._initialized && this.autoInitialize) {\n await this.initialize();\n initializedHere = true;\n }\n\n if (!this._agentExecutor) {\n throw new Error(\"MCP agent failed to initialize\");\n }\n\n // Check for tool updates before starting execution (if using server manager)\n if (this.useServerManager && this.serverManager) {\n const currentTools = this.serverManager.tools;\n const currentToolNames = new Set(currentTools.map((t) => t.name));\n const existingToolNames = new Set(this._tools.map((t) => t.name));\n\n if (\n currentToolNames.size !== existingToolNames.size ||\n [...currentToolNames].some((n) => !existingToolNames.has(n))\n ) {\n logger.debug(\n `🔄 Tools changed before execution, updating agent. New tools: ${[...currentToolNames].join(\", \")}`\n );\n this._tools = currentTools;\n this._tools.push(...this.additionalTools);\n // Regenerate system message with ALL current tools\n await this.createSystemMessageFromTools(this._tools);\n // Recreate the agent executor with the new tools and system message\n this._agentExecutor = this.createAgent();\n }\n }\n\n // 2. Build inputs for the agent\n const historyToUse = history ?? this.conversationHistory;\n\n // Convert messages to format expected by LangChain agent\n const langchainHistory: BaseMessage[] = [];\n for (const msg of historyToUse) {\n if (\n this._isHumanMessageLike(msg) ||\n this._isAIMessageLike(msg) ||\n this._isToolMessageLike(msg)\n ) {\n langchainHistory.push(msg);\n }\n }\n\n const displayQuery =\n query.length > 50\n ? `${query.slice(0, 50).replace(/\\n/g, \" \")}...`\n : query.replace(/\\n/g, \" \");\n logger.debug(`💬 Received query: '${displayQuery}'`);\n logger.debug(\"🏁 Starting agent execution\");\n\n // 3. Stream using the built-in astream from CompiledStateGraph\n // The agent graph handles the loop internally\n // With dynamic tool reload: if tools change mid-execution, we interrupt and restart\n const maxRestarts = 3; // Prevent infinite restart loops\n let restartCount = 0;\n const accumulatedMessages: BaseMessage[] = [\n ...langchainHistory,\n new HumanMessage(query),\n ];\n\n while (restartCount <= maxRestarts) {\n // Update inputs with accumulated messages\n const inputs = { messages: accumulatedMessages };\n let shouldRestart = false;\n\n // Stream agent updates with observability callbacks\n const stream = await this._agentExecutor.stream(inputs, {\n streamMode: \"updates\", // Get updates as they happen\n callbacks: this.callbacks,\n metadata: this.getMetadata(),\n tags: this.getTags(),\n // Set trace name for LangChain/Langfuse\n runName: this.metadata.trace_name || \"mcp-use-agent\",\n // Set recursion limit to 3x maxSteps to account for model calls + tool executions\n recursionLimit: this.maxSteps * 3,\n // Pass sessionId for Langfuse if present in metadata\n ...(this.metadata.session_id && {\n sessionId: this.metadata.session_id,\n }),\n // Pass abort signal if provided\n ...(abortSignal && { signal: abortSignal }),\n });\n\n for await (const chunk of stream) {\n // Check for abort\n if (abortSignal?.aborted) {\n break;\n }\n\n // chunk is a dict with node names as keys\n // The agent node will have 'messages' with the AI response\n // The tools node will have 'messages' with tool calls and results\n\n for (const [nodeName, nodeOutput] of Object.entries(chunk)) {\n logger.debug(\n `📦 Node '${nodeName}' output: ${JSON.stringify(nodeOutput)}`\n );\n\n // Extract messages from the node output and accumulate them\n if (\n nodeOutput &&\n typeof nodeOutput === \"object\" &&\n \"messages\" in nodeOutput\n ) {\n let messages = (nodeOutput as any).messages;\n if (!Array.isArray(messages)) {\n messages = [messages];\n }\n\n // Add new messages to accumulated messages for potential restart\n for (const msg of messages) {\n if (!accumulatedMessages.includes(msg)) {\n accumulatedMessages.push(msg);\n }\n }\n\n for (const message of messages) {\n // Track tool calls\n if (\n \"tool_calls\" in message &&\n Array.isArray(message.tool_calls) &&\n message.tool_calls.length > 0\n ) {\n for (const toolCall of message.tool_calls) {\n const toolName = toolCall.name || \"unknown\";\n const toolInput = toolCall.args || {};\n this.toolsUsedNames.push(toolName);\n stepsTaken++;\n\n let toolInputStr = JSON.stringify(toolInput);\n if (toolInputStr.length > 100) {\n toolInputStr = `${toolInputStr.slice(0, 97)}...`;\n }\n logger.debug(\n `🔧 Tool call: ${toolName} with input: ${toolInputStr}`\n );\n\n // Yield tool call as AgentStep\n yield {\n action: {\n tool: toolName,\n toolInput,\n log: `Calling tool ${toolName}`,\n },\n observation: \"\", // Will be filled in by tool result\n };\n }\n }\n\n // Track tool results (ToolMessage)\n if (this._isToolMessageLike(message)) {\n const observation = message.content;\n let observationStr = String(observation);\n if (observationStr.length > 100) {\n observationStr = `${observationStr.slice(0, 97)}...`;\n }\n observationStr = observationStr.replace(/\\n/g, \" \");\n logger.debug(`📄 Tool result: ${observationStr}`);\n\n // --- Check for tool updates after tool results (safe restart point) ---\n if (this.useServerManager && this.serverManager) {\n const currentTools = this.serverManager.tools;\n const currentToolNames = new Set(\n currentTools.map((t) => t.name)\n );\n const existingToolNames = new Set(\n this._tools.map((t) => t.name)\n );\n\n if (\n currentToolNames.size !== existingToolNames.size ||\n [...currentToolNames].some(\n (n) => !existingToolNames.has(n)\n )\n ) {\n logger.debug(\n `🔄 Tools changed during execution. New tools: ${[...currentToolNames].join(\", \")}`\n );\n this._tools = currentTools;\n this._tools.push(...this.additionalTools);\n // Regenerate system message with ALL current tools\n await this.createSystemMessageFromTools(this._tools);\n // Recreate the agent executor with the new tools and system message\n this._agentExecutor = this.createAgent();\n\n // Set restart flag - safe to restart now after tool results\n shouldRestart = true;\n restartCount++;\n logger.debug(\n `🔃 Restarting execution with updated tools (restart ${restartCount}/${maxRestarts})`\n );\n break; // Break out of the message loop\n }\n }\n }\n\n // Track final AI message (without tool calls = final response)\n if (\n this._isAIMessageLike(message) &&\n !this._messageHasToolCalls(message)\n ) {\n finalOutput = this._normalizeOutput(\n this._getMessageContent(message)\n );\n logger.debug(\"✅ Agent finished with output\");\n }\n }\n\n // Break out of node loop if restarting\n if (shouldRestart) {\n break;\n }\n }\n }\n\n // Break out of chunk loop if restarting\n if (shouldRestart) {\n break;\n }\n }\n\n // Check if we should restart or if execution completed\n if (!shouldRestart) {\n // Execution completed successfully without tool changes\n break;\n }\n\n // If we've hit max restarts, log warning and continue\n if (restartCount > maxRestarts) {\n logger.warn(\n `⚠️ Max restarts (${maxRestarts}) reached. Continuing with current tools.`\n );\n break;\n }\n }\n\n // 4. Update conversation history\n if (this.memoryEnabled) {\n // Store all messages from execution (including tool calls and tool outputs)\n // Extract messages from current execution (skip the messages that were already in history)\n const newMessages = accumulatedMessages.slice(langchainHistory.length);\n for (const msg of newMessages) {\n this.addToHistory(msg);\n }\n }\n\n // 5. Handle structured output if requested\n if (schema && finalOutput) {\n try {\n logger.debug(\"🔧 Attempting structured output...\");\n const structuredResult = await this._attemptStructuredOutput<T>(\n finalOutput,\n this.llm!,\n schema\n );\n\n if (this.memoryEnabled) {\n this.addToHistory(\n new AIMessage(\n `Structured result: ${JSON.stringify(structuredResult)}`\n )\n );\n }\n\n logger.debug(\"✅ Structured output successful\");\n success = true;\n return structuredResult;\n } catch (e) {\n logger.error(`❌ Structured output failed: ${e}`);\n throw new Error(\n `Failed to generate structured output: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n\n // 6. Yield final result\n logger.debug(\n `🎉 Agent execution complete in ${((Date.now() - startTime) / 1000).toFixed(2)} seconds`\n );\n success = true;\n return (finalOutput || \"No output generated\") as string | T;\n } catch (e) {\n logger.error(`❌ Error running query: ${e}`);\n if (initializedHere && manage) {\n logger.debug(\"🧹 Cleaning up resources after error\");\n await this.close();\n }\n throw e;\n } finally {\n // Track comprehensive execution data\n const executionTimeMs = Date.now() - startTime;\n\n let serverCount = 0;\n if (this.client) {\n serverCount = Object.keys(this.client.getAllActiveSessions()).length;\n } else if (this.connectors) {\n serverCount = this.connectors.length;\n }\n\n const conversationHistoryLength = this.memoryEnabled\n ? this.conversationHistory.length\n : 0;\n\n // Safely access _tools in case initialization failed\n const toolsAvailable = this._tools || [];\n\n await this.telemetry.trackAgentExecution({\n executionMethod: \"stream\",\n query,\n success,\n modelProvider: this.modelProvider,\n modelName: this.modelName,\n serverCount,\n serverIdentifiers: this.connectors.map(\n (connector) => connector.publicIdentifier\n ),\n totalToolsAvailable: toolsAvailable.length,\n toolsAvailableNames: toolsAvailable.map((t) => t.name),\n maxStepsConfigured: this.maxSteps,\n memoryEnabled: this.memoryEnabled,\n useServerManager: this.useServerManager,\n maxStepsUsed: steps ?? null,\n manageConnector: manage ?? true,\n externalHistoryUsed: history !== undefined,\n stepsTaken,\n toolsUsedCount: this.toolsUsedNames.length,\n toolsUsedNames: this.toolsUsedNames,\n response: finalOutput || \"\",\n executionTimeMs,\n errorType: success ? null : \"execution_error\",\n conversationHistoryLength,\n });\n\n // Clean up if necessary\n if (manage && !this.client && initializedHere) {\n logger.debug(\"🧹 Closing agent after stream completion\");\n await this.close();\n }\n }\n }\n /**\n * Flush observability traces to the configured observability platform.\n * Important for serverless environments where traces need to be sent before function termination.\n */\n public async flush(): Promise<void> {\n // Delegate to remote agent if in remote mode\n if (this.isRemote && this.remoteAgent) {\n // Remote agents don't have observability manager\n return;\n }\n\n logger.debug(\"Flushing observability traces...\");\n await this.observabilityManager.flush();\n }\n\n /**\n * Flushes observability, closes owned MCP resources, and resets the executor.\n */\n public async close(): Promise<void> {\n // Delegate to remote agent if in remote mode\n if (this.isRemote && this.remoteAgent) {\n await this.remoteAgent.close();\n return;\n }\n\n logger.debug(\"🔌 Closing MCPAgent resources…\");\n\n // Shutdown observability handlers (important for serverless)\n await this.observabilityManager.shutdown();\n try {\n this._agentExecutor = null;\n this._tools = [];\n\n // Clean up client (always close if we own it, or if it exists in explicit mode)\n if (this.client) {\n // In simplified mode, we always own the client and should close it\n // In explicit mode, we only close if explicitly requested (current behavior)\n if (this.clientOwnedByAgent) {\n logger.debug(\n \"🔄 Closing internally-created client (simplified mode) and cleaning up resources\"\n );\n await this.client.close();\n this.sessions = {};\n this.client = undefined;\n } else {\n logger.debug(\"🔄 Closing client and cleaning up resources\");\n await this.client.close();\n this.sessions = {};\n }\n } else {\n for (const connector of this.connectors) {\n logger.debug(\"🔄 Disconnecting connector\");\n await connector.disconnect();\n }\n }\n\n // Clean up LLM reference (important for simplified mode)\n if (this.isSimplifiedMode && this.llm) {\n logger.debug(\"🔄 Clearing LLM reference (simplified mode)\");\n this.llm = undefined;\n }\n\n if (\"connectorToolMap\" in this.adapter) {\n this.adapter = new LangChainAdapter();\n }\n } finally {\n this._initialized = false;\n logger.debug(\"👋 Agent closed successfully\");\n }\n }\n\n /**\n * Yields with pretty-printed output for code mode with options object.\n */\n public prettyStreamEvents(\n options: RunOptions\n ): AsyncGenerator<void, string, void>;\n\n /**\n * Yields with pretty-printed output for code mode with options object and structured output.\n */\n public prettyStreamEvents<T>(\n options: RunOptions<T>\n ): AsyncGenerator<void, string, void>;\n\n /**\n * Yields with pretty-printed output for code mode.\n * This method formats and displays tool executions in a user-friendly way for the terminal.\n * @deprecated Use the options object instead: `prettyStreamEvents({ prompt, maxSteps, ... })`.\n */\n public prettyStreamEvents<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): AsyncGenerator<void, string, void>;\n\n public async *prettyStreamEvents<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector = true,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): AsyncGenerator<void, string, void> {\n const { prettyStreamEvents: prettyStream } = await import(\"./display.js\");\n\n const finalResponse = \"\";\n\n for await (const _ of prettyStream(\n this.streamEvents(\n queryOrOptions as any,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema\n )\n )) {\n yield;\n }\n\n return finalResponse;\n }\n\n /**\n * Yields LangChain StreamEvent objects with options object.\n */\n public streamEvents(\n options: RunOptions\n ): AsyncGenerator<StreamEvent, void, void>;\n\n /**\n * Yields LangChain StreamEvent objects with options object and structured output.\n */\n public streamEvents<T>(\n options: RunOptions<T>\n ): AsyncGenerator<StreamEvent, void, void>;\n\n /**\n * Yields LangChain StreamEvent objects from the underlying streamEvents() method.\n * This provides token-level streaming and fine-grained event updates.\n * @deprecated Use the options object instead: `streamEvents({ prompt, maxSteps, ... })`.\n */\n public streamEvents<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): AsyncGenerator<StreamEvent, void, void>;\n\n public async *streamEvents<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector = true,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>,\n signal?: AbortSignal\n ): AsyncGenerator<StreamEvent, void, void> {\n // Normalize input to internal parameters\n const normalized = normalizeRunOptions(\n queryOrOptions,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n signal\n );\n let { query } = normalized;\n const {\n maxSteps: steps,\n manageConnector: manage,\n externalHistory: history,\n outputSchema: schema,\n signal: abortSignal,\n } = normalized;\n\n let initializedHere = false;\n const startTime = Date.now();\n let success = false;\n let eventCount = 0;\n let totalResponseLength = 0;\n let finalResponse = \"\";\n\n // Enhance query with schema information if structured output is requested\n if (schema) {\n query = this._enhanceQueryWithSchema(query, schema);\n }\n\n try {\n // Initialize if needed\n if (manage && !this._initialized) {\n await this.initialize();\n initializedHere = true;\n } else if (!this._initialized && this.autoInitialize) {\n await this.initialize();\n initializedHere = true;\n }\n\n const agentExecutor = this._agentExecutor;\n if (!agentExecutor) {\n throw new Error(\"MCP agent failed to initialize\");\n }\n\n // Set max iterations\n this.maxSteps = steps ?? this.maxSteps;\n\n const display_query =\n typeof query === \"string\" && query.length > 50\n ? `${query.slice(0, 50).replace(/\\n/g, \" \")}...`\n : typeof query === \"string\"\n ? query.replace(/\\n/g, \" \")\n : String(query);\n logger.debug(`💬 Received query for streamEvents: '${display_query}'`);\n\n // Add user message to history if memory enabled\n if (this.memoryEnabled) {\n logger.debug(`🔄 Adding user message to history: ${display_query}`);\n this.addToHistory(new HumanMessage({ content: query }));\n }\n\n // Prepare history\n const historyToUse = history ?? this.conversationHistory;\n const langchainHistory: BaseMessage[] = [];\n for (const msg of historyToUse) {\n if (\n this._isHumanMessageLike(msg) ||\n this._isAIMessageLike(msg) ||\n this._isToolMessageLike(msg)\n ) {\n langchainHistory.push(msg);\n } else {\n logger.debug(\n `⚠️ Skipped message of type: ${msg.constructor?.name || typeof msg}`\n );\n }\n }\n\n // Prepare inputs\n const inputs: BaseMessage[] = [\n ...langchainHistory,\n new HumanMessage(query),\n ];\n\n logger.debug(\"callbacks\", this.callbacks);\n\n // Stream events from the agent executor with observability support\n const eventStream = agentExecutor.streamEvents(\n { messages: inputs },\n {\n streamMode: \"messages\",\n version: \"v2\",\n callbacks: this.callbacks,\n metadata: this.getMetadata(),\n tags: this.getTags(),\n // Set trace name for LangChain/Langfuse\n runName: this.metadata.trace_name || \"mcp-use-agent\",\n // Set recursion limit to 3x maxSteps to account for model calls + tool executions\n recursionLimit: this.maxSteps * 3,\n // Pass sessionId for Langfuse if present in metadata\n ...(this.metadata.session_id && {\n sessionId: this.metadata.session_id,\n }),\n // Pass abort signal if provided\n ...(abortSignal && { signal: abortSignal }),\n }\n );\n\n // Yield each event\n for await (const event of eventStream) {\n // Check for abort\n if (abortSignal?.aborted) {\n break;\n }\n\n eventCount++;\n\n // Skip null or invalid events\n if (!event || typeof event !== \"object\") {\n continue;\n }\n\n // Track response length for telemetry\n if (\n event.event === \"on_chat_model_stream\" &&\n event.data?.chunk?.content\n ) {\n totalResponseLength += event.data.chunk.content.length;\n }\n\n // Capture AI message content as it streams\n if (event.event === \"on_chat_model_stream\" && event.data?.chunk) {\n const chunk = event.data.chunk;\n if (chunk.content) {\n if (!finalResponse) {\n finalResponse = \"\";\n }\n // Normalize the content to ensure it's a string\n const normalizedContent = this._normalizeOutput(chunk.content);\n finalResponse += normalizedContent;\n logger.debug(\n `📝 Accumulated response length: ${finalResponse.length}`\n );\n }\n }\n\n yield event;\n\n // Capture final response from chain end event (fallback)\n if (\n event.event === \"on_chain_end\" &&\n event.data?.output &&\n !finalResponse\n ) {\n const output = event.data.output;\n if (Array.isArray(output) && output.length > 0 && output[0]?.text) {\n finalResponse = output[0].text;\n } else if (typeof output === \"string\") {\n finalResponse = output;\n } else if (\n output &&\n typeof output === \"object\" &&\n \"output\" in output\n ) {\n finalResponse = output.output;\n }\n }\n }\n\n // Convert to structured output if requested\n if (schema && finalResponse) {\n logger.debug(\"🔧 Attempting structured output conversion...\");\n\n try {\n // Start the conversion (non-blocking)\n let conversionCompleted = false;\n let conversionResult: T | null = null;\n let conversionError: Error | null = null;\n\n this._attemptStructuredOutput<T>(finalResponse, this.llm!, schema)\n .then((result) => {\n conversionCompleted = true;\n conversionResult = result;\n return result;\n })\n .catch((error) => {\n conversionCompleted = true;\n conversionError = error;\n throw error;\n });\n\n // Yield progress events while conversion is running\n let progressCount = 0;\n\n while (!conversionCompleted) {\n // Wait 2 seconds\n await new Promise((resolve) => setTimeout(resolve, 2000));\n\n if (!conversionCompleted) {\n // Still running - yield progress event\n progressCount++;\n yield {\n event: \"on_structured_output_progress\",\n data: {\n message: `Converting to structured output... (${progressCount * 2}s)`,\n elapsed: progressCount * 2,\n },\n } as unknown as StreamEvent;\n }\n }\n\n // Check if conversion succeeded or failed\n if (conversionError) {\n throw conversionError;\n }\n\n if (conversionResult) {\n // Yield structured result as a custom event\n yield {\n event: \"on_structured_output\",\n data: { output: conversionResult },\n } as unknown as StreamEvent;\n\n if (this.memoryEnabled) {\n this.addToHistory(\n new AIMessage(\n `Structured result: ${JSON.stringify(conversionResult)}`\n )\n );\n }\n\n logger.debug(\"✅ Structured output successful\");\n }\n } catch (e) {\n logger.warn(`⚠️ Structured output failed: ${e}`);\n // Yield error event\n yield {\n event: \"on_structured_output_error\",\n data: { error: e instanceof Error ? e.message : String(e) },\n } as unknown as StreamEvent;\n }\n } else if (this.memoryEnabled && finalResponse) {\n // Add the final AI response to conversation history if memory is enabled\n this.addToHistory(new AIMessage(finalResponse));\n }\n console.log(\"\\n\\n\");\n logger.debug(`🎉 StreamEvents complete - ${eventCount} events emitted`);\n success = true;\n } catch (e) {\n logger.error(`❌ Error during streamEvents: ${e}`);\n if (initializedHere && manage) {\n logger.debug(\n \"🧹 Cleaning up resources after initialization error in streamEvents\"\n );\n await this.close();\n }\n throw e;\n } finally {\n // Track telemetry\n const executionTimeMs = Date.now() - startTime;\n\n let serverCount = 0;\n if (this.client) {\n serverCount = Object.keys(this.client.getAllActiveSessions()).length;\n } else if (this.connectors) {\n serverCount = this.connectors.length;\n }\n\n const conversationHistoryLength = this.memoryEnabled\n ? this.conversationHistory.length\n : 0;\n\n await this.telemetry.trackAgentExecution({\n executionMethod: \"streamEvents\",\n query,\n success,\n modelProvider: this.modelProvider,\n modelName: this.modelName,\n serverCount,\n serverIdentifiers: this.connectors.map(\n (connector) => connector.publicIdentifier\n ),\n totalToolsAvailable: this._tools.length,\n toolsAvailableNames: this._tools.map((t) => t.name),\n maxStepsConfigured: this.maxSteps,\n memoryEnabled: this.memoryEnabled,\n useServerManager: this.useServerManager,\n maxStepsUsed: steps ?? null,\n manageConnector: manage ?? true,\n externalHistoryUsed: history !== undefined,\n response: `[STREAMED RESPONSE - ${totalResponseLength} chars]`,\n executionTimeMs,\n errorType: success ? null : \"streaming_error\",\n conversationHistoryLength,\n });\n\n // Clean up if needed\n if (manage && !this.client && initializedHere) {\n logger.debug(\"🧹 Closing agent after streamEvents completion\");\n await this.close();\n }\n }\n }\n\n /**\n * Attempt to create structured output from raw result with validation and retry logic.\n *\n * @param rawResult - The raw text result from the agent\n * @param llm - LLM to use for structured output\n * @param outputSchema - The Zod schema to validate against\n */\n private async _attemptStructuredOutput<T>(\n rawResult: string | any,\n llm: LanguageModel,\n outputSchema: ZodSchema<T>\n ): Promise<T> {\n logger.debug(\n `🔄 Attempting structured output with schema: ${JSON.stringify(outputSchema, null, 2)}`\n );\n logger.debug(`🔄 Raw result: ${JSON.stringify(rawResult, null, 2)}`);\n\n // Schema-aware setup for structured output\n let structuredLlm: LanguageModel = null;\n let schemaDescription = \"\";\n\n logger.debug(\n `🔄 Structured output requested, schema: ${JSON.stringify(toJSONSchema(outputSchema), null, 2)}`\n );\n // Check if withStructuredOutput method exists\n if (\n llm &&\n \"withStructuredOutput\" in llm &&\n typeof (llm as any).withStructuredOutput === \"function\"\n ) {\n structuredLlm = (llm as any).withStructuredOutput(outputSchema);\n } else if (llm) {\n // Fallback: use the same LLM but we'll handle structure in our helper method\n structuredLlm = llm;\n } else {\n throw new Error(\"LLM is required for structured output\");\n }\n const jsonSchema = toJSONSchema(outputSchema) as any;\n const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;\n schemaDescription = JSON.stringify(cleanSchema, null, 2);\n logger.debug(`🔄 Schema description: ${schemaDescription}`);\n\n // Handle different input formats - rawResult might be an array or object from the agent\n let textContent: string = \"\";\n if (typeof rawResult === \"string\") {\n textContent = rawResult;\n } else if (rawResult && typeof rawResult === \"object\") {\n // Handle object format\n textContent = JSON.stringify(rawResult);\n }\n\n logger.debug(\"rawResult\", rawResult);\n\n // If we couldn't extract text, use the stringified version\n if (!textContent) {\n textContent = JSON.stringify(rawResult);\n }\n\n // Get detailed schema information for better prompting\n const maxRetries = 3;\n let lastError: string = \"\";\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n logger.debug(`🔄 Structured output attempt ${attempt}/${maxRetries}`);\n\n let formatPrompt = `\n Please format the following information according to the EXACT schema specified below.\n You must use the exact field names and types as shown in the schema.\n\n Required schema format:\n ${schemaDescription}\n\n Content to extract from:\n ${textContent}\n\n IMPORTANT:\n - Use ONLY the field names specified in the schema\n - Match the data types exactly (string, number, boolean, array, etc.)\n - Include ALL required fields\n - Return valid JSON that matches the schema structure exactly\n - For missing data: use null for nullable fields, omit optional fields entirely\n - Do NOT use empty strings (\"\") or zero (0) as placeholders for missing data\n `;\n\n // Add specific error feedback for retry attempts\n if (attempt > 1) {\n formatPrompt += `\n\n PREVIOUS ATTEMPT FAILED with error: ${lastError}\n Please fix the issues mentioned above and ensure the output matches the schema exactly.\n `;\n }\n\n try {\n logger.debug(\n `🔄 Structured output attempt ${attempt} - using streaming approach`\n );\n const contentPreview =\n textContent.length > 300\n ? `${textContent.slice(0, 300)}...`\n : textContent;\n logger.debug(\n `🔄 Content being formatted (${textContent.length} chars): ${contentPreview}`\n );\n\n // Log the full prompt being sent to LLM\n logger.debug(\n `🔄 Full format prompt (${formatPrompt.length} chars):\\n${formatPrompt}`\n );\n\n // Use streaming to avoid blocking the event loop\n const stream = await structuredLlm!.stream(formatPrompt);\n let structuredResult = null;\n let chunkCount = 0;\n\n for await (const chunk of stream) {\n chunkCount++;\n\n // Print the chunk for debugging\n logger.debug(\n `Chunk ${chunkCount}: ${JSON.stringify(chunk, null, 2)}`\n );\n\n // Handle different chunk types\n if (typeof chunk === \"string\") {\n // If it's a string, try to parse it as JSON\n try {\n structuredResult = JSON.parse(chunk);\n } catch (e) {\n logger.warn(`🔄 Failed to parse string chunk as JSON: ${chunk}`);\n }\n } else if (chunk && typeof chunk === \"object\") {\n // If it's already an object, use it directly\n structuredResult = chunk;\n } else {\n // Convert other types to string and try to parse\n try {\n structuredResult = JSON.parse(String(chunk));\n } catch (e) {\n logger.warn(`🔄 Failed to parse chunk as JSON: ${chunk}`);\n }\n }\n\n if (chunkCount % 10 === 0) {\n logger.debug(\n `🔄 Structured output streaming: ${chunkCount} chunks`\n );\n }\n }\n\n logger.debug(\n `🔄 Structured result attempt ${attempt}: ${JSON.stringify(structuredResult, null, 2)}`\n );\n\n // Use the structured result directly (no need to parse)\n if (!structuredResult) {\n throw new Error(\"No structured result received from stream\");\n }\n\n // Validate the structured result\n const validatedResult = this._validateStructuredResult(\n structuredResult,\n outputSchema\n );\n logger.debug(`✅ Structured output successful on attempt ${attempt}`);\n return validatedResult;\n } catch (e) {\n lastError = e instanceof Error ? e.message : String(e);\n logger.warn(\n `⚠️ Structured output attempt ${attempt} failed: ${lastError}`\n );\n\n if (attempt === maxRetries) {\n logger.error(\n `❌ All ${maxRetries} structured output attempts failed`\n );\n throw new Error(\n `Failed to generate valid structured output after ${maxRetries} attempts. Last error: ${lastError}`\n );\n }\n\n // Continue to next attempt\n continue;\n }\n }\n\n // This should never be reached, but TypeScript requires it\n throw new Error(\"Unexpected error in structured output generation\");\n }\n\n /**\n * Validate the structured result against the schema with detailed error reporting\n */\n private _validateStructuredResult<T>(\n structuredResult: any,\n outputSchema: ZodSchema<T>\n ): T {\n // Use Zod to validate the structured result\n try {\n // Use Zod to validate the structured result\n const validatedResult = outputSchema.parse(structuredResult);\n\n // Additional validation for required fields\n const schemaType = outputSchema as any;\n if (schemaType._def && schemaType._def.shape) {\n for (const [fieldName, fieldSchema] of Object.entries(\n schemaType._def.shape\n )) {\n const field = fieldSchema as any;\n const isOptional =\n field.isOptional?.() ?? field._def?.typeName === \"ZodOptional\";\n const isNullable =\n field.isNullable?.() ?? field._def?.typeName === \"ZodNullable\";\n if (!isOptional && !isNullable) {\n const value = (validatedResult as any)[fieldName];\n if (\n value === null ||\n value === undefined ||\n (typeof value === \"string\" && !value.trim()) ||\n (Array.isArray(value) && value.length === 0)\n ) {\n throw new Error(\n `Required field '${fieldName}' is missing or empty`\n );\n }\n }\n }\n }\n\n return validatedResult;\n } catch (e) {\n logger.debug(`Validation details: ${e}`);\n throw e; // Re-raise to trigger retry logic\n }\n }\n\n /**\n * Enhance the query with schema information to make the agent aware of required fields.\n */\n private _enhanceQueryWithSchema<T>(\n query: string,\n outputSchema: ZodSchema<T>\n ): string {\n try {\n const jsonSchema = toJSONSchema(outputSchema) as any;\n const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;\n const schemaDescription = JSON.stringify(cleanSchema, null, 2);\n\n // Enhance the query with schema awareness\n const enhancedQuery = `\n ${query}\n\n IMPORTANT: Your response must include sufficient information to populate the following structured output:\n\n ${schemaDescription}\n\n Make sure you gather ALL the required information during your task execution.\n If any required information is missing, continue working to find it.\n `;\n\n return enhancedQuery;\n } catch (e) {\n logger.warn(`Could not extract schema details: ${e}`);\n return query;\n }\n }\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type {\n CallToolResult,\n Tool as MCPTool,\n Resource,\n Prompt,\n} from \"@modelcontextprotocol/client\";\nimport type { BaseConnector } from \"@mcp-use/client\";\n\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\nimport { BaseAdapter } from \"./base.js\";\n\nfunction schemaToZod(schema: unknown): z.ZodType {\n try {\n // MCP tool inputSchema is JSON Schema; Zod 4 converts natively.\n return z.fromJSONSchema(schema as Record<string, unknown>);\n } catch (err) {\n logger.warn(`Failed to convert JSON schema to Zod: ${err}`);\n return z.any();\n }\n}\n\nfunction sanitizeToolName(name: string): string {\n return name\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase()\n .replace(/^_+|_+$/g, \"\");\n}\n\n/** Converts MCP tools, resources, and prompts into LangChain structured tools. */\nexport class LangChainAdapter extends BaseAdapter<StructuredToolInterface> {\n private usedToolNames: Set<string> = new Set();\n\n /**\n * @param disallowedTools - MCP tool names to omit during conversion.\n */\n constructor(disallowedTools: string[] = []) {\n super(disallowedTools);\n }\n\n private reserveName(name: string, kind?: \"resource\" | \"prompt\"): string {\n if (!this.usedToolNames.has(name)) {\n this.usedToolNames.add(name);\n return name;\n }\n if (kind) {\n const prefixed = `${kind}_${name}`;\n if (!this.usedToolNames.has(prefixed)) {\n this.usedToolNames.add(prefixed);\n return prefixed;\n }\n // Both base name and prefixed name are taken; fall back to a numeric suffix.\n let i = 2;\n while (this.usedToolNames.has(`${prefixed}_${i}`)) i++;\n const fallback = `${prefixed}_${i}`;\n this.usedToolNames.add(fallback);\n return fallback;\n }\n // No kind: use a numeric suffix to avoid collision.\n let i = 2;\n while (this.usedToolNames.has(`${name}_${i}`)) i++;\n const fallback = `${name}_${i}`;\n this.usedToolNames.add(fallback);\n return fallback;\n }\n\n /**\n * Converts MCP tools from all connectors and resets name deduplication.\n *\n * @param connectors - Connected MCP connectors.\n * @returns LangChain structured tools.\n */\n public override async createToolsFromConnectors(\n connectors: BaseConnector[]\n ): Promise<StructuredToolInterface[]> {\n // Reset names at the start of each loading cycle.\n this.usedToolNames.clear();\n return super.createToolsFromConnectors(connectors);\n }\n\n /**\n * Convert a single MCP tool specification into a LangChainJS structured tool.\n */\n protected convertTool(\n mcpTool: MCPTool,\n connector: BaseConnector\n ): StructuredToolInterface | null {\n // Filter out disallowed tools early.\n if (this.disallowedTools.includes(mcpTool.name)) {\n return null;\n }\n\n // Derive a strict Zod schema for the tool's arguments.\n const argsSchema: z.ZodType = mcpTool.inputSchema\n ? schemaToZod(mcpTool.inputSchema)\n : z.object({}).optional();\n\n const toolName = this.reserveName(mcpTool.name ?? \"NO NAME\");\n const tool = new DynamicStructuredTool({\n name: toolName,\n description: mcpTool.description ?? \"\", // Blank is acceptable but discouraged.\n schema: argsSchema,\n func: async (input: Record<string, any>): Promise<string> => {\n logger.debug(\n `MCP tool \"${mcpTool.name}\" received input: ${JSON.stringify(input)}`\n );\n try {\n const result: CallToolResult = await connector.callTool(\n mcpTool.name,\n input\n );\n return JSON.stringify(result);\n } catch (err: any) {\n logger.error(`Error executing MCP tool: ${err.message}`);\n return `Error executing MCP tool: ${String(err)}`;\n }\n },\n });\n\n return tool;\n }\n\n /**\n * Convert a single MCP resource into a LangChainJS structured tool.\n * Each resource becomes an async tool that returns its content when called.\n */\n protected convertResource(\n mcpResource: Resource,\n connector: BaseConnector\n ): StructuredToolInterface | null {\n const resourceBaseName =\n sanitizeToolName(mcpResource.name || mcpResource.uri) || \"resource\";\n const resourceName = this.reserveName(resourceBaseName, \"resource\");\n const resourceUri = mcpResource.uri;\n\n const tool = new DynamicStructuredTool({\n name: resourceName,\n description:\n mcpResource.description ||\n `Return the content of the resource located at URI ${resourceUri}.`,\n schema: z.object({}).optional(), // Resources take no arguments\n func: async (): Promise<string> => {\n logger.debug(`Resource tool: \"${resourceName}\" called`);\n try {\n const result = await connector.readResource(resourceUri);\n if (result.contents && result.contents.length > 0) {\n return result.contents\n .map((content: any) => {\n if (typeof content === \"string\") {\n return content;\n }\n if (content.text) {\n return content.text;\n }\n if (content.uri) {\n return content.uri;\n }\n return JSON.stringify(content);\n })\n .join(\"\\n\");\n }\n return \"Resource is empty or unavailable\";\n } catch (err: any) {\n logger.error(`Error reading resource: ${err.message}`);\n return `Error reading resource: ${String(err)}`;\n }\n },\n });\n\n return tool;\n }\n\n /**\n * Convert a single MCP prompt into a LangChainJS structured tool.\n * The resulting tool executes getPrompt on the connector with the prompt's name\n * and the user-provided arguments (if any).\n */\n protected convertPrompt(\n mcpPrompt: Prompt,\n connector: BaseConnector\n ): StructuredToolInterface | null {\n // Build Zod schema from prompt arguments\n let argsSchema: z.ZodType = z.object({}).optional();\n\n if (mcpPrompt.arguments && mcpPrompt.arguments.length > 0) {\n const schemaFields: Record<string, z.ZodType> = {};\n for (const arg of mcpPrompt.arguments) {\n // All arguments default to string type since type is not available in Prompt definition\n // (Note: MCP spec includes type, but SDK TypeScript types don't)\n const zodType: z.ZodType = z.string();\n\n if (arg.required !== false) {\n schemaFields[arg.name] = zodType;\n } else {\n schemaFields[arg.name] = zodType.optional();\n }\n }\n argsSchema =\n Object.keys(schemaFields).length > 0\n ? z.object(schemaFields)\n : z.object({}).optional();\n }\n\n const promptBaseName =\n sanitizeToolName(mcpPrompt.name || \"prompt\") || \"prompt\";\n const promptName = this.reserveName(promptBaseName, \"prompt\");\n const tool = new DynamicStructuredTool({\n name: promptName,\n description: mcpPrompt.description || \"\",\n schema: argsSchema,\n func: async (input: Record<string, any>): Promise<string> => {\n logger.debug(\n `Prompt tool: \"${mcpPrompt.name}\" called with args: ${JSON.stringify(input)}`\n );\n try {\n const result = await connector.getPrompt(mcpPrompt.name, input);\n if (result.messages && result.messages.length > 0) {\n return result.messages\n .map((msg: any) => {\n if (typeof msg === \"string\") {\n return msg;\n }\n if (msg.content) {\n return typeof msg.content === \"string\"\n ? msg.content\n : JSON.stringify(msg.content);\n }\n return JSON.stringify(msg);\n })\n .join(\"\\n\");\n }\n return \"Prompt returned no messages\";\n } catch (err: any) {\n logger.error(`Error getting prompt: ${err.message}`);\n return `Error getting prompt: ${String(err)}`;\n }\n },\n });\n\n return tool;\n }\n}\n","import type { MCPClient } from \"@mcp-use/client\";\nimport type { BaseConnector } from \"@mcp-use/client\";\nimport { logger } from \"@mcp-use/client\";\n\n/**\n * Abstract base class for converting MCP tools to other framework formats.\n *\n * This class defines the common interface that all adapter implementations\n * should follow to ensure consistency across different frameworks.\n */\nexport abstract class BaseAdapter<T> {\n /**\n * List of tool names that should not be available.\n */\n protected readonly disallowedTools: string[];\n\n /**\n * Internal cache that maps a connector instance to the list of tools\n * generated for it.\n */\n private readonly connectorToolMap: Map<BaseConnector, T[]> = new Map();\n\n /**\n * @param disallowedTools - MCP tool names to omit during conversion.\n */\n constructor(disallowedTools?: string[]) {\n this.disallowedTools = disallowedTools ?? [];\n }\n\n /**\n * Create tools from an MCPClient instance.\n *\n * This is the recommended way to create tools from an MCPClient, as it handles\n * session creation and connector extraction automatically.\n *\n * @param client - The MCPClient to extract tools from.\n * @param disallowedTools - Optional list of tool names to exclude.\n * @returns A promise that resolves with a list of converted tools.\n */\n static async createTools<TTool, TAdapter extends BaseAdapter<TTool>>(\n this: new (disallowedTools?: string[]) => TAdapter,\n client: MCPClient,\n disallowedTools?: string[]\n ): Promise<TTool[]> {\n // Create the adapter\n const adapter = new this(disallowedTools);\n\n // Ensure we have active sessions\n if (\n !client.activeSessions ||\n Object.keys(client.activeSessions).length === 0\n ) {\n logger.debug(\"No active sessions found, creating new ones...\");\n await client.createAllSessions();\n }\n\n // Get all active sessions\n const sessions = client.getAllActiveSessions();\n\n // Extract connectors from sessions\n const connectors: BaseConnector[] = Object.values(sessions).map(\n (session) => session.connector\n );\n\n // Create tools from connectors\n return adapter.createToolsFromConnectors(connectors);\n }\n\n /**\n * Dynamically load tools for a specific connector.\n *\n * @param connector - The connector to load tools for.\n * @returns The list of tools that were loaded in the target framework's format.\n */\n async loadToolsForConnector(connector: BaseConnector): Promise<T[]> {\n // Return cached tools if we already processed this connector\n if (this.connectorToolMap.has(connector)) {\n const cached = this.connectorToolMap.get(connector)!;\n logger.debug(`Returning ${cached.length} existing tools for connector`);\n return cached;\n }\n\n const connectorTools: T[] = [];\n\n // Make sure the connector is initialized and has tools\n const success = await this.ensureConnectorInitialized(connector);\n if (!success) {\n return [];\n }\n\n // Convert and collect tools\n for (const tool of connector.tools) {\n const converted = this.convertTool(tool, connector);\n if (converted) {\n connectorTools.push(converted);\n }\n }\n\n // Cache the tools for this connector\n this.connectorToolMap.set(connector, connectorTools);\n\n // Log for debugging purposes\n logger.debug(\n `Loaded ${connectorTools.length} new tools for connector: ${connectorTools\n .map((t: any) => t?.name ?? String(t))\n .join(\", \")}`\n );\n\n return connectorTools;\n }\n\n /**\n * Convert an MCP tool to the target framework's tool format.\n *\n * @param mcpTool - The MCP tool definition to convert.\n * @param connector - The connector that provides this tool.\n * @returns The converted tool, or null / undefined if no tool should be produced.\n */\n protected abstract convertTool(\n mcpTool: Record<string, any>,\n connector: BaseConnector\n ): T | null | undefined;\n\n /**\n * Convert an MCP resource to the target framework's tool format.\n *\n * @param mcpResource - The MCP resource definition to convert.\n * @param connector - The connector that provides this resource.\n * @returns The converted resource as a tool, or null / undefined if no tool should be produced.\n */\n protected abstract convertResource?(\n mcpResource: Record<string, any>,\n connector: BaseConnector\n ): T | null | undefined;\n\n /**\n * Convert an MCP prompt to the target framework's tool format.\n *\n * @param mcpPrompt - The MCP prompt definition to convert.\n * @param connector - The connector that provides this prompt.\n * @returns The converted prompt as a tool, or null / undefined if no tool should be produced.\n */\n protected abstract convertPrompt?(\n mcpPrompt: Record<string, any>,\n connector: BaseConnector\n ): T | null | undefined;\n\n /**\n * Create tools from MCP tools in all provided connectors.\n *\n * @param connectors - List of MCP connectors to create tools from.\n * @returns A promise that resolves with all converted tools.\n */\n public async createToolsFromConnectors(\n connectors: BaseConnector[]\n ): Promise<T[]> {\n const tools: T[] = [];\n for (const connector of connectors) {\n const connectorTools = await this.loadToolsForConnector(connector);\n tools.push(...connectorTools);\n }\n\n logger.debug(`Available tools: ${tools.length}`);\n return tools;\n }\n\n /**\n * Dynamically load resources for a specific connector.\n *\n * @param connector - The connector to load resources for.\n * @returns The list of resources that were loaded in the target framework's format.\n */\n async loadResourcesForConnector(connector: BaseConnector): Promise<T[]> {\n const connectorResources: T[] = [];\n\n // Make sure the connector is initialized\n const success = await this.ensureConnectorInitialized(connector);\n if (!success) {\n return [];\n }\n\n try {\n // Get resources from connector\n const resourcesResult = await connector.listAllResources();\n const resources = resourcesResult?.resources || [];\n\n // Convert and collect resources\n if (this.convertResource) {\n for (const resource of resources) {\n const converted = this.convertResource(resource, connector);\n if (converted) {\n connectorResources.push(converted);\n }\n }\n }\n\n logger.debug(\n `Loaded ${connectorResources.length} new resources for connector: ${connectorResources\n .map((r: any) => r?.name ?? String(r))\n .join(\", \")}`\n );\n } catch (err) {\n logger.warn(`Error loading resources for connector: ${err}`);\n }\n\n return connectorResources;\n }\n\n /**\n * Dynamically load prompts for a specific connector.\n *\n * @param connector - The connector to load prompts for.\n * @returns The list of prompts that were loaded in the target framework's format.\n */\n async loadPromptsForConnector(connector: BaseConnector): Promise<T[]> {\n const connectorPrompts: T[] = [];\n\n // Make sure the connector is initialized\n const success = await this.ensureConnectorInitialized(connector);\n if (!success) {\n return [];\n }\n\n try {\n // Get prompts from connector\n const promptsResult = await connector.listPrompts();\n const prompts = promptsResult?.prompts || [];\n\n // Convert and collect prompts\n if (this.convertPrompt) {\n for (const prompt of prompts) {\n const converted = this.convertPrompt(prompt, connector);\n if (converted) {\n connectorPrompts.push(converted);\n }\n }\n }\n\n logger.debug(\n `Loaded ${connectorPrompts.length} new prompts for connector: ${connectorPrompts\n .map((p: any) => p?.name ?? String(p))\n .join(\", \")}`\n );\n } catch (err) {\n logger.warn(`Error loading prompts for connector: ${err}`);\n }\n\n return connectorPrompts;\n }\n\n /**\n * Create resources from MCP resources in all provided connectors.\n *\n * @param connectors - List of MCP connectors to create resources from.\n * @returns A promise that resolves with all converted resources.\n */\n public async createResourcesFromConnectors(\n connectors: BaseConnector[]\n ): Promise<T[]> {\n const resources: T[] = [];\n for (const connector of connectors) {\n const connectorResources =\n await this.loadResourcesForConnector(connector);\n resources.push(...connectorResources);\n }\n\n logger.debug(`Available resources: ${resources.length}`);\n return resources;\n }\n\n /**\n * Create prompts from MCP prompts in all provided connectors.\n *\n * @param connectors - List of MCP connectors to create prompts from.\n * @returns A promise that resolves with all converted prompts.\n */\n public async createPromptsFromConnectors(\n connectors: BaseConnector[]\n ): Promise<T[]> {\n const prompts: T[] = [];\n for (const connector of connectors) {\n const connectorPrompts = await this.loadPromptsForConnector(connector);\n prompts.push(...connectorPrompts);\n }\n\n logger.debug(`Available prompts: ${prompts.length}`);\n return prompts;\n }\n\n /**\n * Check if a connector is initialized and has tools.\n *\n * @param connector - The connector to check.\n * @returns True if the connector is initialized and has tools, false otherwise.\n */\n private checkConnectorInitialized(connector: BaseConnector): boolean {\n return Boolean(connector.tools && connector.tools.length);\n }\n\n /**\n * Ensure a connector is initialized.\n *\n * @param connector - The connector to initialize.\n * @returns True if initialization succeeded, false otherwise.\n */\n private async ensureConnectorInitialized(\n connector: BaseConnector\n ): Promise<boolean> {\n if (!this.checkConnectorInitialized(connector)) {\n logger.debug(\"Connector doesn't have tools, initializing it\");\n try {\n await connector.initialize();\n return true;\n } catch (err) {\n logger.error(`Error initializing connector: ${err}`);\n return false;\n }\n }\n return true;\n }\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { LangChainAdapter } from \"../adapters/langchain_adapter.js\";\nimport type { MCPClient } from \"@mcp-use/client\";\nimport type { BaseConnector } from \"@mcp-use/client\";\nimport type { MCPSession } from \"@mcp-use/client\";\nimport type { IServerManager } from \"./types.js\";\nimport { logger } from \"@mcp-use/client\";\nimport { AcquireActiveMCPServerTool } from \"./tools/acquire_active_mcp_server.js\";\nimport { AddMCPServerFromConfigTool } from \"./tools/add_server_from_config.js\";\nimport { ConnectMCPServerTool } from \"./tools/connect_mcp_server.js\";\nimport { ListMCPServersTool } from \"./tools/list_mcp_servers.js\";\nimport { ReleaseMCPServerConnectionTool } from \"./tools/release_mcp_server_connection.js\";\n\n/**\n * Deep equality check for comparing objects and arrays\n * Handles nested structures, primitives, arrays, and objects\n */\nfunction isEqual(a: any, b: any): boolean {\n // Handle identical references and primitives\n if (a === b) return true;\n\n // Handle null/undefined cases\n if (a == null || b == null) return false;\n\n // Handle different types\n if (typeof a !== typeof b) return false;\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((item, index) => isEqual(item, b[index]));\n }\n\n // Handle objects\n if (typeof a === \"object\" && typeof b === \"object\") {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n return keysA.every((key) => {\n return (\n Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key])\n );\n });\n }\n\n // For primitives that aren't strictly equal\n return false;\n}\n\n/** Selects an active MCP server and exposes its LangChain tools. */\nexport class ServerManager implements IServerManager {\n /** Whether capabilities have been loaded for each configured server. */\n public readonly initializedServers: Record<string, boolean> = {};\n /** Cached LangChain tools, resources, and prompts by server name. */\n public readonly serverTools: Record<string, StructuredToolInterface[]> = {};\n\n /** MCP client that owns server configurations and sessions. */\n public readonly client: MCPClient;\n /** Adapter used to create LangChain tools. */\n public readonly adapter: LangChainAdapter;\n /** Server whose cached tools are currently exposed. */\n public activeServer: string | null = null;\n private overrideManagementTools?: StructuredToolInterface[];\n\n /**\n * @param client - MCP client that owns the managed servers.\n * @param adapter - Adapter used to convert MCP capabilities.\n * @param managementTools - Optional replacement for the built-in server\n * management tools.\n */\n constructor(\n client: MCPClient,\n adapter: LangChainAdapter,\n managementTools?: StructuredToolInterface[]\n ) {\n this.client = client;\n this.adapter = adapter;\n this.overrideManagementTools = managementTools;\n }\n\n /**\n * Replaces the management tools returned by {@link ServerManager.tools}.\n *\n * @param tools - Complete replacement tool list.\n */\n public setManagementTools(tools: StructuredToolInterface[]): void {\n this.overrideManagementTools = tools;\n logger.debug(\n `Overriding default management tools with a new set of ${tools.length} tools.`\n );\n }\n\n /**\n * Writes current connection and tool-cache state at debug level.\n *\n * @param context - Label describing why the state was logged.\n */\n public logState(context: string): void {\n const allServerNames = this.client.getServerNames();\n const activeSessionNames = Object.keys(this.client.getAllActiveSessions());\n\n if (allServerNames.length === 0) {\n logger.debug(\"Server Manager State: No servers configured.\");\n return;\n }\n\n const tableData = allServerNames.map((name) => ({\n \"Server Name\": name,\n Connected: activeSessionNames.includes(name) ? \"✅\" : \"❌\",\n Initialized: this.initializedServers[name] ? \"✅\" : \"❌\",\n \"Tool Count\": this.serverTools[name]?.length ?? 0,\n Active: this.activeServer === name ? \"✅\" : \"❌\",\n }));\n\n logger.debug(`Server Manager State: [${context}]`);\n console.table(tableData);\n }\n\n /** Validates that the client contains at least one server configuration. */\n initialize(): void {\n const serverNames = this.client.getServerNames?.();\n if (serverNames.length === 0) {\n logger.warn(\"No MCP servers defined in client configuration\");\n }\n }\n\n /**\n * Connects configured servers as needed and caches all tools, resources, and\n * prompts.\n */\n async prefetchServerTools(): Promise<void> {\n const servers: string[] = this.client.getServerNames();\n\n for (const serverName of servers) {\n try {\n let session: MCPSession | null = null;\n\n session = this.client.getSession(serverName);\n logger.debug(\n `Using existing session for server '${serverName}' to prefetch tools.`\n );\n\n if (!session) {\n session = await this.client\n .createSession(serverName)\n .catch((createSessionError) => {\n logger.warn(\n `Could not create session for '${serverName}' during prefetch: ${createSessionError}`\n );\n return null;\n });\n logger.debug(\n `Temporarily created session for '${serverName}' to prefetch tools.`\n );\n }\n\n if (session) {\n const connector: BaseConnector = session.connector;\n let tools: StructuredToolInterface[] = [];\n let resources: StructuredToolInterface[] = [];\n let prompts: StructuredToolInterface[] = [];\n\n try {\n tools = await this.adapter.createToolsFromConnectors([connector]);\n resources = await this.adapter.createResourcesFromConnectors([\n connector,\n ]);\n prompts = await this.adapter.createPromptsFromConnectors([\n connector,\n ]);\n } catch (toolFetchError) {\n logger.error(\n `Failed to create tools/resources/prompts from connector for server '${serverName}': ${toolFetchError}`\n );\n continue;\n }\n\n const allItems = [...tools, ...resources, ...prompts];\n const cachedTools = this.serverTools[serverName];\n const toolsChanged = !cachedTools || !isEqual(cachedTools, allItems);\n\n if (toolsChanged) {\n this.serverTools[serverName] = allItems;\n this.initializedServers[serverName] = true;\n logger.debug(\n `Prefetched ${allItems.length} items for server '${serverName}': ` +\n `${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts.`\n );\n } else {\n logger.debug(\n `Tools for server '${serverName}' unchanged, using cached version.`\n );\n }\n }\n } catch (outerError) {\n logger.error(\n `Error prefetching tools for server '${serverName}': ${outerError}`\n );\n }\n }\n }\n\n /**\n * @returns Management tools plus cached tools from the active server, if any.\n */\n get tools(): StructuredToolInterface[] {\n if (logger.level === \"debug\") {\n this.logState(\"Providing tools to agent\");\n }\n\n const managementTools = this.overrideManagementTools ?? [\n new AddMCPServerFromConfigTool(this),\n new ListMCPServersTool(this),\n new ConnectMCPServerTool(this),\n new AcquireActiveMCPServerTool(this),\n new ReleaseMCPServerConnectionTool(this),\n ];\n\n if (this.activeServer && this.serverTools[this.activeServer]) {\n const activeTools = this.serverTools[this.activeServer];\n logger.debug(\n `Adding ${activeTools.length} tools from active server '${this.activeServer}'`\n );\n return [...managementTools, ...activeTools];\n }\n\n return managementTools;\n }\n}\n","import type { IServerManager } from \"../types.js\";\nimport { z } from \"zod\";\nimport { MCPServerTool } from \"./base.js\";\n\nconst PresentActiveServerSchema = z.object({});\n\n/** Reports the MCP server whose tools are currently active. */\nexport class AcquireActiveMCPServerTool extends MCPServerTool<\n typeof PresentActiveServerSchema\n> {\n /** Tool name exposed to the model. */\n override name = \"get_active_mcp_server\";\n /** Tool description exposed to the model. */\n override description =\n \"Get the currently active MCP (Model Context Protocol) server\";\n /** Empty input schema. */\n override schema = PresentActiveServerSchema;\n\n constructor(manager: IServerManager) {\n super(manager);\n }\n\n /** @returns A message identifying the active server, or stating there is none. */\n async _call(): Promise<string> {\n if (!this.manager.activeServer) {\n return `No MCP server is currently active. Use connect_to_mcp_server to connect to a server.`;\n }\n\n return `Currently active MCP server: ${this.manager.activeServer}`;\n }\n}\n","import type { CallbackManagerForToolRun } from \"@langchain/core/callbacks/manager\";\nimport type { ToolRunnableConfig, ToolSchemaBase } from \"@langchain/core/tools\";\nimport type { JSONSchema } from \"@langchain/core/utils/json_schema\";\nimport type z from \"zod\";\nimport type { IServerManager } from \"../types.js\";\nimport { StructuredTool } from \"@langchain/core/tools\";\n\ntype ToolOutputT = any;\nexport type SchemaOutputT<T extends ToolSchemaBase> = T extends z.ZodSchema\n ? z.output<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\nexport class MCPServerTool<\n SchemaT extends ToolSchemaBase,\n> extends StructuredTool<SchemaT, SchemaOutputT<SchemaT>> {\n /** Default tool name. Subclasses replace this value. */\n override name: string = \"mcp_server_tool\";\n /** Default tool description. Subclasses replace this value. */\n override description: string = \"Base tool for MCP server operations.\";\n /** Input schema supplied by the concrete management tool. */\n override schema!: SchemaT;\n\n private readonly _manager: IServerManager;\n\n /**\n * @param manager - Server manager operated by this tool.\n */\n constructor(manager: IServerManager) {\n super();\n this._manager = manager;\n }\n\n protected async _call(\n _arg: SchemaOutputT<SchemaT>,\n _runManager?: CallbackManagerForToolRun,\n _parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n throw new Error(\"Method not implemented.\");\n }\n\n /** @returns The server manager operated by this tool. */\n get manager(): IServerManager {\n return this._manager;\n }\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { IServerManager } from \"../types.js\";\nimport { StructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\n\n/** Adds, connects, and activates an MCP server from model-supplied config. */\nexport class AddMCPServerFromConfigTool extends StructuredTool {\n /** Tool name exposed to the model. */\n name = \"add_mcp_server_from_config\";\n /** Tool description exposed to the model. */\n description =\n \"Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.\";\n\n /** Input schema for the server name and transport configuration. */\n schema = z.object({\n /** Name used to register the server with the MCP client. */\n serverName: z.string().describe(\"The name for the new MCP server.\"),\n /** MCP transport configuration without a top-level `mcpServers` key. */\n serverConfig: z\n .any()\n .describe(\n 'The configuration object for the server. This should not include the top-level \"mcpServers\" key.'\n ),\n });\n\n private manager: IServerManager;\n\n /**\n * @param manager - Server manager that receives the new server.\n */\n constructor(manager: IServerManager) {\n super();\n this.manager = manager;\n }\n\n /**\n * Adds the server, opens a session, and makes the server active.\n *\n * @returns A success message with loaded tool names, or an error message.\n */\n protected async _call({\n serverName,\n serverConfig,\n }: z.infer<typeof this.schema>): Promise<string> {\n try {\n this.manager.client.addServer(serverName, serverConfig);\n let result = `Server '${serverName}' added to the client.`;\n logger.debug(\n `Connecting to new server '${serverName}' and discovering tools.`\n );\n const session = await this.manager.client.createSession(serverName);\n const connector = session.connector;\n const tools: StructuredToolInterface[] =\n await this.manager.adapter.createToolsFromConnectors([connector]);\n\n this.manager.serverTools[serverName] = tools;\n this.manager.initializedServers[serverName] = true;\n this.manager.activeServer = serverName; // Set as active server\n\n const numTools = tools.length;\n result += ` Session created and connected. '${serverName}' is now the active server with ${numTools} tools available.`;\n result += `\\n\\n${tools.map((t) => t.name).join(\"\\n\")}`;\n logger.debug(result);\n return result;\n } catch (e: any) {\n logger.error(\n `Failed to add or connect to server '${serverName}': ${e.message}`\n );\n return `Failed to add or connect to server '${serverName}': ${e.message}`;\n }\n }\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { BaseConnector } from \"@mcp-use/client\";\nimport type { IServerManager } from \"../types.js\";\nimport type { SchemaOutputT } from \"./base.js\";\nimport { z } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\nimport { MCPServerTool } from \"./base.js\";\n\nconst ConnectMCPServerSchema = z.object({\n /** Name of a configured MCP server. */\n serverName: z.string().describe(\"The name of the MCP server.\"),\n});\n\n/** Activates a configured MCP server and exposes its capabilities. */\nexport class ConnectMCPServerTool extends MCPServerTool<\n typeof ConnectMCPServerSchema\n> {\n /** Tool name exposed to the model. */\n override name = \"connect_to_mcp_server\";\n /** Tool description exposed to the model. */\n override description =\n \"Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.\";\n /** Input schema containing the server name. */\n override schema = ConnectMCPServerSchema;\n\n constructor(manager: IServerManager) {\n super(manager);\n }\n\n /**\n * Activates a configured server and loads its capabilities if needed.\n *\n * @returns A human-readable success or error message.\n */\n async _call({ serverName }: SchemaOutputT<typeof ConnectMCPServerSchema>) {\n const serverNames = this.manager.client.getServerNames();\n\n if (!serverNames.includes(serverName)) {\n const available =\n serverNames.length > 0 ? serverNames.join(\", \") : \"none\";\n return `Server '${serverName}' not found. Available servers: ${available}`;\n }\n\n if (this.manager.activeServer === serverName) {\n return `Already connected to MCP server '${serverName}'`;\n }\n\n try {\n let session = this.manager.client.getSession(serverName);\n logger.debug(`Using existing session for server '${serverName}'`);\n if (!session) {\n logger.debug(`Creating new session for server '${serverName}'`);\n session = await this.manager.client.createSession(serverName);\n }\n this.manager.activeServer = serverName;\n if (!this.manager.serverTools[serverName]) {\n const connector: BaseConnector = session.connector;\n const tools: StructuredToolInterface[] =\n await this.manager.adapter.createToolsFromConnectors([connector]);\n const resources: StructuredToolInterface[] =\n await this.manager.adapter.createResourcesFromConnectors([connector]);\n const prompts: StructuredToolInterface[] =\n await this.manager.adapter.createPromptsFromConnectors([connector]);\n const allItems = [...tools, ...resources, ...prompts];\n this.manager.serverTools[serverName] = allItems;\n this.manager.initializedServers[serverName] = true;\n logger.debug(\n `Loaded ${allItems.length} items for server '${serverName}': ` +\n `${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`\n );\n }\n const serverTools: StructuredToolInterface[] =\n this.manager.serverTools[serverName] || [];\n const numTools: number = serverTools.length;\n return `Connected to MCP server '${serverName}'. ${numTools} tools, resources, and prompts are now available.`;\n } catch (error) {\n logger.error(\n `Error connecting to server '${serverName}': ${String(error)}`\n );\n return `Failed to connect to server '${serverName}': ${String(error)}`;\n }\n }\n}\n","import type { IServerManager } from \"../types.js\";\nimport { z } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\nimport { MCPServerTool } from \"./base.js\";\n\nconst EnumerateServersSchema = z.object({});\n\n/** Lists configured MCP servers and their cached capability counts. */\nexport class ListMCPServersTool extends MCPServerTool<\n typeof EnumerateServersSchema\n> {\n /** Tool name exposed to the model. */\n override name = \"list_mcp_servers\";\n /** Tool description exposed to the model. */\n override description = `Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.`;\n /** Empty input schema. */\n override schema = EnumerateServersSchema;\n\n constructor(manager: IServerManager) {\n super(manager);\n }\n\n /** @returns A formatted list of configured servers and capability counts. */\n async _call(): Promise<string> {\n const serverNames = this.manager.client.getServerNames();\n if (serverNames.length === 0) {\n return `No MCP servers are currently defined.`;\n }\n\n const outputLines: string[] = [\"Available MCP servers:\"];\n\n for (const serverName of serverNames) {\n const isActiveServer = serverName === this.manager.activeServer;\n const activeFlag = isActiveServer ? \" (ACTIVE)\" : \"\";\n outputLines.push(`- ${serverName}${activeFlag}`);\n\n try {\n const serverTools = this.manager.serverTools?.[serverName] ?? [];\n const numberOfTools = Array.isArray(serverTools)\n ? serverTools.length\n : 0;\n outputLines.push(`${numberOfTools} tools available for this server\\n`);\n } catch (error) {\n logger.error(\n `Unexpected error listing tools for server '${serverName}': ${String(error)}`\n );\n }\n }\n return outputLines.join(\"\\n\");\n }\n}\n","import type { IServerManager } from \"../types.js\";\nimport { z } from \"zod\";\nimport { MCPServerTool } from \"./base.js\";\n\nconst ReleaseConnectionSchema = z.object({});\n\n/** Deactivates the current MCP server without closing its client session. */\nexport class ReleaseMCPServerConnectionTool extends MCPServerTool<\n typeof ReleaseConnectionSchema\n> {\n /** Tool name exposed to the model. */\n override name = \"disconnect_from_mcp_server\";\n /** Tool description exposed to the model. */\n override description =\n \"Disconnect from the currently active MCP (Model Context Protocol) server\";\n /** Empty input schema. */\n override schema = ReleaseConnectionSchema;\n\n constructor(manager: IServerManager) {\n super(manager);\n }\n\n /** @returns A message identifying the deactivated server, or stating there is none. */\n async _call(): Promise<string> {\n if (!this.manager.activeServer) {\n return `No MCP server is currently active, so there's nothing to disconnect from.`;\n }\n const serverName = this.manager.activeServer;\n this.manager.activeServer = null;\n return `Successfully disconnected from MCP server '${serverName}'.`;\n }\n}\n","/**\n * Observability module for MCP-use.\n *\n * This module provides centralized observability management for LangChain agents,\n * supporting multiple platforms like Langfuse and Laminar.\n */\n\n// Import observability providers - order matters for initialization\nimport \"./langfuse.js\";\n\n// Export the manager and its utilities\nexport {\n type ObservabilityConfig,\n ObservabilityManager,\n type ObservabilityStatus,\n} from \"./manager.js\";\n","/**\n * Observability callbacks manager for MCP-use.\n *\n * This module provides a centralized manager for handling observability callbacks\n * from various platforms (Langfuse, Laminar, etc.) in a clean and extensible way.\n */\n\nimport type { BaseCallbackHandler } from \"@langchain/core/callbacks/base\";\nimport { logger } from \"@mcp-use/client\";\n\n/** Configures callbacks and trace metadata for an agent. */\nexport interface ObservabilityConfig {\n /** Custom callbacks to use instead of defaults */\n customCallbacks?: BaseCallbackHandler[];\n /** Whether to enable verbose logging */\n verbose?: boolean;\n /** Whether to enable observability (defaults to true) */\n observe?: boolean;\n /** Agent ID for tagging traces */\n agentId?: string;\n /** Metadata to add to traces */\n metadata?: Record<string, any>;\n /** Function to get current metadata from agent */\n metadataProvider?: () => Record<string, any>;\n /** Function to get current tags from agent */\n tagsProvider?: () => string[];\n}\n\n/** Snapshot returned by {@link ObservabilityManager.getStatus}. */\nexport interface ObservabilityStatus {\n /** Whether observability is enabled and has at least one callback. */\n enabled: boolean;\n /** Number of active callbacks. */\n callbackCount: number;\n /** Human-readable callback handler names. */\n handlerNames: string[];\n /** Current trace metadata. */\n metadata: Record<string, any>;\n /** Current trace tags. */\n tags: string[];\n}\n\n/** Discovers, configures, and shuts down LangChain observability callbacks. */\nexport class ObservabilityManager {\n private customCallbacks?: BaseCallbackHandler[];\n private availableHandlers: BaseCallbackHandler[] = [];\n private handlerNames: string[] = [];\n private initialized = false;\n private verbose: boolean;\n private observe: boolean;\n private agentId?: string;\n private metadata?: Record<string, any>;\n private metadataProvider?: () => Record<string, any>;\n private tagsProvider?: () => string[];\n\n /**\n * @param config - Callback selection and trace metadata settings.\n */\n constructor(config: ObservabilityConfig = {}) {\n this.customCallbacks = config.customCallbacks;\n this.verbose = config.verbose ?? false;\n this.observe = config.observe ?? true;\n this.agentId = config.agentId;\n this.metadata = config.metadata;\n this.metadataProvider = config.metadataProvider;\n this.tagsProvider = config.tagsProvider;\n }\n\n /**\n * Collect all available observability handlers from configured platforms.\n */\n private async collectAvailableHandlers(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n // Import handlers lazily to avoid circular imports\n try {\n const { langfuseHandler, langfuseInitPromise } =\n await import(\"./langfuse.js\");\n\n // If we have an agent ID, metadata, or providers, we need to reinitialize Langfuse\n if (\n this.agentId ||\n this.metadata ||\n this.metadataProvider ||\n this.tagsProvider\n ) {\n // Import the initialization function directly\n const { initializeLangfuse } = await import(\"./langfuse.js\");\n await initializeLangfuse(\n this.agentId,\n this.metadata,\n this.metadataProvider,\n this.tagsProvider\n );\n logger.debug(\n `ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`\n );\n } else {\n // Wait for existing initialization to complete\n const initPromise = langfuseInitPromise();\n if (initPromise) {\n await initPromise;\n }\n }\n\n const handler = langfuseHandler();\n if (handler) {\n this.availableHandlers.push(handler);\n this.handlerNames.push(\"Langfuse\");\n logger.debug(\"ObservabilityManager: Langfuse handler available\");\n }\n } catch {\n logger.debug(\"ObservabilityManager: Langfuse module not available\");\n }\n\n // Future: Add more platforms here...\n\n this.initialized = true;\n }\n\n /**\n * Get the list of callbacks to use.\n * @returns List of callbacks - either custom callbacks if provided, or all available observability handlers.\n */\n async getCallbacks(): Promise<BaseCallbackHandler[]> {\n // If observability is disabled, return empty array\n if (!this.observe) {\n logger.debug(\n \"ObservabilityManager: Observability disabled via observe=false\"\n );\n return [];\n }\n\n // If custom callbacks were provided, use those\n if (this.customCallbacks) {\n logger.debug(\n `ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`\n );\n return this.customCallbacks;\n }\n\n // Otherwise, collect and return all available handlers\n await this.collectAvailableHandlers();\n\n if (this.availableHandlers.length > 0) {\n logger.debug(\n `ObservabilityManager: Using ${this.availableHandlers.length} handlers`\n );\n } else {\n logger.debug(\"ObservabilityManager: No callbacks configured\");\n }\n\n return this.availableHandlers;\n }\n\n /**\n * Get the names of available handlers.\n * @returns List of handler names (e.g., [\"Langfuse\", \"Laminar\"])\n */\n async getHandlerNames(): Promise<string[]> {\n // If observability is disabled, return empty array\n if (!this.observe) {\n return [];\n }\n\n if (this.customCallbacks) {\n // For custom callbacks, try to get their class names\n return this.customCallbacks.map((cb) => cb.constructor.name);\n }\n\n await this.collectAvailableHandlers();\n return this.handlerNames;\n }\n\n /**\n * Check if any callbacks are available.\n * @returns True if callbacks are available, False otherwise.\n */\n async hasCallbacks(): Promise<boolean> {\n // If observability is disabled, no callbacks are available\n if (!this.observe) {\n return false;\n }\n\n const callbacks = await this.getCallbacks();\n return callbacks.length > 0;\n }\n\n /**\n * Get the current observability status including metadata and tags.\n * @returns Object containing enabled status, callback count, handler names, metadata, and tags.\n */\n async getStatus(): Promise<ObservabilityStatus> {\n const callbacks = await this.getCallbacks();\n const handlerNames = await this.getHandlerNames();\n\n // Get current metadata from provider if available\n const currentMetadata = this.metadataProvider\n ? this.metadataProvider()\n : this.metadata || {};\n\n // Get current tags from provider if available\n const currentTags = this.tagsProvider ? this.tagsProvider() : [];\n\n return {\n enabled: this.observe && callbacks.length > 0,\n callbackCount: callbacks.length,\n handlerNames,\n metadata: currentMetadata,\n tags: currentTags,\n };\n }\n\n /**\n * Add a callback to the custom callbacks list.\n * @param callback - The callback to add.\n */\n addCallback(callback: BaseCallbackHandler): void {\n if (!this.customCallbacks) {\n this.customCallbacks = [];\n }\n this.customCallbacks.push(callback);\n logger.debug(\n `ObservabilityManager: Added custom callback: ${callback.constructor.name}`\n );\n }\n\n /**\n * Clear all custom callbacks.\n */\n clearCallbacks(): void {\n this.customCallbacks = [];\n logger.debug(\"ObservabilityManager: Cleared all custom callbacks\");\n }\n\n /**\n * Flush all pending traces to observability platforms.\n * Important for serverless environments and short-lived processes.\n */\n async flush(): Promise<void> {\n // Flush Langfuse traces\n const callbacks = await this.getCallbacks();\n for (const callback of callbacks) {\n if (\n \"flushAsync\" in callback &&\n typeof callback.flushAsync === \"function\"\n ) {\n await callback.flushAsync();\n }\n }\n logger.debug(\"ObservabilityManager: All traces flushed\");\n }\n\n /**\n * Shutdown all handlers gracefully (for serverless environments).\n */\n async shutdown(): Promise<void> {\n // Flush before shutdown\n await this.flush();\n\n // Shutdown other callbacks\n const callbacks = await this.getCallbacks();\n for (const callback of callbacks) {\n // Check if the callback has a shutdown method (like Langfuse)\n if (\n \"shutdownAsync\" in callback &&\n typeof callback.shutdownAsync === \"function\"\n ) {\n await callback.shutdownAsync();\n } else if (\n \"shutdown\" in callback &&\n typeof callback.shutdown === \"function\"\n ) {\n await (callback as any).shutdown();\n }\n }\n logger.debug(\"ObservabilityManager: All handlers shutdown\");\n }\n\n /**\n * String representation of the ObservabilityManager.\n */\n toString(): string {\n const names = this.handlerNames;\n if (names.length > 0) {\n return `ObservabilityManager(handlers=${names.join(\", \")})`;\n }\n return \"ObservabilityManager(no handlers)\";\n }\n}\n","declare const __MCP_USE_PACKAGE_VERSION__: string;\n\nexport const VERSION = __MCP_USE_PACKAGE_VERSION__;\n\nexport function getPackageVersion(): string {\n return VERSION;\n}\n","import type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nexport { getPackageVersion } from \"../version.js\";\n\nfunction getModelProvider(llm: BaseLanguageModel): string {\n // Use LangChain's standard _llm_type property for identification\n return (llm as any)._llm_type || llm.constructor.name.toLowerCase();\n}\n\nfunction getModelName(llm: BaseLanguageModel): string {\n // First try _identifying_params which may contain model info\n if (\"_identifyingParams\" in llm) {\n const identifyingParams = (llm as any)._identifyingParams;\n if (typeof identifyingParams === \"object\" && identifyingParams !== null) {\n // Common keys that contain model names\n for (const key of [\n \"model\",\n \"modelName\",\n \"model_name\",\n \"modelId\",\n \"model_id\",\n \"deploymentName\",\n \"deployment_name\",\n ]) {\n if (key in identifyingParams) {\n return String(identifyingParams[key]);\n }\n }\n }\n }\n\n // Fallback to direct model attributes\n return (llm as any).model || (llm as any).modelName || llm.constructor.name;\n}\n\nexport function extractModelInfo(llm: BaseLanguageModel): [string, string] {\n return [getModelProvider(llm), getModelName(llm)];\n}\n","import type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { SystemMessage } from \"langchain\";\n\nfunction generateToolDescriptions(\n tools: StructuredToolInterface[],\n disallowedTools?: string[]\n): string[] {\n const disallowedSet = new Set(disallowedTools ?? []);\n const descriptions: string[] = [];\n\n for (const tool of tools) {\n if (disallowedSet.has(tool.name)) continue;\n const escaped = tool.description.replace(/\\{/g, \"{{\").replace(/\\}/g, \"}}\");\n descriptions.push(`- ${tool.name}: ${escaped}`);\n }\n\n return descriptions;\n}\n\nfunction buildSystemPromptContent(\n template: string,\n toolDescriptionLines: string[],\n additionalInstructions?: string\n): string {\n const block = toolDescriptionLines.join(\"\\n\");\n\n let content: string;\n if (template.includes(\"{tool_descriptions}\")) {\n content = template.replace(\"{tool_descriptions}\", block);\n } else {\n console.warn(\n \"`{tool_descriptions}` placeholder not found; appending at end.\"\n );\n content = `${template}\\n\\nAvailable tools:\\n${block}`;\n }\n\n if (additionalInstructions) {\n content += `\\n\\n${additionalInstructions}`;\n }\n\n return content;\n}\n\nexport function createSystemMessage(\n tools: StructuredToolInterface[],\n systemPromptTemplate: string,\n serverManagerTemplate: string,\n useServerManager: boolean,\n disallowedTools?: string[],\n userProvidedPrompt?: string,\n additionalInstructions?: string\n): SystemMessage {\n if (userProvidedPrompt) {\n return new SystemMessage({ content: userProvidedPrompt });\n }\n\n const template = useServerManager\n ? serverManagerTemplate\n : systemPromptTemplate;\n\n const toolLines = generateToolDescriptions(tools, disallowedTools);\n const finalContent = buildSystemPromptContent(\n template,\n toolLines,\n additionalInstructions\n );\n\n return new SystemMessage({ content: finalContent });\n}\n","export const DEFAULT_SYSTEM_PROMPT_TEMPLATE = `You are a helpful AI assistant.\nYou have access to the following tools:\n\n{tool_descriptions}\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of the available tools\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question`;\n\nexport const SERVER_MANAGER_SYSTEM_PROMPT_TEMPLATE = `You are a helpful assistant designed to interact with MCP\n (Model Context Protocol) servers. You can manage connections to different servers and use the tools\n provided by the currently active server.\n\nImportant: The available tools change depending on which server is active.\nIf a request requires tools not listed below (e.g., file operations, web browsing,\n image manipulation), you MUST first connect to the appropriate server using\n 'connect_to_mcp_server'.\nUse 'list_mcp_servers' to find the relevant server if you are unsure.\nOnly after successfully connecting and seeing the new tools listed in\nthe response should you attempt to use those server-specific tools.\nBefore attempting a task that requires specific tools, you should\nensure you are connected to the correct server and aware of its\navailable tools. If unsure, use 'list_mcp_servers' to see options\nor 'get_active_mcp_server' to check the current connection.\n\nWhen you connect to a server using 'connect_to_mcp_server',\n you will be informed about the new tools that become available.\nYou can then use these server-specific tools in subsequent steps.\n\nHere are the tools *currently* available to you (this list includes server management tools and will\n change when you connect to a server):\n{tool_descriptions}\n`;\n","/** Remote execution support for hosted MCP agents. */\n\nimport type { ZodSchema } from \"zod\";\nimport { toJSONSchema } from \"zod\";\nimport { logger } from \"@mcp-use/client\";\nimport type { RunOptions } from \"./run_options.js\";\nimport type { BaseMessage } from \"./types.js\";\n\n// API endpoint constants\nconst API_CHATS_ENDPOINT = \"/api/v1/chats\";\nconst API_CHAT_EXECUTE_ENDPOINT = \"/api/v1/chats/{chat_id}/execute\";\n\n/**\n * Helper function to normalize run options for remote agent\n */\nfunction normalizeRemoteRunOptions<T>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n): {\n query: string;\n maxSteps?: number;\n manageConnector?: boolean;\n externalHistory?: BaseMessage[];\n outputSchema?: ZodSchema<T>;\n} {\n // Check if first argument is an options object\n if (typeof queryOrOptions === \"object\" && queryOrOptions !== null) {\n const options = queryOrOptions as RunOptions<T>;\n return {\n query: options.prompt ?? \"\",\n maxSteps: options.maxSteps,\n manageConnector: options.manageConnector,\n externalHistory: options.externalHistory,\n outputSchema: options.schema,\n };\n }\n\n // Old-style positional arguments\n return {\n query: queryOrOptions as string,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema,\n };\n}\n\n/** Configures a {@link RemoteAgent}. */\nexport interface RemoteAgentOptions {\n /** Hosted agent identifier. */\n agentId: string;\n /** API key. Defaults to `MCP_USE_API_KEY`. */\n apiKey?: string;\n /** API origin. Defaults to `https://cloud.manufact.com`. */\n baseUrl?: string;\n}\n\n/** Executes a hosted MCP agent through the mcp-use remote API. */\nexport class RemoteAgent {\n private agentId: string;\n private apiKey: string;\n private baseUrl: string;\n private chatId: string | null = null;\n\n /**\n * @param options - Hosted agent identifier and API connection settings.\n * @throws Error if no API key is supplied or available from\n * `MCP_USE_API_KEY`.\n */\n constructor(options: RemoteAgentOptions) {\n this.agentId = options.agentId;\n this.baseUrl = options.baseUrl ?? \"https://cloud.manufact.com\";\n\n // Handle API key validation\n const apiKey =\n options.apiKey ??\n (typeof process !== \"undefined\" && process.env?.MCP_USE_API_KEY);\n if (!apiKey) {\n throw new Error(\n \"API key is required for remote execution. \" +\n \"Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. \" +\n \"You can get an API key from https://cloud.manufact.com\"\n );\n }\n this.apiKey = apiKey;\n }\n\n private pydanticToJsonSchema<T>(schema: ZodSchema<T>): any {\n /**\n * Convert a Zod schema to JSON schema for API transmission.\n */\n return toJSONSchema(schema);\n }\n\n private parseStructuredResponse<T>(\n responseData: any,\n outputSchema: ZodSchema<T>\n ): T {\n /**\n * Parse the API response into the structured output format.\n */\n let resultData: any;\n\n // Handle different response formats\n if (typeof responseData === \"object\" && responseData !== null) {\n if (\"result\" in responseData) {\n const outerResult = responseData.result;\n // Check if this is a nested result structure (agent execution response)\n if (\n typeof outerResult === \"object\" &&\n outerResult !== null &&\n \"result\" in outerResult\n ) {\n // Extract the actual structured output from the nested result\n resultData = outerResult.result;\n } else {\n // Use the outer result directly\n resultData = outerResult;\n }\n } else {\n resultData = responseData;\n }\n } else if (typeof responseData === \"string\") {\n try {\n resultData = JSON.parse(responseData);\n } catch {\n // If it's not valid JSON, try to create the model from the string content\n resultData = { content: responseData };\n }\n } else {\n resultData = responseData;\n }\n\n // Parse into the Zod schema\n try {\n return outputSchema.parse(resultData);\n } catch (e) {\n logger.warn(`Failed to parse structured output: ${e}`);\n // Fallback: try to parse it as raw content if the schema has a content field\n const schemaShape = (outputSchema as any)._def?.shape();\n if (schemaShape && \"content\" in schemaShape) {\n return outputSchema.parse({ content: String(resultData) });\n }\n throw e;\n }\n }\n\n private async createChatSession(): Promise<string> {\n /**\n * Create a persistent chat session for the agent.\n */\n const chatPayload = {\n title: `Remote Agent Session - ${this.agentId}`,\n agent_id: this.agentId,\n type: \"agent_execution\",\n };\n\n const headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n };\n const chatUrl = `${this.baseUrl}${API_CHATS_ENDPOINT}`;\n\n logger.debug(`📝 Creating chat session for agent ${this.agentId}`);\n\n try {\n const response = await fetch(chatUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify(chatPayload),\n });\n\n if (!response.ok) {\n const responseText = await response.text();\n const statusCode = response.status;\n\n if (statusCode === 404) {\n throw new Error(\n `Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. ` +\n \"Please verify the agent ID and ensure it exists in your account.\"\n );\n }\n throw new Error(\n `Failed to create chat session: ${statusCode} - ${responseText}`\n );\n }\n\n const chatData = await response.json();\n const chatId = chatData.id;\n logger.debug(`✅ Chat session created: ${chatId}`);\n return chatId;\n } catch (e) {\n if (e instanceof Error) {\n throw new TypeError(`Failed to create chat session: ${e.message}`);\n }\n throw new Error(`Failed to create chat session: ${String(e)}`);\n }\n }\n\n /**\n * Runs the remote agent and returns its final text.\n *\n * @param options - Input and per-run execution settings.\n * @returns Final agent text.\n */\n public async run(options: RunOptions): Promise<string>;\n\n /**\n * Runs the remote agent and parses its result with `options.schema`.\n *\n * @param options - Input, schema, and per-run execution settings.\n * @returns The schema-validated result.\n */\n public async run<T>(options: RunOptions<T>): Promise<T>;\n\n /**\n * Runs the remote agent and returns a promise for the final result.\n * @deprecated Use the options object instead: `run({ prompt, maxSteps, ... })`.\n */\n public async run<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): Promise<T>;\n\n public async run<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): Promise<T> {\n /**\n * Run a query on the remote agent.\n */\n // Normalize input to internal parameters\n const {\n query,\n maxSteps: steps,\n externalHistory: history,\n outputSchema: schema,\n } = normalizeRemoteRunOptions(\n queryOrOptions,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema\n );\n\n if (history !== undefined) {\n logger.warn(\"External history is not yet supported for remote execution\");\n }\n\n try {\n logger.debug(`🌐 Executing query on remote agent ${this.agentId}`);\n\n // Step 1: Create a chat session for this agent (only if we don't have one)\n if (this.chatId === null) {\n this.chatId = await this.createChatSession();\n }\n\n const chatId = this.chatId;\n\n // Step 2: Execute the agent within the chat context\n const executionPayload: any = {\n query,\n max_steps: steps ?? 10,\n };\n\n // Add structured output schema if provided\n if (schema) {\n executionPayload.output_schema = this.pydanticToJsonSchema(schema);\n logger.debug(`🔧 Using structured output with schema`);\n }\n\n const headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n };\n const executionUrl = `${this.baseUrl}${API_CHAT_EXECUTE_ENDPOINT.replace(\"{chat_id}\", chatId)}`;\n logger.debug(`🚀 Executing agent in chat ${chatId}`);\n\n const response = await fetch(executionUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify(executionPayload),\n signal: AbortSignal.timeout(300000), // 5 minute timeout\n });\n\n if (!response.ok) {\n const responseText = await response.text();\n const statusCode = response.status;\n\n // Provide specific error messages based on status code\n if (statusCode === 401) {\n logger.error(`❌ Authentication failed: ${responseText}`);\n throw new Error(\n \"Authentication failed: Invalid or missing API key. \" +\n \"Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.\"\n );\n } else if (statusCode === 403) {\n logger.error(`❌ Access forbidden: ${responseText}`);\n throw new Error(\n `Access denied: You don't have permission to execute agent '${this.agentId}'. ` +\n \"Check if the agent exists and you have the necessary permissions.\"\n );\n } else if (statusCode === 404) {\n logger.error(`❌ Agent not found: ${responseText}`);\n throw new Error(\n `Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. ` +\n \"Please verify the agent ID and ensure it exists in your account.\"\n );\n } else if (statusCode === 422) {\n logger.error(`❌ Validation error: ${responseText}`);\n throw new Error(\n `Request validation failed: ${responseText}. ` +\n \"Please check your query parameters and output schema format.\"\n );\n } else if (statusCode === 500) {\n logger.error(`❌ Server error: ${responseText}`);\n throw new Error(\n \"Internal server error occurred during agent execution. \" +\n \"Please try again later or contact support if the issue persists.\"\n );\n } else {\n logger.error(\n `❌ Remote execution failed with status ${statusCode}: ${responseText}`\n );\n throw new Error(\n `Remote agent execution failed: ${statusCode} - ${responseText}`\n );\n }\n }\n\n const result = await response.json();\n logger.debug(`🔧 Response: ${JSON.stringify(result)}`);\n logger.debug(\"✅ Remote execution completed successfully\");\n\n // Check for error responses (even with 200 status)\n if (typeof result === \"object\" && result !== null) {\n // Check for actual error conditions (not just presence of error field)\n if (result.status === \"error\" || result.error !== null) {\n const errorMsg = result.error ?? String(result);\n logger.error(`❌ Remote agent execution failed: ${errorMsg}`);\n throw new Error(`Remote agent execution failed: ${errorMsg}`);\n }\n\n // Check if the response indicates agent initialization failure\n if (String(result).includes(\"failed to initialize\")) {\n logger.error(`❌ Agent initialization failed: ${result}`);\n throw new Error(\n \"Agent initialization failed on remote server. \" +\n \"This usually indicates:\\n\" +\n \"• Invalid agent configuration (LLM model, system prompt)\\n\" +\n \"• Missing or invalid MCP server configurations\\n\" +\n \"• Network connectivity issues with MCP servers\\n\" +\n \"• Missing environment variables or credentials\\n\" +\n `Raw error: ${result}`\n );\n }\n }\n\n // Handle structured output\n if (schema) {\n return this.parseStructuredResponse(result, schema);\n }\n\n // Regular string output\n if (typeof result === \"object\" && result !== null && \"result\" in result) {\n return result.result as T;\n } else if (typeof result === \"string\") {\n return result as T;\n } else {\n return String(result) as T;\n }\n } catch (e) {\n if (e instanceof Error) {\n // Check for specific error types\n if (e.name === \"AbortError\") {\n logger.error(`❌ Remote execution timed out: ${e}`);\n throw new Error(\n \"Remote agent execution timed out. The server may be overloaded or the query is taking too long to \" +\n \"process. Try again or use a simpler query.\"\n );\n }\n logger.error(`❌ Remote execution error: ${e}`);\n throw new Error(`Remote agent execution failed: ${e.message}`);\n }\n logger.error(`❌ Remote execution error: ${e}`);\n throw new Error(`Remote agent execution failed: ${String(e)}`);\n }\n }\n\n /**\n * Runs the remote agent through an async-generator interface.\n *\n * The current remote API does not emit intermediate values. Read the\n * generator's return value for the final result.\n *\n * @param options - Input and per-run execution settings.\n * @returns An async generator whose return value is the final text.\n */\n public stream(options: RunOptions): AsyncGenerator<any, string, void>;\n\n /**\n * Runs structured remote execution through an async-generator interface.\n *\n * @param options - Input, schema, and per-run execution settings.\n * @returns An async generator whose return value is schema validated.\n */\n public stream<T>(options: RunOptions<T>): AsyncGenerator<any, T, void>;\n\n /**\n * Streams the remote agent execution.\n * @deprecated Use the options object instead: `stream({ prompt, maxSteps, ... })`.\n */\n public stream<T = string>(\n query: string,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): AsyncGenerator<any, T, void>;\n\n // eslint-disable-next-line require-yield\n public async *stream<T = string>(\n queryOrOptions: string | RunOptions<T>,\n maxSteps?: number,\n manageConnector?: boolean,\n externalHistory?: BaseMessage[],\n outputSchema?: ZodSchema<T>\n ): AsyncGenerator<any, T, void> {\n /**\n * Stream implementation for remote agent - currently just wraps run.\n * In the future, this could be enhanced to support actual streaming from the API.\n */\n const result = await this.run(\n queryOrOptions as any,\n maxSteps,\n manageConnector,\n externalHistory,\n outputSchema\n );\n return result;\n }\n\n /** Releases local remote-agent state. */\n public async close(): Promise<void> {\n /**\n * Close the remote agent connection.\n */\n logger.debug(\"🔌 Remote agent client closed\");\n // In the future, we might want to delete the chat session here\n // if (this.chatId) {\n // await this.deleteChatSession(this.chatId)\n // }\n }\n}\n","import type { LanguageModel } from \"../types.js\";\nimport { logger } from \"@mcp-use/client\";\n\n/** Constructor settings forwarded to a dynamically loaded LangChain model. */\nexport interface LLMConfig {\n /** Provider API key. When omitted, the provider environment variable is used. */\n apiKey?: string;\n /** Sampling temperature. */\n temperature?: number;\n /** Maximum number of output tokens. */\n maxTokens?: number;\n /** Nucleus sampling probability. */\n topP?: number;\n /** Additional provider-specific constructor settings. */\n [key: string]: any; // Allow additional provider-specific config\n}\n\n/** LangChain providers supported by {@link createLLMFromString}. */\nexport type LLMProvider = \"openai\" | \"anthropic\" | \"google\" | \"groq\";\n\n/** Parsed components of a LangChain model identifier. */\nexport interface ParsedLLMString {\n /** Normalized provider name. */\n provider: LLMProvider;\n /** Provider-specific model name. */\n model: string;\n}\n\n/**\n * Provider configuration mapping\n */\nconst PROVIDER_CONFIG = {\n openai: {\n package: \"@langchain/openai\",\n className: \"ChatOpenAI\",\n envVars: [\"OPENAI_API_KEY\"],\n defaultModel: \"gpt-4o\",\n },\n anthropic: {\n package: \"@langchain/anthropic\",\n className: \"ChatAnthropic\",\n envVars: [\"ANTHROPIC_API_KEY\"],\n defaultModel: \"claude-sonnet-4-6\",\n },\n google: {\n package: \"@langchain/google-genai\",\n className: \"ChatGoogleGenerativeAI\",\n envVars: [\"GOOGLE_API_KEY\", \"GOOGLE_GENERATIVE_AI_API_KEY\"],\n defaultModel: \"gemini-pro\",\n },\n groq: {\n package: \"@langchain/groq\",\n className: \"ChatGroq\",\n envVars: [\"GROQ_API_KEY\"],\n defaultModel: \"llama-3.1-70b-versatile\",\n },\n} as const;\n\n/**\n * Parses an LLM identifier in `\"provider/model\"` format.\n *\n * @param llmString - Provider and model separated by one slash.\n * @returns The normalized provider and model.\n * @throws Error if the format is invalid or the provider is unsupported.\n */\nexport function parseLLMString(llmString: string): ParsedLLMString {\n const parts = llmString.split(\"/\");\n\n if (parts.length !== 2) {\n throw new Error(\n `Invalid LLM string format. Expected 'provider/model', got '${llmString}'. ` +\n `Examples: 'openai/gpt-4', 'anthropic/claude-sonnet-4-6', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`\n );\n }\n\n const [provider, model] = parts;\n\n if (!provider || !model) {\n throw new Error(\n `Invalid LLM string format. Both provider and model must be non-empty. Got '${llmString}'`\n );\n }\n\n const normalizedProvider = provider.toLowerCase() as LLMProvider;\n\n if (!(normalizedProvider in PROVIDER_CONFIG)) {\n const supportedProviders = Object.keys(PROVIDER_CONFIG).join(\", \");\n throw new Error(\n `Unsupported LLM provider '${provider}'. Supported providers: ${supportedProviders}`\n );\n }\n\n return { provider: normalizedProvider, model };\n}\n\n/**\n * Determine the API key to use for a given provider by checking `llmConfig` then provider-specific environment variables.\n *\n * @param provider - The LLM provider identifier (e.g., \"openai\").\n * @param config - Optional LLM configuration; if `config.apiKey` is present it is returned.\n * @returns The resolved API key string.\n * @throws Error if no API key is found in `config.apiKey` or any of the provider's expected environment variables.\n */\nfunction getAPIKey(provider: LLMProvider, config?: LLMConfig): string {\n // First check if provided in config\n if (config?.apiKey) {\n return config.apiKey;\n }\n\n // Get provider config for error message\n const providerConfig = PROVIDER_CONFIG[provider];\n\n // Check environment variables (only if process.env is available)\n if (typeof process !== \"undefined\" && process.env) {\n for (const envVar of providerConfig.envVars) {\n const apiKey = process.env[envVar];\n if (apiKey) {\n logger.debug(\n `Using API key from environment variable ${envVar} for provider ${provider}`\n );\n return apiKey;\n }\n }\n }\n\n // No API key found\n const envVarsStr = providerConfig.envVars.join(\" or \");\n throw new Error(\n `API key not found for provider '${provider}'. ` +\n `Set ${envVarsStr} environment variable or pass apiKey in llmConfig. ` +\n `Example: new MCPAgent({ llm: '${provider}/model', llmConfig: { apiKey: 'your-key' } })`\n );\n}\n\n/**\n * Dynamically imports and instantiates a LangChain chat model.\n *\n * @param llmString - LLM specification in format \"provider/model\" (e.g., \"openai/gpt-4\")\n * @param config - Optional configuration for the LLM (apiKey, temperature, etc.)\n * @returns The instantiated LangChain model.\n * @throws Error if credentials are unavailable, the provider package is not\n * installed, or the model cannot be constructed.\n *\n * @example\n * ```ts\n * const llm = await createLLMFromString('openai/gpt-4', { temperature: 0.7 });\n * ```\n *\n * @example\n * ```ts\n * const llm = await createLLMFromString('anthropic/claude-sonnet-4-6');\n * ```\n */\nexport async function createLLMFromString(\n llmString: string,\n config?: LLMConfig\n): Promise<LanguageModel> {\n logger.debug(`Creating LLM from string: ${llmString}`);\n\n const { provider, model } = parseLLMString(llmString);\n const providerConfig = PROVIDER_CONFIG[provider];\n\n // Get API key\n const apiKey = getAPIKey(provider, config);\n\n // Dynamically import the provider package\n let providerModule: any;\n try {\n logger.debug(`Importing package ${providerConfig.package}...`);\n providerModule = await import(providerConfig.package);\n } catch (error: any) {\n // Check if it's a module not found error\n if (\n error?.code === \"MODULE_NOT_FOUND\" ||\n error?.message?.includes(\"Cannot find module\") ||\n error?.message?.includes(\"Cannot find package\")\n ) {\n throw new Error(\n `Package '${providerConfig.package}' is not installed. ` +\n `Install it with: npm install ${providerConfig.package}, pnpm add ${providerConfig.package}, or bun add ${providerConfig.package}`\n );\n }\n throw new Error(\n `Failed to import ${providerConfig.package}: ${error?.message || error}`\n );\n }\n\n // Get the class from the module\n const LLMClass = providerModule[providerConfig.className];\n if (!LLMClass) {\n throw new Error(\n `Could not find ${providerConfig.className} in package ${providerConfig.package}. ` +\n `This might be a version compatibility issue.`\n );\n }\n\n // Build configuration object\n const llmConfig: Record<string, any> = {\n model,\n apiKey,\n ...config,\n };\n\n // Remove apiKey from the spread to avoid duplication\n if (config?.apiKey) {\n delete llmConfig.apiKey;\n llmConfig.apiKey = apiKey;\n }\n\n // Provider-specific configuration mapping\n if (provider === \"anthropic\") {\n // Anthropic uses 'model' parameter\n llmConfig.model = model;\n } else if (provider === \"google\") {\n // Google uses 'model' parameter\n llmConfig.model = model;\n } else if (provider === \"openai\") {\n // OpenAI uses 'model' parameter\n llmConfig.model = model;\n } else if (provider === \"groq\") {\n // Groq uses 'model' parameter\n llmConfig.model = model;\n }\n\n // Instantiate the LLM\n try {\n const llmInstance = new LLMClass(llmConfig);\n logger.debug(`Successfully created ${provider} LLM with model ${model}`);\n return llmInstance as LanguageModel;\n } catch (error: any) {\n throw new Error(\n `Failed to instantiate ${providerConfig.className} with model '${model}': ${error?.message || error}`\n );\n }\n}\n\n/**\n * Tests whether an LLM identifier has a supported provider and valid format.\n *\n * @param llmString - Candidate `\"provider/model\"` identifier.\n * @returns `true` when {@link parseLLMString} accepts the identifier.\n */\nexport function isValidLLMString(llmString: string): boolean {\n try {\n parseLLMString(llmString);\n return true;\n } catch {\n return false;\n }\n}\n\n/** @returns A new array containing every supported LangChain provider. */\nexport function getSupportedProviders(): LLMProvider[] {\n return Object.keys(PROVIDER_CONFIG) as LLMProvider[];\n}\n","/**\n * Prompt templates for MCP agents.\n *\n * This module provides prompt templates to guide agents on how to use\n * MCP tools, including code execution mode.\n */\n\n// ponytail: CODE_MODE_AGENT_PROMPT may be absent on older @mcp-use/client builds\nconst CODE_MODE_PROMPT =\n \"Use code execution mode to discover and call MCP tools programmatically.\";\n\n/**\n * Built-in prompt fragments for agent features.\n *\n * `CODE_MODE` instructs a model to discover and invoke MCP tools through the\n * code execution interface.\n */\nexport const PROMPTS = {\n /** Instruction used to enable code-based MCP tool discovery and calls. */\n CODE_MODE: CODE_MODE_PROMPT,\n} as const;\n","/**\n * AI SDK Integration Utilities\n *\n * Utility functions for integrating MCPAgent's streamEvents with Vercel AI SDK.\n * These utilities help convert stream events to AI SDK compatible formats.\n */\n\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\n\n/**\n * Converts LangChain model stream events to text chunks.\n *\n * @param streamEvents - Events returned by the LangChain agent's\n * `streamEvents` method.\n * @returns An async generator containing only model text chunks.\n */\nexport async function* streamEventsToAISDK(\n streamEvents: AsyncGenerator<StreamEvent, void, void>\n): AsyncGenerator<string, void, void> {\n for await (const event of streamEvents) {\n if (event.event === \"on_chat_model_stream\" && event.data?.chunk?.text) {\n const textContent = event.data.chunk.text;\n if (typeof textContent === \"string\" && textContent.length > 0) {\n yield textContent;\n }\n }\n }\n}\n\n/**\n * Wraps an async text generator in a web `ReadableStream`.\n *\n * @param generator - Async text generator to consume.\n * @returns A stream that enqueues each generated string and forwards errors.\n */\nexport function createReadableStreamFromGenerator(\n generator: AsyncGenerator<string, void, void>\n): ReadableStream<string> {\n return new ReadableStream({\n async start(controller) {\n try {\n for await (const chunk of generator) {\n controller.enqueue(chunk);\n }\n controller.close();\n } catch (error) {\n controller.error(error);\n }\n },\n });\n}\n\n/**\n * Converts LangChain events to text and inserts tool lifecycle messages.\n *\n * @param streamEvents - Events returned by the LangChain agent's\n * `streamEvents` method.\n * @returns Model text interleaved with human-readable tool start/end messages.\n */\nexport async function* streamEventsToAISDKWithTools(\n streamEvents: AsyncGenerator<StreamEvent, void, void>\n): AsyncGenerator<string, void, void> {\n for await (const event of streamEvents) {\n switch (event.event) {\n case \"on_chat_model_stream\":\n if (event.data?.chunk?.text) {\n const textContent = event.data.chunk.text;\n if (typeof textContent === \"string\" && textContent.length > 0) {\n yield textContent;\n }\n }\n break;\n\n case \"on_tool_start\":\n yield `\\n🔧 Using tool: ${event.name}\\n`;\n break;\n\n case \"on_tool_end\":\n yield `\\n✅ Tool completed: ${event.name}\\n`;\n break;\n default:\n break;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,SAAS,UAAAA,eAAc;AAQvB,SAAS,UAAU,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;AAAA;AACpC;AAAA,MAEF,KAAK;AACH,cAAM;AAAA,yBAAuB,MAAM,IAAI;AAAA;AACvC;AAAA,MACF;AACE;AAAA,IACJ;AAAA,EACF;AACF;","names":["logger","config","agentId","metadata","metadataProvider","tagsProvider","execResult","isError","title","SystemMessage","toJSONSchema","logger","logger","i","fallback","logger","logger","z","z","StructuredTool","z","logger","z","logger","z","logger","z","logger","z","logger","z","z","logger","logger","langfuseHandler","langfuseInitPromise","initializeLangfuse","logger","logger","logger","SystemMessage","toJSONSchema"]}
|