Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

fix: upgrade langflow to 1.12.2 and upgrade flows (#2342)

Lucas Oliveira88ea3fc76632
diff --git a/Dockerfile.langflow b/Dockerfile.langflow
index e128ec9a5..60774b936 100644
--- a/Dockerfile.langflow
+++ b/Dockerfile.langflow
@@ -1,12 +1,16 @@
# syntax=docker/dockerfile:1.4
-FROM langflowai/langflow:base-0.11.6
+FROM langflowai/langflow:base-1.12.2
-# Install uv and pre-create the Langflow data directory.
-# The base image already runs as uid=1000 and owns /app, so no root or chown needed.
+# Install uv, then pre-create the Langflow data directory as root.
+# Langflow 1.12's base image runs as uid=1000, but /app itself is not writable.
# Upgrade pip first to patch CVE-2026-8643 (fixed in 26.1.2) in the base image.
RUN pip install --no-cache-dir --upgrade "pip>=26.1.2" \
- && pip install --no-cache-dir uv \
- && mkdir -p /app/langflow-data
+ && pip install --no-cache-dir uv
+
+USER root
+RUN mkdir -p /app/langflow-data \
+ && chmod 0777 /app/langflow-data
+USER 1000
RUN pip install --no-cache-dir \
--extra-index-url https://download.pytorch.org/whl/cpu \
@@ -29,9 +33,8 @@ RUN pip install --no-cache-dir \
COPY flows/ /app/flows/
COPY custom_components/ /app/custom_components/
-# Copy the entrypoint before switching to root so the COPY runs as uid=1000
-# (which owns /app), then switch to root so the entrypoint can correct
-# bind-mount permissions at runtime before dropping back to uid=1000.
+# Switch to root so the entrypoint can correct bind-mount permissions at
+# runtime before dropping back to uid=1000.
COPY --chmod=755 scripts/langflow-entrypoint.py /usr/local/bin/langflow-entrypoint
COPY scripts/patch_langflow_openrag_bundle.py /tmp/patch_langflow_openrag_bundle.py
USER root
diff --git a/flows/openrag_agent.json b/flows/openrag_agent.json
index 5b5ec1899..d4efa95ce 100644
--- a/flows/openrag_agent.json
+++ b/flows/openrag_agent.json
@@ -967,10 +967,9 @@
],
"frozen": false,
"icon": "bot",
- "last_updated": "2026-08-18T22:52:17.781Z",
"legacy": false,
"metadata": {
- "code_hash": "e3c6d36a2020",
+ "code_hash": "d7994f67e4fa",
"dependencies": {
"dependencies": [
{
@@ -983,11 +982,11 @@
},
{
"name": "lfx",
- "version": "1.11.2"
+ "version": "1.12.0"
},
{
"name": "langchain_core",
- "version": "1.5.3"
+ "version": "1.6.2"
}
],
"total_dependencies": 4
@@ -1037,14 +1036,6 @@
],
"pinned": false,
"template": {
- "_frontend_node_flow_id": {
- "input_types": [],
- "value": "1098eea1-6649-4e1d-aed1-b77249fb8dd0"
- },
- "_frontend_node_folder_id": {
- "input_types": [],
- "value": "501d7212-c442-4593-a43a-e987cc095eb4"
- },
"_type": "Component",
"add_calculator_tool": {
"_input_type": "BoolInput",
@@ -1053,7 +1044,6 @@
"display_name": "Calculator",
"dynamic": false,
"info": "If true, adds a zero-config arithmetic calculator tool to the agent (safe: only +, -, *, /, ** operators via AST).",
- "input_types": [],
"list": false,
"list_add_label": "Add More",
"name": "add_calculator_tool",
@@ -1075,7 +1065,6 @@
"display_name": "Current Date",
"dynamic": false,
"info": "If true, will add a tool to the agent that returns the current date.",
- "input_types": [],
"list": false,
"list_add_label": "Add More",
"name": "add_current_date_tool",
@@ -1121,7 +1110,6 @@
"dynamic": false,
"external_options": {},
"info": "The base URL of the API (IBM watsonx.ai only)",
- "input_types": [],
"name": "base_url_ibm_watsonx",
"options": [
"https://us-south.ml.cloud.ibm.com",
@@ -1152,7 +1140,6 @@
"fileTypes": [],
"file_path": "",
"info": "",
- "input_types": [],
"list": false,
"load_from_db": false,
"multiline": true,
@@ -1163,7 +1150,7 @@
"show": true,
"title_case": false,
"type": "code",
- "value": "from __future__ import annotations\n\nimport uuid\nfrom contextlib import contextmanager\nfrom datetime import datetime, timezone\nfrom typing import TYPE_CHECKING, Any, cast\n\nfrom langchain.agents import create_agent\nfrom langchain.agents.middleware import (\n HumanInTheLoopMiddleware,\n ModelCallLimitMiddleware,\n ToolRetryMiddleware,\n)\nfrom langgraph.types import Command\n\nfrom lfx.components.models_and_agents.agent_helpers.graph_event_adapter import (\n adapt_graph_events_to_executor_shape,\n)\nfrom lfx.components.models_and_agents.agent_helpers.messages_input_builder import (\n build_initial_messages,\n)\nfrom lfx.components.models_and_agents.agent_helpers.placeholder_corrective_middleware import (\n WatsonXPlaceholderMiddleware,\n)\nfrom lfx.components.models_and_agents.agent_helpers.single_tool_call_middleware import (\n SingleToolCallMiddleware,\n)\nfrom lfx.components.models_and_agents.agent_helpers.tool_approval import ToolApprovalMixin\nfrom lfx.components.models_and_agents.agent_helpers.tool_call_id_middleware import ToolCallIDMiddleware\nfrom lfx.components.models_and_agents.memory import MemoryComponent, _safe_graph_user_id, aget_agent_chat_history\n\nif TYPE_CHECKING:\n from collections.abc import Awaitable, Callable\n\n from langchain_core.tools import Tool\n\n from lfx.schema.log import OnTokenFunctionType, SendMessageFunctionType\n\nfrom lfx.base.agents.agent import LCToolsAgentComponent\nfrom lfx.base.agents.callback import AgentAsyncHandler\nfrom lfx.base.agents.default_system_prompt import DEFAULT_SYSTEM_PROMPT_TEMPLATE\nfrom lfx.base.agents.events import AgentPausedError, ExceptionWithMessageError, process_agent_events\nfrom lfx.base.agents.token_callback import TokenUsageCallbackHandler\nfrom lfx.base.agents.utils import get_chat_output_sender_name\nfrom lfx.base.constants import STREAM_INFO_TEXT\nfrom lfx.base.models.unified_models import (\n get_language_model_options,\n get_llm,\n handle_model_input_update,\n)\nfrom lfx.base.models.watsonx_constants import IBM_WATSONX_URLS\nfrom lfx.components.agentics.helpers.model_config import validate_model_selection\nfrom lfx.components.helpers import CalculatorComponent, CurrentDateComponent\nfrom lfx.components.langchain_utilities.ibm_granite_handler import is_watsonx_model\nfrom lfx.components.langchain_utilities.tool_calling import ToolCallingAgentComponent\nfrom lfx.custom.custom_component.component import get_component_toolkit\nfrom lfx.field_typing.range_spec import RangeSpec\nfrom lfx.inputs.inputs import BoolInput, DropdownInput, ModelInput, StrInput\nfrom lfx.io import IntInput, MessageTextInput, MultilineInput, Output, SecretStrInput, TableInput\nfrom lfx.log.logger import logger\nfrom lfx.memory import delete_message\nfrom lfx.schema.data import Data\nfrom lfx.schema.dotdict import dotdict\nfrom lfx.schema.message import Message\nfrom lfx.schema.table import EditMode\nfrom lfx.utils.constants import MESSAGE_SENDER_AI\n\n\ndef set_advanced_true(component_input):\n component_input.advanced = True\n return component_input\n\n\ndef _agent_base_inputs():\n \"\"\"Return base inputs tailored to AgentComponent's create_agent path.\n\n `get_base_inputs()` returns a shared list — replace, don't mutate. We drop\n inputs that are no-ops here and override info text on the inputs whose\n semantics shifted under create_agent.\n\n `verbose` is dropped because the create_agent event stream already surfaces\n every agent step via the \"Agent Steps\" content blocks; the legacy boolean\n has nothing to toggle. Saved flows that still carry a `verbose` value just\n ignore it on load (the schema no longer declares it).\n \"\"\"\n drop = {\"verbose\"}\n overrides = {\n \"handle_parsing_errors\": BoolInput(\n name=\"handle_parsing_errors\",\n display_name=\"Handle Parse Errors\",\n value=True,\n advanced=True,\n info=(\n \"Adds tool-execution retry as a safety net. `create_agent` already \"\n \"feeds tool-call validation errors back to the LLM automatically; \"\n \"this flag layers `ToolRetryMiddleware` on top so transient tool \"\n \"runtime failures are retried (max 2 retries).\"\n ),\n ),\n \"max_iterations\": IntInput(\n name=\"max_iterations\",\n display_name=\"Max Iterations\",\n value=15,\n advanced=True,\n range_spec=RangeSpec(min=1, max=128000, step=1, step_type=\"int\"),\n info=(\n \"Maximum number of model calls the agent can make before stopping \"\n \"(maps to `ModelCallLimitMiddleware.run_limit` on the create_agent \"\n \"path). Must be at least 1 — it is a safety cap, never 'unlimited'.\"\n ),\n ),\n }\n return [overrides.get(inp.name, inp) for inp in LCToolsAgentComponent.get_base_inputs() if inp.name not in drop]\n\n\ndef _extract_text_content(value) -> str:\n \"\"\"Pull a string payload from a Message-like, AIMessage-like, or string value.\"\"\"\n if isinstance(value, str):\n return value\n text = getattr(value, \"text\", None)\n if isinstance(text, str):\n return text\n content = getattr(value, \"content\", None)\n if isinstance(content, str):\n return content\n return str(value) if value is not None else \"\"\n\n\n@contextmanager\ndef _suppress_send_message(component: Any):\n \"\"\"Temporarily replace component.send_message with a no-op for the duration of the block.\n\n Used during the structured-output prompt fallback: run_agent streams the agent's\n final answer through self.send_message (correct for message_response), but in\n json_response the orchestrator parses that text into structured Data which the\n downstream Chat Output emits — leaving the original emission in place produces a\n duplicate message in the playground. The original method is always restored on exit,\n even when the wrapped call raises.\n \"\"\"\n original = component.send_message\n\n async def _noop(message, *_args, **_kwargs):\n return message\n\n component.send_message = _noop\n try:\n yield\n finally:\n component.send_message = original\n\n\nclass AgentComponent(ToolApprovalMixin, ToolCallingAgentComponent):\n display_name: str = \"Agent\"\n description: str = \"Define the agent's instructions, then enter a task to complete using tools.\"\n documentation: str = \"https://docs.langflow.org/agents\"\n icon = \"bot\"\n beta = False\n name = \"Agent\"\n\n memory_inputs = [set_advanced_true(component_input) for component_input in MemoryComponent().inputs]\n\n inputs = [\n ModelInput(\n name=\"model\",\n display_name=\"Language Model\",\n info=\"Select your model provider\",\n real_time_refresh=True,\n required=True,\n # Agents require tool calling — the filter is honored by\n # ``handle_model_input_update`` so models that can't run with\n # tools never reach the picker (and any saved selection that\n # no longer satisfies the constraint is auto-replaced).\n filters={\"tool_calling\": True},\n ),\n SecretStrInput(\n name=\"api_key\",\n display_name=\"API Key\",\n info=\"Overrides global provider settings. Leave blank to use your pre-configured API Key.\",\n real_time_refresh=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"base_url_ibm_watsonx\",\n display_name=\"watsonx API Endpoint\",\n info=\"The base URL of the API (IBM watsonx.ai only)\",\n options=IBM_WATSONX_URLS,\n value=IBM_WATSONX_URLS[0],\n combobox=True,\n show=False,\n real_time_refresh=True,\n ),\n StrInput(\n name=\"project_id\",\n display_name=\"watsonx Project ID\",\n info=\"The project ID associated with the foundation model (IBM watsonx.ai only)\",\n show=False,\n required=False,\n ),\n MultilineInput(\n name=\"system_prompt\",\n display_name=\"Agent Instructions\",\n info=(\n \"System Prompt: Initial instructions and context provided to guide the agent's behavior. \"\n \"Supports dynamic placeholders: {current_date}, {model_name}, {optional_user_context}.\"\n ),\n value=DEFAULT_SYSTEM_PROMPT_TEMPLATE,\n advanced=False,\n ),\n MessageTextInput(\n name=\"context_id\",\n display_name=\"Context ID\",\n info=\"The context ID of the chat. Adds an extra layer to the local memory.\",\n value=\"\",\n advanced=True,\n ),\n IntInput(\n name=\"n_messages\",\n display_name=\"Number of Chat History Messages\",\n value=100,\n info=\"Number of chat history messages to retrieve.\",\n advanced=True,\n show=True,\n ),\n IntInput(\n name=\"max_tokens\",\n display_name=\"Max Tokens\",\n info=\"Maximum number of tokens to generate. Field name varies by provider.\",\n advanced=True,\n range_spec=RangeSpec(min=1, max=128000, step=1, step_type=\"int\"),\n ),\n MultilineInput(\n name=\"format_instructions\",\n display_name=\"Output Format Instructions\",\n info=\"Generic Template for structured output formatting. Valid only with Structured response.\",\n value=(\n \"You are an AI that extracts structured JSON objects from unstructured text. \"\n \"Use a predefined schema with expected types (str, int, float, bool, dict). \"\n \"Extract ALL relevant instances that match the schema - if multiple patterns exist, capture them all. \"\n \"Fill missing or ambiguous values with defaults: null for missing values. \"\n \"Remove exact duplicates but keep variations that have different field values. \"\n \"Always return valid JSON in the expected format, never throw errors. \"\n \"If multiple objects can be extracted, return them all in the structured format.\"\n ),\n advanced=True,\n ),\n TableInput(\n name=\"output_schema\",\n display_name=\"Output Schema\",\n info=(\n \"Schema Validation: Define the structure and data types for structured output. \"\n \"No validation if no output schema.\"\n ),\n advanced=True,\n required=False,\n value=[],\n table_schema=[\n {\n \"name\": \"name\",\n \"display_name\": \"Name\",\n \"type\": \"str\",\n \"description\": \"Specify the name of the output field.\",\n \"default\": \"field\",\n \"edit_mode\": EditMode.INLINE,\n },\n {\n \"name\": \"description\",\n \"display_name\": \"Description\",\n \"type\": \"str\",\n \"description\": \"Describe the purpose of the output field.\",\n \"default\": \"description of field\",\n \"edit_mode\": EditMode.POPOVER,\n },\n {\n \"name\": \"type\",\n \"display_name\": \"Type\",\n \"type\": \"str\",\n \"edit_mode\": EditMode.INLINE,\n \"description\": (\"Indicate the data type of the output field (e.g., str, int, float, bool, dict).\"),\n \"options\": [\"str\", \"int\", \"float\", \"bool\", \"dict\"],\n \"default\": \"str\",\n },\n {\n \"name\": \"multiple\",\n \"display_name\": \"As List\",\n \"type\": \"boolean\",\n \"description\": \"Set to True if this output field should be a list of the specified type.\",\n \"default\": \"False\",\n \"edit_mode\": EditMode.INLINE,\n },\n ],\n ),\n *_agent_base_inputs(),\n # removed memory inputs from agent component\n # *memory_inputs,\n BoolInput(\n name=\"stream\",\n display_name=\"Stream\",\n info=STREAM_INFO_TEXT,\n value=True,\n advanced=True,\n ),\n BoolInput(\n name=\"add_current_date_tool\",\n display_name=\"Current Date\",\n advanced=True,\n info=\"If true, will add a tool to the agent that returns the current date.\",\n value=True,\n ),\n BoolInput(\n name=\"add_calculator_tool\",\n display_name=\"Calculator\",\n advanced=True,\n info=(\n \"If true, adds a zero-config arithmetic calculator tool to the agent \"\n \"(safe: only +, -, *, /, ** operators via AST).\"\n ),\n value=True,\n ),\n ]\n outputs = [\n Output(name=\"response\", display_name=\"Response\", method=\"message_response\"),\n Output(\n name=\"structured_response\",\n display_name=\"Structured Response\",\n method=\"json_response\",\n types=[\"Data\"],\n ),\n ]\n\n def _resolve_selected_model(self):\n \"\"\"Resolve the selected model, including legacy agent_llm/model_name inputs.\"\"\"\n try:\n from langchain_core.language_models import BaseLanguageModel\n\n if isinstance(self.model, BaseLanguageModel):\n return self.model\n except ImportError:\n pass\n\n if isinstance(self.model, list) and self.model:\n return self.model\n\n legacy_provider = getattr(self, \"agent_llm\", None)\n legacy_model_name = getattr(self, \"model_name\", None)\n if not legacy_provider or not legacy_model_name:\n return self.model\n\n options = get_language_model_options(user_id=self.user_id)\n for option in options:\n if option.get(\"provider\") == legacy_provider and option.get(\"name\") == legacy_model_name:\n return [option]\n\n return [\n {\n \"name\": legacy_model_name,\n \"provider\": legacy_provider,\n \"metadata\": {},\n }\n ]\n\n def _get_max_tokens_value(self):\n \"\"\"Return the user-supplied max_tokens or None when unset/zero.\"\"\"\n val = getattr(self, \"max_tokens\", None)\n if val in {\"\", 0}:\n return None\n return val\n\n def _get_llm(self):\n \"\"\"Override parent to include max_tokens from the Agent's input field.\n\n Streaming is mandatory for AgentComponent: ``runnable.astream_events(v2)`` only\n emits ``on_chat_model_stream`` chunks when the underlying chat model is\n instantiated with ``streaming=True``. Unlike the LanguageModel component (where\n ``stream`` is a user-facing toggle), the Agent has no opt-out — the toggle is\n kept in the UI for backwards compatibility but is intentionally ignored here.\n Without ``stream=True``, the chat model accumulates the whole response and\n only emits ``on_chat_model_end``, silently disabling the Playground's live-\n typing view and breaking the streaming contract on the /events surface.\n \"\"\"\n return get_llm(\n model=self.model,\n user_id=self.user_id,\n api_key=getattr(self, \"api_key\", None),\n stream=True,\n max_tokens=self._get_max_tokens_value(),\n watsonx_url=getattr(self, \"base_url_ibm_watsonx\", None),\n watsonx_project_id=getattr(self, \"project_id\", None),\n overrides=getattr(self, \"_model_overrides\", None),\n )\n\n async def get_agent_requirements(self):\n \"\"\"Get the agent requirements for the agent.\"\"\"\n from langchain_core.tools import StructuredTool\n\n selected_model = self._resolve_selected_model()\n try:\n from langchain_core.language_models import BaseLanguageModel\n\n is_connected_model = isinstance(selected_model, BaseLanguageModel)\n except ImportError:\n is_connected_model = False\n\n if not is_connected_model:\n validate_model_selection(selected_model)\n\n # Ensure _get_llm() uses the resolved model (e.g. from legacy agent_llm/model_name)\n self.model = selected_model\n llm_model = self._get_llm()\n if llm_model is None:\n msg = \"No language model selected. Please choose a model to proceed.\"\n raise ValueError(msg)\n\n # Get memory data\n self.chat_history = await self.get_memory_data()\n await logger.adebug(f\"Retrieved {len(self.chat_history)} chat history messages\")\n if isinstance(self.chat_history, Message):\n self.chat_history = [self.chat_history]\n\n # Add current date tool if enabled\n if self.add_current_date_tool:\n if not isinstance(self.tools, list): # type: ignore[has-type]\n self.tools = []\n current_date_tool = (await CurrentDateComponent(**self.get_base_args()).to_toolkit()).pop(0)\n\n if not isinstance(current_date_tool, StructuredTool):\n msg = \"CurrentDateComponent must be converted to a StructuredTool\"\n raise TypeError(msg)\n # Skip if an externally-connected tool already provides the same name.\n # Duplicate tool names are rejected by Anthropic/Gemini with HTTP 400.\n if not any(getattr(t, \"name\", None) == current_date_tool.name for t in self.tools):\n self.tools.append(current_date_tool)\n\n # Add calculator tool if enabled (zero-config arithmetic)\n if getattr(self, \"add_calculator_tool\", False):\n if not isinstance(self.tools, list): # type: ignore[has-type]\n self.tools = []\n calculator_tool = (await CalculatorComponent(**self.get_base_args()).to_toolkit()).pop(0)\n\n if not isinstance(calculator_tool, StructuredTool):\n msg = \"CalculatorComponent must be converted to a StructuredTool\"\n raise TypeError(msg)\n # Skip if an externally-connected tool already provides the same name.\n # Duplicate tool names are rejected by Anthropic/Gemini with HTTP 400.\n if not any(getattr(t, \"name\", None) == calculator_tool.name for t in self.tools):\n self.tools.append(calculator_tool)\n\n # Set shared callbacks for tracing the tools used by the agent\n self.set_tools_callbacks(self.tools, self._get_shared_callbacks())\n\n return llm_model, self.chat_history, self.tools\n\n def _get_resolved_model_name(self) -> str:\n \"\"\"Best-effort human-readable model name for {model_name} injection.\"\"\"\n try:\n from langchain_core.language_models import BaseLanguageModel\n\n if isinstance(self.model, BaseLanguageModel):\n return type(self.model).__name__\n except ImportError:\n pass\n\n if isinstance(self.model, list) and self.model:\n first = self.model[0]\n if isinstance(first, dict):\n name = first.get(\"name\")\n if isinstance(name, str) and name:\n return name\n\n legacy_model_name = getattr(self, \"model_name\", None)\n if isinstance(legacy_model_name, str) and legacy_model_name:\n return legacy_model_name\n return \"\"\n\n def _inject_dynamic_prompt_values(self, prompt: Any | None) -> str | None:\n \"\"\"Replace known env placeholders in the system prompt.\n\n Handles {current_date}, {model_name}, and {optional_user_context} (the\n last one ships with the structured DEFAULT_SYSTEM_PROMPT_TEMPLATE and\n is currently unused at the AgentComponent layer, so it resolves to \"\").\n Uses str.replace (not str.format) so user prompts containing literal\n braces such as JSON examples ({\"key\": 1}) never break the agent.\n\n `system_prompt` is a connectable MultilineInput, so the value can arrive\n as a Message (e.g. a Prompt node wired in). Normalize it to text first —\n a raw Message has no `.replace` and used to crash the agent build.\n \"\"\"\n if prompt is None:\n return None\n prompt = _extract_text_content(prompt)\n if not prompt:\n return prompt\n replacements = {\n \"{current_date}\": datetime.now(tz=timezone.utc).strftime(\"%Y-%m-%d %H:%M:%S UTC\"),\n \"{model_name}\": self._get_resolved_model_name(),\n \"{optional_user_context}\": \"\",\n }\n for placeholder, value in replacements.items():\n prompt = prompt.replace(placeholder, value)\n return prompt\n\n def create_agent_runnable(self, *, allow_interrupts: bool = True):\n \"\"\"Build the LangGraph `CompiledStateGraph` via `langchain.agents.create_agent`.\n\n Replaces the legacy `AgentExecutor` runnable inherited from\n `ToolCallingAgentComponent`. Other agent components (tool_calling, csv, json,\n openapi, sql*, vector_store_router) keep the legacy path — only AgentComponent\n runs on the new graph API.\n\n `max_iterations` and `handle_parsing_errors` (legacy AgentExecutor knobs) are\n translated to LangGraph middleware. Without that translation those user inputs\n would silently become no-ops on the new API.\n\n Provider notes:\n - WatsonX/Granite work natively with create_agent — `ChatWatsonx.bind_tools`\n handles tool_choice correctly. The legacy `create_granite_agent` path was\n dropped because it hardcoded `tool_choice='required'`, which the WatsonX\n API now rejects.\n - Ollama and other small/local models often emit malformed tool args. The\n ToolRetryMiddleware (default `retry_on=(Exception,)`, `on_failure='continue'`)\n catches Pydantic ValidationErrors from bad args and feeds the error back\n to the LLM as a retry signal, so the agent recovers gracefully.\n \"\"\"\n llm = self._get_llm()\n tools = self.tools or []\n\n # Eager bind_tools validation. `create_agent(...)` is lazy — without this,\n # an LLM that doesn't support tool calling fails on the first user message\n # instead of when the user wires up the component, which is a much worse UX.\n # Gated on a non-empty tools list so a no-tool Agent on a plain chat model\n # (which legitimately has no `bind_tools`) isn't shut out at flow-build time.\n # Providers signal \"no tool calling\" inconsistently — `NotImplementedError`\n # (langchain default), `AttributeError` (no `bind_tools` attr), or `TypeError`\n # (signature mismatch). Treat all three as the same UX failure.\n if tools:\n try:\n llm.bind_tools(tools)\n except (NotImplementedError, AttributeError, TypeError) as exc:\n # Include the underlying error so a broken tool schema or a\n # provider implementation bug is not silently disguised as a\n # \"model can't call tools\" UX error.\n msg = (\n f\"{self.display_name} does not support tool calling, \"\n \"or one of the connected tools failed to bind. \"\n \"Please connect a tool-calling capable language model and \"\n f\"verify your tools are well-formed. Underlying error: {exc!s}\"\n )\n raise NotImplementedError(msg) from exc\n\n middleware = self._build_middleware(llm, allow_interrupts=allow_interrupts)\n checkpointer = self._build_agent_checkpointer() if allow_interrupts else None\n return create_agent(\n model=llm,\n tools=tools,\n system_prompt=self.system_prompt or \"\",\n middleware=middleware or None,\n checkpointer=checkpointer,\n )\n\n def _compute_recursion_limit(self) -> int:\n \"\"\"Derive the LangGraph recursion_limit from the user-set max_iterations.\n\n Mirrors the clamp in `_build_middleware` (max(1, max_iterations)) so a\n saved 0 or negative value cannot under-cap the graph below one full\n iteration. The +5 buffer covers start/end/router overhead.\n \"\"\"\n raw = getattr(self, \"max_iterations\", None)\n run_limit = max(1, int(raw)) if raw is not None else 15\n return run_limit * 2 + 5\n\n def _build_middleware(self, llm: Any, *, allow_interrupts: bool = True) -> list:\n # `llm` is passed in (rather than re-fetched via `self._get_llm()`)\n # because some providers do credential resolution / client instantiation\n # lazily on each call. The caller — `create_agent_runnable` — already\n # resolved it once for `bind_tools`, so reuse that instance here.\n middleware: list = []\n # LangChain accepts missing IDs on AIMessage.tool_calls, but LangGraph's\n # invalid-call path and ToolRetryMiddleware both require a string when\n # they construct an error ToolMessage. Normalize at the model boundary\n # so either recovery path can return the error to the model instead of\n # crashing the flow.\n if self.tools:\n middleware.append(ToolCallIDMiddleware())\n max_iterations = getattr(self, \"max_iterations\", None)\n if max_iterations is not None:\n # `max_iterations` is a safety cap, not an \"unlimited\" toggle. A saved\n # 0 or negative value (falsy) must NOT silently drop the limiter and\n # allow an unbounded model/tool loop — clamp it to a real minimum.\n run_limit = max(1, int(max_iterations))\n middleware.append(ModelCallLimitMiddleware(run_limit=run_limit))\n # ToolRetryMiddleware only matters when there ARE tools to retry. Attaching\n # it on a no-tools agent inflates the compiled graph and adds per-invocation\n # middleware overhead for nothing, which is a measurable contributor to\n # trivial-prompt latency (QA UI-003).\n if getattr(self, \"handle_parsing_errors\", False) and self.tools:\n middleware.append(ToolRetryMiddleware(max_retries=2))\n # WatsonX models have two known platform quirks; both still reproduce on\n # the current API, so we keep the protections from the legacy\n # `create_granite_agent` path.\n # 1. Multi-tool-call assistant turns are rejected (\"This model only\n # supports single tool-calls at once!\"). Clamp to one per turn.\n # 2. Tool args occasionally come back as literal placeholder strings\n # (e.g. `<result-from-search>`). Re-invoke once with a corrective\n # SystemMessage.\n # Order: SingleToolCallMiddleware first (outermost) so the clamp is\n # applied to the final response, including any corrective re-invoke\n # produced by WatsonXPlaceholderMiddleware.\n if is_watsonx_model(llm):\n middleware.append(SingleToolCallMiddleware())\n middleware.append(WatsonXPlaceholderMiddleware())\n # Human-in-the-loop: attach only when a tool is gated AND interrupts are allowed\n # (the structured-output path disables them), keeping ungated flows unchanged.\n interrupt_on = self._gated_interrupt_on() if allow_interrupts else {}\n if interrupt_on:\n middleware.append(HumanInTheLoopMiddleware(interrupt_on=interrupt_on))\n return middleware\n\n async def run_agent(self, agent) -> Message:\n \"\"\"Run the LangGraph `CompiledStateGraph` and return the final agent Message.\n\n Overrides the legacy `LCAgentComponent.run_agent` (which builds an\n `{\"input\": str, \"chat_history\": [...]}` dict for `AgentExecutor`). The graph\n wants `{\"messages\": [BaseMessage, ...]}`. The event stream is wrapped with\n `adapt_graph_events_to_executor_shape` so the legacy `process_agent_events`\n (in `lfx.base.agents.events`) can be reused unchanged.\n \"\"\"\n messages = build_initial_messages(\n input_value=self.input_value,\n chat_history=getattr(self, \"chat_history\", None),\n )\n input_dict = {\"messages\": messages}\n\n agent_message = self._build_initial_agent_message()\n token_usage_handler = TokenUsageCallbackHandler()\n\n # Stream tokens to the event manager when running inside the Langflow runtime.\n # This is what powers the live-typing view in the chat UI.\n on_token_callback: OnTokenFunctionType | None = None\n if getattr(self, \"_event_manager\", None):\n on_token_callback = cast(\"OnTokenFunctionType\", self._event_manager.on_token)\n\n # Align LangGraph's `recursion_limit` with `max_iterations` so the\n # middleware cap (ModelCallLimitMiddleware) is what bounds the loop —\n # not LangGraph's default 25-step guard, which fires at ~12 model+tool\n # iterations and raises a raw GraphRecursionError (QA UI-009/UI-010).\n # Each iteration is ~2 graph steps (model node + tools node); add 5\n # for start/end overhead.\n recursion_limit = self._compute_recursion_limit()\n\n agent_config: dict[str, Any] = {\n \"callbacks\": [\n AgentAsyncHandler(self.log),\n token_usage_handler,\n *self._get_shared_callbacks(),\n ],\n \"recursion_limit\": recursion_limit,\n }\n # The durable checkpointer keys on the per-run thread_id; it must be in the\n # astream_events config (not just create_agent) for both initial run and resume.\n thread_id = self._agent_thread_id()\n get_pending_interrupt = None\n stream_input: Any = input_dict\n # A checkpointer is only present when the agent was built with interrupts enabled\n # (the structured-output path builds without one); never probe its state otherwise.\n interrupts_enabled = getattr(agent, \"checkpointer\", None) is not None\n if interrupts_enabled and thread_id and self._gated_interrupt_on():\n agent_config[\"configurable\"] = {\"thread_id\": thread_id}\n get_pending_interrupt = self._pending_interrupt_getter(agent, agent_config)\n if self._has_candidate_decision(thread_id):\n # The injected decision must match the pending interrupt's nonce, so read\n # the interrupt first; a matched decision resumes the checkpointed thread.\n value, interrupt_id = await self._read_pending_interrupt(agent, agent_config)\n decision = self._injected_agent_decision(thread_id, interrupt_id)\n if decision is not None:\n action_requests = (value or {}).get(\"action_requests\") or []\n stream_input = Command(\n resume={\"decisions\": self._build_resume_decisions(decision, action_requests)}\n )\n stream = adapt_graph_events_to_executor_shape(\n agent.astream_events(stream_input, config=agent_config, version=\"v2\")\n )\n try:\n result = await process_agent_events(\n stream,\n agent_message,\n cast(\"SendMessageFunctionType\", self.send_message),\n on_token_callback,\n get_pending_interrupt=get_pending_interrupt,\n )\n except AgentPausedError as e:\n # Why: retract the empty partial bubble (leaks as \"[]\"); the HITL card supersedes it, resume re-emits it.\n paused_message = e.agent_message or agent_message\n msg_id = paused_message.get_id()\n if msg_id:\n await delete_message(id_=msg_id)\n await self._send_message_event(paused_message, category=\"remove_message\")\n return self._suspend_for_tool_approval(e.request, paused_message)\n except ExceptionWithMessageError as e:\n # Drop the half-stored partial message from the DB (only if it was\n # actually persisted) and tell the frontend to remove the stale bubble.\n if hasattr(e, \"agent_message\"):\n msg_id = e.agent_message.get_id()\n if msg_id:\n await delete_message(id_=msg_id)\n await self._send_message_event(e.agent_message, category=\"remove_message\")\n logger.error(f\"ExceptionWithMessageError: {e}\")\n raise\n\n usage_data = token_usage_handler.get_usage()\n if usage_data:\n self._token_usage = usage_data\n result.properties.usage = usage_data\n # Only round-trip the DB when the message was stored (Chat Output wired).\n # `_should_skip_message=True` leaves `result.get_id()` empty; persisting\n # then would create a phantom row.\n if result.get_id():\n stored_result = await self._update_stored_message(result)\n await self._send_message_event(stored_result)\n result = stored_result\n\n self.status = result\n return result\n\n def _build_initial_agent_message(self) -> Message:\n \"\"\"Construct the placeholder agent Message that `process_agent_events` mutates.\"\"\"\n if hasattr(self, \"graph\"):\n session_id = self.graph.session_id\n elif hasattr(self, \"_session_id\"):\n session_id = self._session_id\n else:\n session_id = None\n\n sender_name = get_chat_output_sender_name(self) or self.display_name or \"AI\"\n return Message(\n sender=MESSAGE_SENDER_AI,\n sender_name=sender_name,\n properties={\"icon\": \"Bot\", \"state\": \"partial\"},\n # `text=\"\"` sentinel so MessageTable's no_content check accepts\n # an in-flight agent message whose content_blocks haven't been\n # populated yet. Mirrors ChatInput's convention.\n text=\"\",\n # Flat chronological event log; see lfx.base.agents.events.\n content_blocks=[],\n session_id=session_id or uuid.uuid4(),\n )\n\n def _selected_model_remediation_context(self) -> tuple[str | None, str | None, Any | None]:\n \"\"\"Return provider/name plus a connected model target, when present.\"\"\"\n try:\n selected = self._resolve_selected_model()\n if isinstance(selected, list) and selected and isinstance(selected[0], dict):\n return selected[0].get(\"provider\"), selected[0].get(\"name\"), None\n\n from langchain_core.language_models import BaseLanguageModel\n\n if isinstance(selected, BaseLanguageModel):\n model_name = None\n for attr in (\"model_name\", \"model\", \"model_id\"):\n value = getattr(selected, attr, None)\n if isinstance(value, str) and value:\n model_name = value\n break\n return self._connected_model_provider(selected), model_name, selected\n except (AttributeError, TypeError, ValueError, KeyError, ImportError):\n pass\n return None, None, None\n\n def _connected_model_provider(self, model: Any) -> str | None:\n \"\"\"Resolve a connected model's provider from the source component.\n\n Runtime model classes are not provider identities: OpenAI, OpenRouter,\n and compatible endpoints can all produce ``ChatOpenAI``. The incoming\n model edge preserves the source component, so prefer its explicit\n provider override or selected-model metadata, then its provider display\n name. If the Agent is used without graph provenance, leave the provider\n unknown so provider-scoped remediations remain disabled.\n \"\"\"\n vertex = getattr(self, \"_vertex\", None)\n if vertex is None:\n return None\n source_id = vertex.get_incoming_edge_by_target_param(\"model\")\n if not source_id:\n return None\n source = vertex.graph.get_vertex(source_id)\n component = getattr(source, \"custom_component\", None)\n if component is None:\n return None\n\n candidate = getattr(component, \"provider\", None)\n\n if not isinstance(candidate, str) or not candidate:\n selected_model = getattr(component, \"model\", None)\n if isinstance(selected_model, list) and selected_model and isinstance(selected_model[0], dict):\n candidate = selected_model[0].get(\"provider\")\n\n if not isinstance(candidate, str) or not candidate:\n candidate = getattr(component, \"display_name\", None)\n if not isinstance(candidate, str) or not candidate:\n return None\n\n from lfx.base.models.unified_models.provider_queries import get_model_provider_metadata\n\n provider_metadata = get_model_provider_metadata().get(candidate, {})\n expected_class = provider_metadata.get(\"mapping\", {}).get(\"model_class\")\n model_classes = {base.__name__ for base in type(model).__mro__}\n return candidate if expected_class in model_classes else None\n\n async def _run_agent_with_model_remediation(\n self,\n run_once: Callable[[], Awaitable[Message]],\n ) -> Message:\n \"\"\"Run one Agent operation, retrying safe provider-validation failures.\n\n Registered remediations must identify request-validation failures that\n occur before tool execution. A failure that can happen after a tool runs\n must instead retry at the model-call boundary to avoid repeating tool\n side effects.\n \"\"\"\n from lfx.base.models.model_remediation import apply_overrides_to_model, find_remediation, remember\n\n provider, model_name, connected_model = self._selected_model_remediation_context()\n applied: set[str] = set()\n while True:\n try:\n result = await run_once()\n except (ValueError, TypeError, KeyError) as exc:\n await logger.aerror(f\"{type(exc).__name__}: {exc!s}\")\n raise\n except Exception as exc:\n # run_agent may wrap the provider error in ExceptionWithMessageError.\n error_text = f\"{exc} {getattr(exc, '__cause__', '') or ''}\"\n remediation = find_remediation(error_text, provider, already_applied=applied)\n if remediation is None:\n await logger.aerror(f\"{type(exc).__name__}: {exc!s}\")\n raise\n if connected_model is not None and not apply_overrides_to_model(connected_model, remediation.overrides):\n await logger.aerror(\n f\"model.remediation.unapplied name={remediation.name} provider={provider} model={model_name}\"\n )\n raise\n applied.add(remediation.name)\n if connected_model is None:\n self._model_overrides = {\n **(getattr(self, \"_model_overrides\", None) or {}),\n **remediation.overrides,\n }\n else:\n # Connected outputs are shared objects across downstream flow\n # branches. The mutation is intentionally flow-scoped: sibling\n # branches holding this model will see the matched override too.\n await logger.adebug(\n f\"model.remediation.shared_model name={remediation.name} provider={provider} model={model_name}\"\n )\n await logger.awarning(\n f\"model.remediation.applied name={remediation.name} provider={provider} model={model_name}\"\n )\n else:\n if connected_model is None and getattr(self, \"_model_overrides\", None):\n remember(provider, model_name, self._model_overrides)\n return result\n\n async def message_response(self) -> Message:\n async def _run_once() -> Message:\n llm_model, self.chat_history, self.tools = await self.get_agent_requirements()\n self.set(\n llm=llm_model,\n tools=self.tools or [],\n chat_history=self.chat_history,\n input_value=self.input_value,\n system_prompt=self._inject_dynamic_prompt_values(self.system_prompt),\n )\n agent = self.create_agent_runnable()\n return await self.run_agent(agent)\n\n result = await self._run_agent_with_model_remediation(_run_once)\n self._agent_result = result\n return result\n\n async def json_response(self) -> Data:\n \"\"\"Produce structured Data via native LLM structured output, with prompt-based fallback.\n\n Native path (no tools, llm has with_structured_output) bypasses the agent loop and\n returns provider-validated JSON. When tools are attached, falls back to running the\n agent with a schema-augmented system prompt and parsing the final message content.\n \"\"\"\n from lfx.components.models_and_agents.structured_output.structured_output_orchestrator import (\n orchestrate_structured_output,\n )\n\n try:\n llm_model, self.chat_history, self.tools = await self.get_agent_requirements()\n except (ValueError, TypeError) as exc:\n await logger.aerror(f\"json_response.requirements_failed: {exc}\")\n return Data(data={\"content\": \"\", \"error\": str(exc)})\n\n injected_system_prompt = self._inject_dynamic_prompt_values(getattr(self, \"system_prompt\", \"\") or \"\") or \"\"\n format_instructions = getattr(self, \"format_instructions\", \"\") or \"\"\n output_schema = getattr(self, \"output_schema\", None) or []\n has_tools = bool(self.tools)\n\n async def _run_agent_for_fallback(augmented_prompt: str) -> str:\n first_attempt = True\n\n async def _run_once() -> Message:\n nonlocal first_attempt, llm_model\n if first_attempt:\n first_attempt = False\n else:\n llm_model, self.chat_history, self.tools = await self.get_agent_requirements()\n self.set(\n llm=llm_model,\n tools=self.tools or [],\n chat_history=self.chat_history,\n input_value=self.input_value,\n system_prompt=augmented_prompt,\n )\n # Structured output cannot suspend mid-parse: disable tool-approval interrupts.\n agent_runnable = self.create_agent_runnable(allow_interrupts=False)\n return await self.run_agent(agent_runnable)\n\n with _suppress_send_message(self):\n result = await self._run_agent_with_model_remediation(_run_once)\n return _extract_text_content(result)\n\n try:\n return await orchestrate_structured_output(\n llm=llm_model,\n output_schema=output_schema,\n system_prompt=injected_system_prompt,\n format_instructions=format_instructions,\n input_value=_extract_text_content(self.input_value),\n run_prompt_fallback=_run_agent_for_fallback,\n prefer_native=not has_tools,\n )\n except (\n ExceptionWithMessageError,\n ValueError,\n TypeError,\n NotImplementedError,\n AttributeError,\n ) as exc:\n await logger.aerror(f\"json_response.orchestration_failed: {exc}\")\n return Data(data={\"content\": \"\", \"error\": str(exc)})\n\n async def get_memory_data(self):\n # Scope by flow_id so default playground session names (e.g. \"New Session 0\")\n # cannot leak chat history across unrelated flows. See issue #13059.\n # The helper also returns [] when n_messages == 0, preserving the\n # explicit \"memory disabled\" contract from MemoryComponent.retrieve_messages.\n messages = await aget_agent_chat_history(\n session_id=self.graph.session_id,\n flow_id=getattr(self.graph, \"flow_id\", None),\n context_id=self.context_id,\n n_messages=self.n_messages,\n user_id=_safe_graph_user_id(self),\n )\n return [\n message for message in messages if getattr(message, \"id\", None) != getattr(self.input_value, \"id\", None)\n ]\n\n def update_input_types(self, build_config: dotdict) -> dotdict:\n \"\"\"Update input types for all fields in build_config.\"\"\"\n for key, value in build_config.items():\n if isinstance(value, dict):\n if value.get(\"input_types\") is None:\n build_config[key][\"input_types\"] = []\n elif hasattr(value, \"input_types\") and value.input_types is None:\n value.input_types = []\n return build_config\n\n async def update_build_config(\n self,\n build_config: dotdict,\n field_value: list[dict],\n field_name: str | None = None,\n ) -> dotdict:\n # Update model options with caching (for all field changes).\n # The tool-calling constraint lives on the ModelInput's ``filters``\n # field (declared above); ``handle_model_input_update`` reads it\n # and applies the filter to both the dropdown options and the\n # sticky-default re-injection path.\n build_config = handle_model_input_update(\n component=self,\n build_config=dict(build_config),\n field_value=field_value,\n field_name=field_name,\n )\n build_config = dotdict(build_config)\n\n if field_name == \"model\":\n build_config = self.update_input_types(build_config)\n\n # Validate required keys. `verbose` was dropped from the input set\n # (see `_agent_base_inputs` — the create_agent event stream already\n # surfaces every step), so it is intentionally NOT required here.\n # Saved flows that still carry a `verbose` value just ignore it on\n # load.\n default_keys = [\n \"code\",\n \"_type\",\n \"model\",\n \"tools\",\n \"input_value\",\n \"add_current_date_tool\",\n \"add_calculator_tool\",\n \"system_prompt\",\n \"max_iterations\",\n \"handle_parsing_errors\",\n ]\n missing_keys = [key for key in default_keys if key not in build_config]\n if missing_keys:\n msg = f\"Missing required keys in build_config: {missing_keys}\"\n raise ValueError(msg)\n return dotdict({k: v.to_dict() if hasattr(v, \"to_dict\") else v for k, v in build_config.items()})\n\n async def _get_tools(self) -> list[Tool]:\n component_toolkit = get_component_toolkit()\n\n tools = component_toolkit(component=self).get_tools(\n tool_name=\"Call_Agent\",\n # here we do not use the shared callbacks as we are exposing the agent as a tool\n callbacks=self.get_langchain_callbacks(),\n )\n if hasattr(self, \"tools_metadata\"):\n tools = component_toolkit(component=self, metadata=self.tools_metadata).update_tools_metadata(tools=tools)\n\n return tools\n"
+ "value": "from __future__ import annotations\n\nimport uuid\nfrom collections.abc import Mapping\nfrom contextlib import contextmanager\nfrom datetime import datetime, timezone\nfrom typing import TYPE_CHECKING, Any, cast\n\nfrom langchain.agents import create_agent\nfrom langchain.agents.middleware import (\n HumanInTheLoopMiddleware,\n ModelCallLimitMiddleware,\n ToolRetryMiddleware,\n)\nfrom langgraph.types import Command\n\nfrom lfx.components.models_and_agents.agent_helpers.graph_event_adapter import (\n adapt_graph_events_to_executor_shape,\n)\nfrom lfx.components.models_and_agents.agent_helpers.messages_input_builder import (\n build_initial_messages,\n)\nfrom lfx.components.models_and_agents.agent_helpers.placeholder_corrective_middleware import (\n WatsonXPlaceholderMiddleware,\n)\nfrom lfx.components.models_and_agents.agent_helpers.single_tool_call_middleware import (\n SingleToolCallMiddleware,\n)\nfrom lfx.components.models_and_agents.agent_helpers.tool_approval import ToolApprovalMixin\nfrom lfx.components.models_and_agents.agent_helpers.tool_call_id_middleware import ToolCallIDMiddleware\nfrom lfx.components.models_and_agents.memory import MemoryComponent, _safe_graph_user_id, aget_agent_chat_history\n\nif TYPE_CHECKING:\n from collections.abc import Awaitable, Callable\n\n from langchain_core.tools import Tool\n\n from lfx.schema.log import OnTokenFunctionType, SendMessageFunctionType\n\nfrom lfx.base.agents.agent import LCToolsAgentComponent\nfrom lfx.base.agents.callback import AgentAsyncHandler\nfrom lfx.base.agents.default_system_prompt import DEFAULT_SYSTEM_PROMPT_TEMPLATE\nfrom lfx.base.agents.events import AgentPausedError, ExceptionWithMessageError, process_agent_events\nfrom lfx.base.agents.token_callback import TokenUsageCallbackHandler\nfrom lfx.base.agents.utils import get_chat_output_sender_name\nfrom lfx.base.constants import STREAM_INFO_TEXT\nfrom lfx.base.models.unified_models import (\n get_language_model_options,\n get_llm,\n handle_model_input_update,\n)\nfrom lfx.base.models.watsonx_constants import IBM_WATSONX_URLS\nfrom lfx.components.agentics.helpers.model_config import validate_model_selection\nfrom lfx.components.helpers import CalculatorComponent, CurrentDateComponent\nfrom lfx.components.langchain_utilities.ibm_granite_handler import is_watsonx_model\nfrom lfx.components.langchain_utilities.tool_calling import ToolCallingAgentComponent\nfrom lfx.custom.custom_component.component import get_component_toolkit\nfrom lfx.field_typing.range_spec import RangeSpec\nfrom lfx.inputs.inputs import BoolInput, DropdownInput, ModelInput, StrInput\nfrom lfx.io import IntInput, MessageTextInput, MultilineInput, Output, SecretStrInput, TableInput\nfrom lfx.log.logger import logger\nfrom lfx.memory import delete_message\nfrom lfx.schema.data import Data\nfrom lfx.schema.dotdict import dotdict\nfrom lfx.schema.message import Message\nfrom lfx.schema.table import EditMode\nfrom lfx.utils.constants import MESSAGE_SENDER_AI\n\n\ndef set_advanced_true(component_input):\n component_input.advanced = True\n return component_input\n\n\ndef _agent_base_inputs():\n \"\"\"Return base inputs tailored to AgentComponent's create_agent path.\n\n `get_base_inputs()` returns a shared list — replace, don't mutate. We drop\n inputs that are no-ops here and override info text on the inputs whose\n semantics shifted under create_agent.\n\n `verbose` is dropped because the create_agent event stream already surfaces\n every agent step via the \"Agent Steps\" content blocks; the legacy boolean\n has nothing to toggle. Saved flows that still carry a `verbose` value just\n ignore it on load (the schema no longer declares it).\n \"\"\"\n drop = {\"verbose\"}\n overrides = {\n \"handle_parsing_errors\": BoolInput(\n name=\"handle_parsing_errors\",\n display_name=\"Handle Parse Errors\",\n value=True,\n advanced=True,\n info=(\n \"Adds tool-execution retry as a safety net. `create_agent` already \"\n \"feeds tool-call validation errors back to the LLM automatically; \"\n \"this flag layers `ToolRetryMiddleware` on top so transient tool \"\n \"runtime failures are retried (max 2 retries).\"\n ),\n ),\n \"max_iterations\": IntInput(\n name=\"max_iterations\",\n display_name=\"Max Iterations\",\n value=15,\n advanced=True,\n range_spec=RangeSpec(min=1, max=128000, step=1, step_type=\"int\"),\n info=(\n \"Maximum number of model calls the agent can make before stopping \"\n \"(maps to `ModelCallLimitMiddleware.run_limit` on the create_agent \"\n \"path). Must be at least 1 — it is a safety cap, never 'unlimited'.\"\n ),\n ),\n }\n return [overrides.get(inp.name, inp) for inp in LCToolsAgentComponent.get_base_inputs() if inp.name not in drop]\n\n\ndef _extract_text_content(value) -> str:\n \"\"\"Pull a string payload from a Message-like, AIMessage-like, or string value.\"\"\"\n if isinstance(value, str):\n return value\n text = getattr(value, \"text\", None)\n if isinstance(text, str):\n return text\n content = getattr(value, \"content\", None)\n if isinstance(content, str):\n return content\n return str(value) if value is not None else \"\"\n\n\n@contextmanager\ndef _suppress_send_message(component: Any):\n \"\"\"Temporarily replace component.send_message with a no-op for the duration of the block.\n\n Used during the structured-output prompt fallback: run_agent streams the agent's\n final answer through self.send_message (correct for message_response), but in\n json_response the orchestrator parses that text into structured Data which the\n downstream Chat Output emits — leaving the original emission in place produces a\n duplicate message in the playground. The original method is always restored on exit,\n even when the wrapped call raises.\n \"\"\"\n original = component.send_message\n\n async def _noop(message, *_args, **_kwargs):\n return message\n\n component.send_message = _noop\n try:\n yield\n finally:\n component.send_message = original\n\n\nclass AgentComponent(ToolApprovalMixin, ToolCallingAgentComponent):\n display_name: str = \"Agent\"\n description: str = \"Define the agent's instructions, then enter a task to complete using tools.\"\n documentation: str = \"https://docs.langflow.org/agents\"\n icon = \"bot\"\n beta = False\n name = \"Agent\"\n\n memory_inputs = [set_advanced_true(component_input) for component_input in MemoryComponent().inputs]\n\n inputs = [\n ModelInput(\n name=\"model\",\n display_name=\"Language Model\",\n info=\"Select your model provider\",\n real_time_refresh=True,\n required=True,\n # Agents require tool calling — the filter is honored by\n # ``handle_model_input_update`` so models that can't run with\n # tools never reach the picker (and any saved selection that\n # no longer satisfies the constraint is auto-replaced).\n filters={\"tool_calling\": True},\n ),\n SecretStrInput(\n name=\"api_key\",\n display_name=\"API Key\",\n info=\"Overrides global provider settings. Leave blank to use your pre-configured API Key.\",\n real_time_refresh=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"base_url_ibm_watsonx\",\n display_name=\"watsonx API Endpoint\",\n info=\"The base URL of the API (IBM watsonx.ai only)\",\n options=IBM_WATSONX_URLS,\n value=IBM_WATSONX_URLS[0],\n combobox=True,\n show=False,\n real_time_refresh=True,\n ),\n StrInput(\n name=\"project_id\",\n display_name=\"watsonx Project ID\",\n info=\"The project ID associated with the foundation model (IBM watsonx.ai only)\",\n show=False,\n required=False,\n ),\n MultilineInput(\n name=\"system_prompt\",\n display_name=\"Agent Instructions\",\n info=(\n \"System Prompt: Initial instructions and context provided to guide the agent's behavior. \"\n \"Supports dynamic placeholders: {current_date}, {model_name}, {optional_user_context}.\"\n ),\n value=DEFAULT_SYSTEM_PROMPT_TEMPLATE,\n advanced=False,\n ),\n MessageTextInput(\n name=\"context_id\",\n display_name=\"Context ID\",\n info=\"The context ID of the chat. Adds an extra layer to the local memory.\",\n value=\"\",\n advanced=True,\n ),\n IntInput(\n name=\"n_messages\",\n display_name=\"Number of Chat History Messages\",\n value=100,\n info=\"Number of chat history messages to retrieve.\",\n advanced=True,\n show=True,\n ),\n IntInput(\n name=\"max_tokens\",\n display_name=\"Max Tokens\",\n info=\"Maximum number of tokens to generate. Field name varies by provider.\",\n advanced=True,\n range_spec=RangeSpec(min=1, max=128000, step=1, step_type=\"int\"),\n ),\n MultilineInput(\n name=\"format_instructions\",\n display_name=\"Output Format Instructions\",\n info=\"Generic Template for structured output formatting. Valid only with Structured response.\",\n value=(\n \"You are an AI that extracts structured JSON objects from unstructured text. \"\n \"Use a predefined schema with expected types (str, int, float, bool, dict). \"\n \"Extract ALL relevant instances that match the schema - if multiple patterns exist, capture them all. \"\n \"Fill missing or ambiguous values with defaults: null for missing values. \"\n \"Remove exact duplicates but keep variations that have different field values. \"\n \"Always return valid JSON in the expected format, never throw errors. \"\n \"If multiple objects can be extracted, return them all in the structured format.\"\n ),\n advanced=True,\n ),\n TableInput(\n name=\"output_schema\",\n display_name=\"Output Schema\",\n info=(\n \"Schema Validation: Define the structure and data types for structured output. \"\n \"No validation if no output schema.\"\n ),\n advanced=True,\n required=False,\n value=[],\n table_schema=[\n {\n \"name\": \"name\",\n \"display_name\": \"Name\",\n \"type\": \"str\",\n \"description\": \"Specify the name of the output field.\",\n \"default\": \"field\",\n \"edit_mode\": EditMode.INLINE,\n },\n {\n \"name\": \"description\",\n \"display_name\": \"Description\",\n \"type\": \"str\",\n \"description\": \"Describe the purpose of the output field.\",\n \"default\": \"description of field\",\n \"edit_mode\": EditMode.POPOVER,\n },\n {\n \"name\": \"type\",\n \"display_name\": \"Type\",\n \"type\": \"str\",\n \"edit_mode\": EditMode.INLINE,\n \"description\": (\"Indicate the data type of the output field (e.g., str, int, float, bool, dict).\"),\n \"options\": [\"str\", \"int\", \"float\", \"bool\", \"dict\"],\n \"default\": \"str\",\n },\n {\n \"name\": \"multiple\",\n \"display_name\": \"As List\",\n \"type\": \"boolean\",\n \"description\": \"Set to True if this output field should be a list of the specified type.\",\n \"default\": \"False\",\n \"edit_mode\": EditMode.INLINE,\n },\n ],\n ),\n *_agent_base_inputs(),\n # removed memory inputs from agent component\n # *memory_inputs,\n BoolInput(\n name=\"stream\",\n display_name=\"Stream\",\n info=STREAM_INFO_TEXT,\n value=True,\n advanced=True,\n ),\n BoolInput(\n name=\"add_current_date_tool\",\n display_name=\"Current Date\",\n advanced=True,\n info=\"If true, will add a tool to the agent that returns the current date.\",\n value=True,\n ),\n BoolInput(\n name=\"add_calculator_tool\",\n display_name=\"Calculator\",\n advanced=True,\n info=(\n \"If true, adds a zero-config arithmetic calculator tool to the agent \"\n \"(safe: only +, -, *, /, ** operators via AST).\"\n ),\n value=True,\n ),\n ]\n outputs = [\n Output(name=\"response\", display_name=\"Response\", method=\"message_response\"),\n Output(\n name=\"structured_response\",\n display_name=\"Structured Response\",\n method=\"json_response\",\n types=[\"Data\"],\n ),\n ]\n\n async def _additional_model_provider_policy_ids(self, purpose, parameters=None) -> tuple[str, ...]:\n \"\"\"Gate the provider selector retained by legacy Agent/ALTK flows.\"\"\"\n _ = purpose\n from lfx.base.models.provider_registry import resolve_provider_id\n\n effective_parameters = parameters if isinstance(parameters, Mapping) else getattr(self, \"_parameters\", None)\n if not isinstance(effective_parameters, Mapping):\n effective_parameters = {}\n selected_model = effective_parameters.get(\"model\", getattr(self, \"model\", None))\n if selected_model:\n # The shared Component hook already handles a selected ModelInput;\n # connected model objects are gated by their upstream vertex.\n return ()\n legacy_provider = effective_parameters.get(\"agent_llm\", getattr(self, \"agent_llm\", None))\n if not isinstance(legacy_provider, str) or not legacy_provider.strip() or legacy_provider == \"Custom\":\n return ()\n return (resolve_provider_id(legacy_provider),)\n\n async def _filter_legacy_provider_options(self, build_config: Mapping[str, Any]) -> None:\n \"\"\"Filter ALTK/legacy Agent provider choices through the active scope.\"\"\"\n from lfx.services.model_provider_policy import ModelProviderPolicyPurpose, aresolve_model_provider_policy\n\n provider_field = build_config.get(\"agent_llm\")\n if not isinstance(provider_field, dict):\n return\n options = provider_field.get(\"options\")\n if not isinstance(options, list):\n return\n candidates = [option for option in options if isinstance(option, str) and option != \"Custom\"]\n if not candidates:\n return\n snapshot = await aresolve_model_provider_policy(\n user_id=self.user_id,\n providers=candidates,\n purpose=ModelProviderPolicyPurpose.CONFIGURE,\n )\n allowed = set(snapshot.filter(candidates))\n keep_indexes = [index for index, option in enumerate(options) if option == \"Custom\" or option in allowed]\n provider_field[\"options\"] = [options[index] for index in keep_indexes]\n metadata = provider_field.get(\"options_metadata\")\n if isinstance(metadata, list) and len(metadata) == len(options):\n provider_field[\"options_metadata\"] = [metadata[index] for index in keep_indexes]\n\n def _resolve_selected_model(self):\n \"\"\"Resolve the selected model, including legacy agent_llm/model_name inputs.\"\"\"\n try:\n from langchain_core.language_models import BaseLanguageModel\n\n if isinstance(self.model, BaseLanguageModel):\n return self.model\n except ImportError:\n pass\n\n if isinstance(self.model, list) and self.model:\n return self.model\n\n legacy_provider = getattr(self, \"agent_llm\", None)\n legacy_model_name = getattr(self, \"model_name\", None)\n if not legacy_provider or not legacy_model_name:\n return self.model\n\n options = get_language_model_options(user_id=self.user_id)\n for option in options:\n if option.get(\"provider\") == legacy_provider and option.get(\"name\") == legacy_model_name:\n return [option]\n\n return [\n {\n \"name\": legacy_model_name,\n \"provider\": legacy_provider,\n \"metadata\": {},\n }\n ]\n\n def _get_max_tokens_value(self):\n \"\"\"Return the user-supplied max_tokens or None when unset/zero.\"\"\"\n val = getattr(self, \"max_tokens\", None)\n if val in {\"\", 0}:\n return None\n return val\n\n def _get_llm(self):\n \"\"\"Override parent to include max_tokens from the Agent's input field.\n\n Streaming is mandatory for AgentComponent: ``runnable.astream_events(v2)`` only\n emits ``on_chat_model_stream`` chunks when the underlying chat model is\n instantiated with ``streaming=True``. Unlike the LanguageModel component (where\n ``stream`` is a user-facing toggle), the Agent has no opt-out — the toggle is\n kept in the UI for backwards compatibility but is intentionally ignored here.\n Without ``stream=True``, the chat model accumulates the whole response and\n only emits ``on_chat_model_end``, silently disabling the Playground's live-\n typing view and breaking the streaming contract on the /events surface.\n \"\"\"\n return get_llm(\n model=self.model,\n user_id=self.user_id,\n api_key=getattr(self, \"api_key\", None),\n stream=True,\n max_tokens=self._get_max_tokens_value(),\n watsonx_url=getattr(self, \"base_url_ibm_watsonx\", None),\n watsonx_project_id=getattr(self, \"project_id\", None),\n overrides=getattr(self, \"_model_overrides\", None),\n )\n\n async def get_agent_requirements(self):\n \"\"\"Get the agent requirements for the agent.\"\"\"\n from langchain_core.tools import StructuredTool\n\n from lfx.services.model_provider_policy import ModelProviderPolicyPurpose\n\n await self.arequire_model_provider_policy(ModelProviderPolicyPurpose.USE)\n\n selected_model = self._resolve_selected_model()\n try:\n from langchain_core.language_models import BaseLanguageModel\n\n is_connected_model = isinstance(selected_model, BaseLanguageModel)\n except ImportError:\n is_connected_model = False\n\n if not is_connected_model:\n validate_model_selection(selected_model)\n\n # Ensure _get_llm() uses the resolved model (e.g. from legacy agent_llm/model_name)\n self.model = selected_model\n llm_model = self._get_llm()\n if llm_model is None:\n msg = \"No language model selected. Please choose a model to proceed.\"\n raise ValueError(msg)\n\n # Get memory data\n self.chat_history = await self.get_memory_data()\n await logger.adebug(f\"Retrieved {len(self.chat_history)} chat history messages\")\n if isinstance(self.chat_history, Message):\n self.chat_history = [self.chat_history]\n\n # Add current date tool if enabled\n if self.add_current_date_tool:\n if not isinstance(self.tools, list): # type: ignore[has-type]\n self.tools = []\n current_date_tool = (await CurrentDateComponent(**self.get_base_args()).to_toolkit()).pop(0)\n\n if not isinstance(current_date_tool, StructuredTool):\n msg = \"CurrentDateComponent must be converted to a StructuredTool\"\n raise TypeError(msg)\n # Skip if an externally-connected tool already provides the same name.\n # Duplicate tool names are rejected by Anthropic/Gemini with HTTP 400.\n if not any(getattr(t, \"name\", None) == current_date_tool.name for t in self.tools):\n self.tools.append(current_date_tool)\n\n # Add calculator tool if enabled (zero-config arithmetic)\n if getattr(self, \"add_calculator_tool\", False):\n if not isinstance(self.tools, list): # type: ignore[has-type]\n self.tools = []\n calculator_tool = (await CalculatorComponent(**self.get_base_args()).to_toolkit()).pop(0)\n\n if not isinstance(calculator_tool, StructuredTool):\n msg = \"CalculatorComponent must be converted to a StructuredTool\"\n raise TypeError(msg)\n # Skip if an externally-connected tool already provides the same name.\n # Duplicate tool names are rejected by Anthropic/Gemini with HTTP 400.\n if not any(getattr(t, \"name\", None) == calculator_tool.name for t in self.tools):\n self.tools.append(calculator_tool)\n\n # Set shared callbacks for tracing the tools used by the agent\n self.set_tools_callbacks(self.tools, self._get_shared_callbacks())\n\n return llm_model, self.chat_history, self.tools\n\n def _get_resolved_model_name(self) -> str:\n \"\"\"Best-effort human-readable model name for {model_name} injection.\"\"\"\n try:\n from langchain_core.language_models import BaseLanguageModel\n\n if isinstance(self.model, BaseLanguageModel):\n return type(self.model).__name__\n except ImportError:\n pass\n\n if isinstance(self.model, list) and self.model:\n first = self.model[0]\n if isinstance(first, dict):\n name = first.get(\"name\")\n if isinstance(name, str) and name:\n return name\n\n legacy_model_name = getattr(self, \"model_name\", None)\n if isinstance(legacy_model_name, str) and legacy_model_name:\n return legacy_model_name\n return \"\"\n\n def _inject_dynamic_prompt_values(self, prompt: Any | None) -> str | None:\n \"\"\"Replace known env placeholders in the system prompt.\n\n Handles {current_date}, {model_name}, and {optional_user_context} (the\n last one ships with the structured DEFAULT_SYSTEM_PROMPT_TEMPLATE and\n is currently unused at the AgentComponent layer, so it resolves to \"\").\n Uses str.replace (not str.format) so user prompts containing literal\n braces such as JSON examples ({\"key\": 1}) never break the agent.\n\n `system_prompt` is a connectable MultilineInput, so the value can arrive\n as a Message (e.g. a Prompt node wired in). Normalize it to text first —\n a raw Message has no `.replace` and used to crash the agent build.\n \"\"\"\n if prompt is None:\n return None\n prompt = _extract_text_content(prompt)\n if not prompt:\n return prompt\n replacements = {\n \"{current_date}\": datetime.now(tz=timezone.utc).strftime(\"%Y-%m-%d %H:%M:%S UTC\"),\n \"{model_name}\": self._get_resolved_model_name(),\n \"{optional_user_context}\": \"\",\n }\n for placeholder, value in replacements.items():\n prompt = prompt.replace(placeholder, value)\n return prompt\n\n def create_agent_runnable(self, *, allow_interrupts: bool = True):\n \"\"\"Build the LangGraph `CompiledStateGraph` via `langchain.agents.create_agent`.\n\n Replaces the legacy `AgentExecutor` runnable inherited from\n `ToolCallingAgentComponent`. Other agent components (tool_calling, csv, json,\n openapi, sql*, vector_store_router) keep the legacy path — only AgentComponent\n runs on the new graph API.\n\n `max_iterations` and `handle_parsing_errors` (legacy AgentExecutor knobs) are\n translated to LangGraph middleware. Without that translation those user inputs\n would silently become no-ops on the new API.\n\n Provider notes:\n - WatsonX/Granite work natively with create_agent — `ChatWatsonx.bind_tools`\n handles tool_choice correctly. The legacy `create_granite_agent` path was\n dropped because it hardcoded `tool_choice='required'`, which the WatsonX\n API now rejects.\n - Ollama and other small/local models often emit malformed tool args. The\n ToolRetryMiddleware (default `retry_on=(Exception,)`, `on_failure='continue'`)\n catches Pydantic ValidationErrors from bad args and feeds the error back\n to the LLM as a retry signal, so the agent recovers gracefully.\n \"\"\"\n llm = self._get_llm()\n tools = self.tools or []\n\n # Eager bind_tools validation. `create_agent(...)` is lazy — without this,\n # an LLM that doesn't support tool calling fails on the first user message\n # instead of when the user wires up the component, which is a much worse UX.\n # Gated on a non-empty tools list so a no-tool Agent on a plain chat model\n # (which legitimately has no `bind_tools`) isn't shut out at flow-build time.\n # Providers signal \"no tool calling\" inconsistently — `NotImplementedError`\n # (langchain default), `AttributeError` (no `bind_tools` attr), or `TypeError`\n # (signature mismatch). Treat all three as the same UX failure.\n if tools:\n try:\n llm.bind_tools(tools)\n except (NotImplementedError, AttributeError, TypeError) as exc:\n # Include the underlying error so a broken tool schema or a\n # provider implementation bug is not silently disguised as a\n # \"model can't call tools\" UX error.\n msg = (\n f\"{self.display_name} does not support tool calling, \"\n \"or one of the connected tools failed to bind. \"\n \"Please connect a tool-calling capable language model and \"\n f\"verify your tools are well-formed. Underlying error: {exc!s}\"\n )\n raise NotImplementedError(msg) from exc\n\n middleware = self._build_middleware(llm, allow_interrupts=allow_interrupts)\n checkpointer = self._build_agent_checkpointer() if allow_interrupts else None\n return create_agent(\n model=llm,\n tools=tools,\n system_prompt=self.system_prompt or \"\",\n middleware=middleware or None,\n checkpointer=checkpointer,\n )\n\n def _compute_recursion_limit(self) -> int:\n \"\"\"Derive the LangGraph recursion_limit from the user-set max_iterations.\n\n Mirrors the clamp in `_build_middleware` (max(1, max_iterations)) so a\n saved 0 or negative value cannot under-cap the graph below one full\n iteration. The +5 buffer covers start/end/router overhead.\n \"\"\"\n raw = getattr(self, \"max_iterations\", None)\n run_limit = max(1, int(raw)) if raw is not None else 15\n return run_limit * 2 + 5\n\n def _build_middleware(self, llm: Any, *, allow_interrupts: bool = True) -> list:\n # `llm` is passed in (rather than re-fetched via `self._get_llm()`)\n # because some providers do credential resolution / client instantiation\n # lazily on each call. The caller — `create_agent_runnable` — already\n # resolved it once for `bind_tools`, so reuse that instance here.\n middleware: list = []\n # LangChain accepts missing IDs on AIMessage.tool_calls, but LangGraph's\n # invalid-call path and ToolRetryMiddleware both require a string when\n # they construct an error ToolMessage. Normalize at the model boundary\n # so either recovery path can return the error to the model instead of\n # crashing the flow.\n if self.tools:\n middleware.append(ToolCallIDMiddleware())\n max_iterations = getattr(self, \"max_iterations\", None)\n if max_iterations is not None:\n # `max_iterations` is a safety cap, not an \"unlimited\" toggle. A saved\n # 0 or negative value (falsy) must NOT silently drop the limiter and\n # allow an unbounded model/tool loop — clamp it to a real minimum.\n run_limit = max(1, int(max_iterations))\n middleware.append(ModelCallLimitMiddleware(run_limit=run_limit))\n # ToolRetryMiddleware only matters when there ARE tools to retry. Attaching\n # it on a no-tools agent inflates the compiled graph and adds per-invocation\n # middleware overhead for nothing, which is a measurable contributor to\n # trivial-prompt latency (QA UI-003).\n if getattr(self, \"handle_parsing_errors\", False) and self.tools:\n middleware.append(ToolRetryMiddleware(max_retries=2))\n # WatsonX models have two known platform quirks; both still reproduce on\n # the current API, so we keep the protections from the legacy\n # `create_granite_agent` path.\n # 1. Multi-tool-call assistant turns are rejected (\"This model only\n # supports single tool-calls at once!\"). Clamp to one per turn.\n # 2. Tool args occasionally come back as literal placeholder strings\n # (e.g. `<result-from-search>`). Re-invoke once with a corrective\n # SystemMessage.\n # Order: SingleToolCallMiddleware first (outermost) so the clamp is\n # applied to the final response, including any corrective re-invoke\n # produced by WatsonXPlaceholderMiddleware.\n if is_watsonx_model(llm):\n middleware.append(SingleToolCallMiddleware())\n middleware.append(WatsonXPlaceholderMiddleware())\n # Human-in-the-loop: attach only when a tool is gated AND interrupts are allowed\n # (the structured-output path disables them), keeping ungated flows unchanged.\n interrupt_on = self._gated_interrupt_on() if allow_interrupts else {}\n if interrupt_on:\n middleware.append(HumanInTheLoopMiddleware(interrupt_on=interrupt_on))\n return middleware\n\n async def run_agent(self, agent) -> Message:\n \"\"\"Run the LangGraph `CompiledStateGraph` and return the final agent Message.\n\n Overrides the legacy `LCAgentComponent.run_agent` (which builds an\n `{\"input\": str, \"chat_history\": [...]}` dict for `AgentExecutor`). The graph\n wants `{\"messages\": [BaseMessage, ...]}`. The event stream is wrapped with\n `adapt_graph_events_to_executor_shape` so the legacy `process_agent_events`\n (in `lfx.base.agents.events`) can be reused unchanged.\n \"\"\"\n messages = build_initial_messages(\n input_value=self.input_value,\n chat_history=getattr(self, \"chat_history\", None),\n )\n input_dict = {\"messages\": messages}\n\n agent_message = self._build_initial_agent_message()\n token_usage_handler = TokenUsageCallbackHandler()\n\n # Stream tokens to the event manager when running inside the Langflow runtime.\n # This is what powers the live-typing view in the chat UI.\n on_token_callback: OnTokenFunctionType | None = None\n if getattr(self, \"_event_manager\", None):\n on_token_callback = cast(\"OnTokenFunctionType\", self._event_manager.on_token)\n\n # Align LangGraph's `recursion_limit` with `max_iterations` so the\n # middleware cap (ModelCallLimitMiddleware) is what bounds the loop —\n # not LangGraph's default 25-step guard, which fires at ~12 model+tool\n # iterations and raises a raw GraphRecursionError (QA UI-009/UI-010).\n # Each iteration is ~2 graph steps (model node + tools node); add 5\n # for start/end overhead.\n recursion_limit = self._compute_recursion_limit()\n\n agent_config: dict[str, Any] = {\n \"callbacks\": [\n AgentAsyncHandler(self.log),\n token_usage_handler,\n *self._get_shared_callbacks(),\n ],\n \"recursion_limit\": recursion_limit,\n }\n # The durable checkpointer keys on the per-run thread_id; it must be in the\n # astream_events config (not just create_agent) for both initial run and resume.\n thread_id = self._agent_thread_id()\n get_pending_interrupt = None\n stream_input: Any = input_dict\n # A checkpointer is only present when the agent was built with interrupts enabled\n # (the structured-output path builds without one); never probe its state otherwise.\n interrupts_enabled = getattr(agent, \"checkpointer\", None) is not None\n if interrupts_enabled and thread_id and self._gated_interrupt_on():\n agent_config[\"configurable\"] = {\"thread_id\": thread_id}\n get_pending_interrupt = self._pending_interrupt_getter(agent, agent_config)\n if self._has_candidate_decision(thread_id):\n # The injected decision must match the pending interrupt's nonce, so read\n # the interrupt first; a matched decision resumes the checkpointed thread.\n value, interrupt_id = await self._read_pending_interrupt(agent, agent_config)\n decision = self._injected_agent_decision(thread_id, interrupt_id)\n if decision is not None:\n action_requests = (value or {}).get(\"action_requests\") or []\n stream_input = Command(\n resume={\"decisions\": self._build_resume_decisions(decision, action_requests)}\n )\n stream = adapt_graph_events_to_executor_shape(\n agent.astream_events(stream_input, config=agent_config, version=\"v2\")\n )\n try:\n result = await process_agent_events(\n stream,\n agent_message,\n cast(\"SendMessageFunctionType\", self.send_message),\n on_token_callback,\n get_pending_interrupt=get_pending_interrupt,\n )\n except AgentPausedError as e:\n # Why: retract the empty partial bubble (leaks as \"[]\"); the HITL card supersedes it, resume re-emits it.\n paused_message = e.agent_message or agent_message\n msg_id = paused_message.get_id()\n if msg_id:\n await delete_message(id_=msg_id)\n await self._send_message_event(paused_message, category=\"remove_message\")\n return self._suspend_for_tool_approval(e.request, paused_message)\n except ExceptionWithMessageError as e:\n # Drop the half-stored partial message from the DB (only if it was\n # actually persisted) and tell the frontend to remove the stale bubble.\n if hasattr(e, \"agent_message\"):\n msg_id = e.agent_message.get_id()\n if msg_id:\n await delete_message(id_=msg_id)\n await self._send_message_event(e.agent_message, category=\"remove_message\")\n # exception(), not error(f\"...{e}\"): this class's str() interpolates the model's\n # partial completion, and passing the exception rather than formatting it is what\n # gives the exported record an error.type to triage on.\n logger.exception(\"Agent run failed after a partial message was emitted\")\n raise\n\n usage_data = token_usage_handler.get_usage()\n if usage_data:\n self._token_usage = usage_data\n result.properties.usage = usage_data\n # Only round-trip the DB when the message was stored (Chat Output wired).\n # `_should_skip_message=True` leaves `result.get_id()` empty; persisting\n # then would create a phantom row.\n if result.get_id():\n stored_result = await self._update_stored_message(result)\n await self._send_message_event(stored_result)\n result = stored_result\n\n self.status = result\n return result\n\n def _build_initial_agent_message(self) -> Message:\n \"\"\"Construct the placeholder agent Message that `process_agent_events` mutates.\"\"\"\n if hasattr(self, \"graph\"):\n session_id = self.graph.session_id\n elif hasattr(self, \"_session_id\"):\n session_id = self._session_id\n else:\n session_id = None\n\n sender_name = get_chat_output_sender_name(self) or self.display_name or \"AI\"\n return Message(\n sender=MESSAGE_SENDER_AI,\n sender_name=sender_name,\n properties={\"icon\": \"Bot\", \"state\": \"partial\"},\n # `text=\"\"` sentinel so MessageTable's no_content check accepts\n # an in-flight agent message whose content_blocks haven't been\n # populated yet. Mirrors ChatInput's convention.\n text=\"\",\n # Flat chronological event log; see lfx.base.agents.events.\n content_blocks=[],\n session_id=session_id or uuid.uuid4(),\n )\n\n def _selected_model_remediation_context(self) -> tuple[str | None, str | None, Any | None]:\n \"\"\"Return provider/name plus a connected model target, when present.\"\"\"\n try:\n selected = self._resolve_selected_model()\n if isinstance(selected, list) and selected and isinstance(selected[0], dict):\n return selected[0].get(\"provider\"), selected[0].get(\"name\"), None\n\n from langchain_core.language_models import BaseLanguageModel\n\n if isinstance(selected, BaseLanguageModel):\n model_name = None\n for attr in (\"model_name\", \"model\", \"model_id\"):\n value = getattr(selected, attr, None)\n if isinstance(value, str) and value:\n model_name = value\n break\n return self._connected_model_provider(selected), model_name, selected\n except (AttributeError, TypeError, ValueError, KeyError, ImportError):\n pass\n return None, None, None\n\n def _connected_model_provider(self, model: Any) -> str | None:\n \"\"\"Resolve a connected model's provider from the source component.\n\n Runtime model classes are not provider identities: OpenAI, OpenRouter,\n and compatible endpoints can all produce ``ChatOpenAI``. The incoming\n model edge preserves the source component, so prefer its explicit\n provider override or selected-model metadata, then its provider display\n name. If the Agent is used without graph provenance, leave the provider\n unknown so provider-scoped remediations remain disabled.\n \"\"\"\n vertex = getattr(self, \"_vertex\", None)\n if vertex is None:\n return None\n source_id = vertex.get_incoming_edge_by_target_param(\"model\")\n if not source_id:\n return None\n source = vertex.graph.get_vertex(source_id)\n component = getattr(source, \"custom_component\", None)\n if component is None:\n return None\n\n candidate = getattr(component, \"provider\", None)\n\n if not isinstance(candidate, str) or not candidate:\n selected_model = getattr(component, \"model\", None)\n if isinstance(selected_model, list) and selected_model and isinstance(selected_model[0], dict):\n candidate = selected_model[0].get(\"provider\")\n\n if not isinstance(candidate, str) or not candidate:\n candidate = getattr(component, \"display_name\", None)\n if not isinstance(candidate, str) or not candidate:\n return None\n\n from lfx.base.models.unified_models.provider_queries import get_model_provider_metadata\n\n provider_metadata = get_model_provider_metadata().get(candidate, {})\n expected_class = provider_metadata.get(\"mapping\", {}).get(\"model_class\")\n model_classes = {base.__name__ for base in type(model).__mro__}\n return candidate if expected_class in model_classes else None\n\n async def _run_agent_with_model_remediation(\n self,\n run_once: Callable[[], Awaitable[Message]],\n ) -> Message:\n \"\"\"Run one Agent operation, retrying safe provider-validation failures.\n\n Registered remediations must identify request-validation failures that\n occur before tool execution. A failure that can happen after a tool runs\n must instead retry at the model-call boundary to avoid repeating tool\n side effects.\n \"\"\"\n from lfx.base.models.model_remediation import apply_overrides_to_model, find_remediation, remember\n\n provider, model_name, connected_model = self._selected_model_remediation_context()\n applied: set[str] = set()\n while True:\n try:\n result = await run_once()\n except (ValueError, TypeError, KeyError):\n await logger.aexception(\"Agent run failed\")\n raise\n except Exception as exc:\n # run_agent may wrap the provider error in ExceptionWithMessageError, whose\n # str() carries the model's partial completion. Matching on it locally is fine;\n # logging it is not, so the record below passes the exception instead.\n error_text = f\"{exc} {getattr(exc, '__cause__', '') or ''}\"\n remediation = find_remediation(error_text, provider, already_applied=applied)\n if remediation is None:\n await logger.aexception(\"Agent run failed with no remediation available\")\n raise\n if connected_model is not None and not apply_overrides_to_model(connected_model, remediation.overrides):\n await logger.aerror(\n f\"model.remediation.unapplied name={remediation.name} provider={provider} model={model_name}\"\n )\n raise\n applied.add(remediation.name)\n if connected_model is None:\n self._model_overrides = {\n **(getattr(self, \"_model_overrides\", None) or {}),\n **remediation.overrides,\n }\n else:\n # Connected outputs are shared objects across downstream flow\n # branches. The mutation is intentionally flow-scoped: sibling\n # branches holding this model will see the matched override too.\n await logger.adebug(\n f\"model.remediation.shared_model name={remediation.name} provider={provider} model={model_name}\"\n )\n await logger.awarning(\n f\"model.remediation.applied name={remediation.name} provider={provider} model={model_name}\"\n )\n else:\n if connected_model is None and getattr(self, \"_model_overrides\", None):\n remember(provider, model_name, self._model_overrides)\n return result\n\n async def message_response(self) -> Message:\n async def _run_once() -> Message:\n llm_model, self.chat_history, self.tools = await self.get_agent_requirements()\n self.set(\n llm=llm_model,\n tools=self.tools or [],\n chat_history=self.chat_history,\n input_value=self.input_value,\n system_prompt=self._inject_dynamic_prompt_values(self.system_prompt),\n )\n agent = self.create_agent_runnable()\n return await self.run_agent(agent)\n\n result = await self._run_agent_with_model_remediation(_run_once)\n self._agent_result = result\n return result\n\n async def json_response(self) -> Data:\n \"\"\"Produce structured Data via native LLM structured output, with prompt-based fallback.\n\n Native path (no tools, llm has with_structured_output) bypasses the agent loop and\n returns provider-validated JSON. When tools are attached, falls back to running the\n agent with a schema-augmented system prompt and parsing the final message content.\n \"\"\"\n from lfx.components.models_and_agents.structured_output.structured_output_orchestrator import (\n orchestrate_structured_output,\n )\n\n try:\n llm_model, self.chat_history, self.tools = await self.get_agent_requirements()\n except (ValueError, TypeError) as exc:\n await logger.aexception(\"json_response.requirements_failed\")\n return Data(data={\"content\": \"\", \"error\": str(exc)})\n\n injected_system_prompt = self._inject_dynamic_prompt_values(getattr(self, \"system_prompt\", \"\") or \"\") or \"\"\n format_instructions = getattr(self, \"format_instructions\", \"\") or \"\"\n output_schema = getattr(self, \"output_schema\", None) or []\n has_tools = bool(self.tools)\n\n async def _run_agent_for_fallback(augmented_prompt: str) -> str:\n first_attempt = True\n\n async def _run_once() -> Message:\n nonlocal first_attempt, llm_model\n if first_attempt:\n first_attempt = False\n else:\n llm_model, self.chat_history, self.tools = await self.get_agent_requirements()\n self.set(\n llm=llm_model,\n tools=self.tools or [],\n chat_history=self.chat_history,\n input_value=self.input_value,\n system_prompt=augmented_prompt,\n )\n # Structured output cannot suspend mid-parse: disable tool-approval interrupts.\n agent_runnable = self.create_agent_runnable(allow_interrupts=False)\n return await self.run_agent(agent_runnable)\n\n with _suppress_send_message(self):\n result = await self._run_agent_with_model_remediation(_run_once)\n return _extract_text_content(result)\n\n try:\n return await orchestrate_structured_output(\n llm=llm_model,\n output_schema=output_schema,\n system_prompt=injected_system_prompt,\n format_instructions=format_instructions,\n input_value=_extract_text_content(self.input_value),\n run_prompt_fallback=_run_agent_for_fallback,\n prefer_native=not has_tools,\n )\n except (\n ExceptionWithMessageError,\n ValueError,\n TypeError,\n NotImplementedError,\n AttributeError,\n ) as exc:\n await logger.aexception(\"json_response.orchestration_failed\")\n return Data(data={\"content\": \"\", \"error\": str(exc)})\n\n async def get_memory_data(self):\n # Scope by flow_id so default playground session names (e.g. \"New Session 0\")\n # cannot leak chat history across unrelated flows. See issue #13059.\n # The helper also returns [] when n_messages == 0, preserving the\n # explicit \"memory disabled\" contract from MemoryComponent.retrieve_messages.\n messages = await aget_agent_chat_history(\n session_id=self.graph.session_id,\n flow_id=getattr(self.graph, \"flow_id\", None),\n context_id=self.context_id,\n n_messages=self.n_messages,\n user_id=_safe_graph_user_id(self),\n )\n return [\n message for message in messages if getattr(message, \"id\", None) != getattr(self.input_value, \"id\", None)\n ]\n\n def update_input_types(self, build_config: dotdict) -> dotdict:\n \"\"\"Update input types for all fields in build_config.\"\"\"\n for key, value in build_config.items():\n if isinstance(value, dict):\n if value.get(\"input_types\") is None:\n build_config[key][\"input_types\"] = []\n elif hasattr(value, \"input_types\") and value.input_types is None:\n value.input_types = []\n return build_config\n\n async def update_build_config(\n self,\n build_config: dotdict,\n field_value: list[dict],\n field_name: str | None = None,\n ) -> dotdict:\n from lfx.services.model_provider_policy import ModelProviderPolicyPurpose\n\n policy_parameters = dict(getattr(self, \"_parameters\", {}) or {})\n if field_name:\n policy_parameters[field_name] = field_value\n await self.arequire_model_provider_policy(\n ModelProviderPolicyPurpose.CONFIGURE,\n parameters=policy_parameters,\n )\n # Update model options with caching (for all field changes).\n # The tool-calling constraint lives on the ModelInput's ``filters``\n # field (declared above); ``handle_model_input_update`` reads it\n # and applies the filter to both the dropdown options and the\n # sticky-default re-injection path.\n build_config = handle_model_input_update(\n component=self,\n build_config=dict(build_config),\n field_value=field_value,\n field_name=field_name,\n )\n build_config = dotdict(build_config)\n\n if field_name == \"model\":\n build_config = self.update_input_types(build_config)\n\n # Validate required keys. `verbose` was dropped from the input set\n # (see `_agent_base_inputs` — the create_agent event stream already\n # surfaces every step), so it is intentionally NOT required here.\n # Saved flows that still carry a `verbose` value just ignore it on\n # load.\n default_keys = [\n \"code\",\n \"_type\",\n \"model\",\n \"tools\",\n \"input_value\",\n \"add_current_date_tool\",\n \"add_calculator_tool\",\n \"system_prompt\",\n \"max_iterations\",\n \"handle_parsing_errors\",\n ]\n missing_keys = [key for key in default_keys if key not in build_config]\n if missing_keys:\n msg = f\"Missing required keys in build_config: {missing_keys}\"\n raise ValueError(msg)\n await self._filter_legacy_provider_options(build_config)\n return dotdict({k: v.to_dict() if hasattr(v, \"to_dict\") else v for k, v in build_config.items()})\n\n async def _get_tools(self) -> list[Tool]:\n component_toolkit = get_component_toolkit()\n\n tools = component_toolkit(component=self).get_tools(\n tool_name=\"Call_Agent\",\n # here we do not use the shared callbacks as we are exposing the agent as a tool\n callbacks=self.get_langchain_callbacks(),\n )\n if hasattr(self, \"tools_metadata\"):\n tools = component_toolkit(component=self, metadata=self.tools_metadata).update_tools_metadata(tools=tools)\n\n return tools\n"
},
"context_id": {
"_input_type": "MessageTextInput",
@@ -1228,7 +1215,6 @@
"display_name": "Handle Parse Errors",
"dynamic": false,
"info": "Adds tool-execution retry as a safety net. `create_agent` already feeds tool-call validation errors back to the LLM automatically; this flag layers `ToolRetryMiddleware` on top so transient tool runtime failures are retried (max 2 retries).",
- "input_types": [],
"list": false,
"list_add_label": "Add More",
"name": "handle_parsing_errors",
@@ -1269,7 +1255,6 @@
"type": "str",
"value": ""
},
- "is_refresh": true,
"max_iterations": {
"_input_type": "IntInput",
"advanced": true,
@@ -1277,7 +1262,6 @@
"display_name": "Max Iterations",
"dynamic": false,
"info": "Maximum number of model calls the agent can make before stopping (maps to `ModelCallLimitMiddleware.run_limit` on the create_agent path). Must be at least 1 — it is a safety cap, never 'unlimited'.",
- "input_types": [],
"list": false,
"list_add_label": "Add More",
"name": "max_iterations",
@@ -1305,7 +1289,6 @@
"display_name": "Max Tokens",
"dynamic": false,
"info": "Maximum number of tokens to generate. Field name varies by provider.",
- "input_types": [],
"list": false,
"list_add_label": "Add More",
"load_from_db": false,
@@ -1356,26 +1339,6 @@
"load_from_db": false,
"model_type": "language",
"name": "model",
- "options": [
- {
- "category": "Anthropic",
- "icon": "Anthropic",
- "metadata": {
- "api_key_param": "api_key",
- "context_length": 128000,
- "max_tokens_field_name": "max_tokens",
- "model_class": "ChatAnthropic",
- "model_name_param": "model",
- "not_enabled_locally": true,
- "reasoning": true,
- "reasoning_models": [
- "claude-opus-5"
- ]
- },
- "name": "claude-opus-5",
- "provider": "Anthropic"
- }
- ],
"override_skip": false,
"placeholder": "Setup Provider",
"real_time_refresh": true,
@@ -1414,7 +1377,6 @@
"display_name": "Number of Chat History Messages",
"dynamic": false,
"info": "Number of chat history messages to retrieve.",
- "input_types": [],
"list": false,
"list_add_label": "Add More",
"name": "n_messages",
@@ -1505,7 +1467,6 @@
"display_name": "watsonx Project ID",
"dynamic": false,
"info": "The project ID associated with the foundation model (IBM watsonx.ai only)",
- "input_types": [],
"list": false,
"list_add_label": "Add More",
"load_from_db": true,
@@ -1528,7 +1489,6 @@
"display_name": "Stream",
"dynamic": false,
"info": "Stream the response from the model. Streaming works only in Chat.",
- "input_types": [],
"list": false,
"list_add_label": "Add More",
"name": "stream",
@@ -1637,7 +1597,7 @@
],
"frozen": false,
"icon": "calculator",
- "last_updated": "2026-09-01T13:59:10.221Z",
+ "last_updated": "2026-09-08T21:06:51.862Z",
"legacy": false,
"metadata": {
"code_hash": "d0b2936e74fa",
@@ -1658,7 +1618,7 @@
{
"allows_loop": false,
"cache": true,
- "display_name": "JSON",
+ "display_name": "Toolset",
"group_outputs": false,
"hidden": null,
"loop_types": null,
@@ -1680,7 +1640,7 @@
"value": "1098eea1-6649-4e1d-aed1-b77249fb8dd0"
},
"_frontend_node_folder_id": {
- "value": "fbc33683-53fb-4a7b-b1c8-505dcae74674"
+ "value": "7ff6c353-e65b-4821-9940-b18a52bf532b"
},
"_type": "Component",
"code": {
@@ -1819,12 +1779,12 @@
"icon": "prompts",
"legacy": false,
"metadata": {
- "code_hash": "3d3fd7b8a36f",
+ "code_hash": "e3714ffe5d15",
"dependencies": {
"dependencies": [
{
"name": "lfx",
- "version": "0.4.0"
+ "version": "1.12.0"
}
],
"total_dependencies": 1
@@ -1858,6 +1818,7 @@
"_type": "Component",
"code": {
"advanced": true,
+ "api_editable": false,
"dynamic": true,
"fileTypes": [],
"file_path": "",
@@ -1872,10 +1833,11 @@
"show": true,
"title_case": false,
"type": "code",
- "value": "from typing import Any\n\nfrom lfx.base.prompts.api_utils import process_prompt_template\nfrom lfx.custom.custom_component.component import Component\nfrom lfx.inputs.input_mixin import FieldTypes\nfrom lfx.inputs.inputs import DefaultPromptField\nfrom lfx.io import BoolInput, MessageTextInput, Output, PromptInput\nfrom lfx.log.logger import logger\nfrom lfx.schema.dotdict import dotdict\nfrom lfx.schema.message import Message\nfrom lfx.template.utils import update_template_values\nfrom lfx.utils.mustache_security import validate_mustache_template\n\n\nclass PromptComponent(Component):\n display_name: str = \"Prompt Template\"\n description: str = \"Create a prompt template with dynamic variables.\"\n documentation: str = \"https://docs.langflow.org/components-prompts\"\n icon = \"prompts\"\n trace_type = \"prompt\"\n name = \"Prompt Template\"\n\n inputs = [\n PromptInput(name=\"template\", display_name=\"Template\"),\n BoolInput(\n name=\"use_double_brackets\",\n display_name=\"Use Double Brackets\",\n value=False,\n advanced=True,\n info=\"Use {{variable}} syntax instead of {variable}.\",\n real_time_refresh=True,\n ),\n MessageTextInput(\n name=\"tool_placeholder\",\n display_name=\"Tool Placeholder\",\n tool_mode=True,\n advanced=True,\n show=False,\n info=\"A placeholder input for tool mode.\",\n ),\n ]\n\n outputs = [\n Output(display_name=\"Prompt\", name=\"prompt\", method=\"build_prompt\"),\n ]\n\n def update_build_config(self, build_config: dotdict, field_value: Any, field_name: str | None = None) -> dotdict:\n \"\"\"Update the template field type based on the selected mode.\"\"\"\n if field_name == \"use_double_brackets\":\n # Change the template field type based on mode\n is_mustache = field_value is True\n if is_mustache:\n build_config[\"template\"][\"type\"] = FieldTypes.MUSTACHE_PROMPT.value\n else:\n build_config[\"template\"][\"type\"] = FieldTypes.PROMPT.value\n\n # Re-process the template to update variables when mode changes\n template_value = build_config.get(\"template\", {}).get(\"value\", \"\")\n if template_value:\n # Ensure custom_fields is properly initialized\n if \"custom_fields\" not in build_config:\n build_config[\"custom_fields\"] = {}\n\n # Clean up fields from the OLD mode before processing with NEW mode\n # This ensures we don't keep fields with wrong syntax even if validation fails\n old_custom_fields = build_config[\"custom_fields\"].get(\"template\", [])\n for old_field in list(old_custom_fields):\n # Remove the field from custom_fields and template\n if old_field in old_custom_fields:\n old_custom_fields.remove(old_field)\n build_config.pop(old_field, None)\n\n # Try to process template with new mode to add new variables\n # If validation fails, at least we cleaned up old fields\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(template_value)\n\n # Re-process template with new mode to add new variables\n _ = process_prompt_template(\n template=template_value,\n name=\"template\",\n custom_fields=build_config[\"custom_fields\"],\n frontend_node_template=build_config,\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, we still updated the mode and cleaned old fields\n # User will see error when they try to save\n logger.debug(f\"Template validation failed during mode switch: {e}\")\n return build_config\n\n async def build_prompt(self) -> Message:\n use_double_brackets = self.use_double_brackets if hasattr(self, \"use_double_brackets\") else False\n template_format = \"mustache\" if use_double_brackets else \"f-string\"\n prompt = await Message.from_template_and_variables(template_format=template_format, **self._attributes)\n self.status = prompt.text\n return prompt\n\n def _update_template(self, frontend_node: dict):\n prompt_template = frontend_node[\"template\"][\"template\"][\"value\"]\n use_double_brackets = frontend_node[\"template\"].get(\"use_double_brackets\", {}).get(\"value\", False)\n is_mustache = use_double_brackets is True\n\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(prompt_template)\n\n custom_fields = frontend_node[\"custom_fields\"]\n frontend_node_template = frontend_node[\"template\"]\n _ = process_prompt_template(\n template=prompt_template,\n name=\"template\",\n custom_fields=custom_fields,\n frontend_node_template=frontend_node_template,\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, don't add variables but allow component to be created\n logger.debug(f\"Template validation failed in _update_template: {e}\")\n return frontend_node\n\n async def update_frontend_node(self, new_frontend_node: dict, current_frontend_node: dict):\n \"\"\"This function is called after the code validation is done.\"\"\"\n frontend_node = await super().update_frontend_node(new_frontend_node, current_frontend_node)\n template = frontend_node[\"template\"][\"template\"][\"value\"]\n use_double_brackets = frontend_node[\"template\"].get(\"use_double_brackets\", {}).get(\"value\", False)\n is_mustache = use_double_brackets is True\n\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(template)\n\n # Kept it duplicated for backwards compatibility\n _ = process_prompt_template(\n template=template,\n name=\"template\",\n custom_fields=frontend_node[\"custom_fields\"],\n frontend_node_template=frontend_node[\"template\"],\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, don't add variables but allow component to be updated\n logger.debug(f\"Template validation failed in update_frontend_node: {e}\")\n # Now that template is updated, we need to grab any values that were set in the current_frontend_node\n # and update the frontend_node with those values\n update_template_values(new_template=frontend_node, previous_template=current_frontend_node[\"template\"])\n return frontend_node\n\n def _get_fallback_input(self, **kwargs):\n return DefaultPromptField(**kwargs)\n"
+ "value": "from typing import Any\n\nfrom lfx.base.prompts.api_utils import process_prompt_template\nfrom lfx.custom.custom_component.component import Component\nfrom lfx.inputs.input_mixin import FieldTypes\nfrom lfx.inputs.inputs import DefaultPromptField\nfrom lfx.io import BoolInput, MessageTextInput, Output, PromptInput\nfrom lfx.log.logger import logger\nfrom lfx.schema.dotdict import dotdict\nfrom lfx.schema.message import Message\nfrom lfx.template.utils import update_template_values\nfrom lfx.utils.mustache_security import validate_mustache_template\n\n\nclass PromptComponent(Component):\n display_name: str = \"Prompt Template\"\n description: str = \"Create a prompt template with dynamic variables.\"\n documentation: str = \"https://docs.langflow.org/components-prompts\"\n icon = \"prompts\"\n trace_type = \"prompt\"\n name = \"Prompt Template\"\n\n inputs = [\n PromptInput(name=\"template\", display_name=\"Template\"),\n BoolInput(\n name=\"use_double_brackets\",\n display_name=\"Use Double Brackets\",\n value=False,\n advanced=True,\n info=\"Use {{variable}} syntax instead of {variable}.\",\n real_time_refresh=True,\n ),\n MessageTextInput(\n name=\"tool_placeholder\",\n display_name=\"Tool Placeholder\",\n tool_mode=True,\n advanced=True,\n show=False,\n info=\"A placeholder input for tool mode.\",\n ),\n ]\n\n outputs = [\n Output(display_name=\"Prompt\", name=\"prompt\", method=\"build_prompt\"),\n ]\n\n def update_build_config(self, build_config: dotdict, field_value: Any, field_name: str | None = None) -> dotdict:\n \"\"\"Update the template field type based on the selected mode.\"\"\"\n if field_name == \"use_double_brackets\":\n # Change the template field type based on mode\n is_mustache = field_value is True\n if is_mustache:\n build_config[\"template\"][\"type\"] = FieldTypes.MUSTACHE_PROMPT.value\n else:\n build_config[\"template\"][\"type\"] = FieldTypes.PROMPT.value\n\n # Re-process the template to update variables when mode changes\n template_value = build_config.get(\"template\", {}).get(\"value\", \"\")\n if template_value:\n # Ensure custom_fields is properly initialized\n if \"custom_fields\" not in build_config:\n build_config[\"custom_fields\"] = {}\n\n # Clean up fields from the OLD mode before processing with NEW mode\n # This ensures we don't keep fields with wrong syntax even if validation fails\n old_custom_fields = build_config[\"custom_fields\"].get(\"template\", [])\n for old_field in list(old_custom_fields):\n # Remove the field from custom_fields and template\n if old_field in old_custom_fields:\n old_custom_fields.remove(old_field)\n build_config.pop(old_field, None)\n\n # Try to process template with new mode to add new variables\n # If validation fails, at least we cleaned up old fields\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(template_value)\n\n # Re-process template with new mode to add new variables\n _ = process_prompt_template(\n template=template_value,\n name=\"template\",\n custom_fields=build_config[\"custom_fields\"],\n frontend_node_template=build_config,\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, we still updated the mode and cleaned old fields\n # User will see error when they try to save\n logger.debug(\"Template validation failed during mode switch\", exc_info=e)\n return build_config\n\n async def build_prompt(self) -> Message:\n use_double_brackets = self.use_double_brackets if hasattr(self, \"use_double_brackets\") else False\n template_format = \"mustache\" if use_double_brackets else \"f-string\"\n prompt = await Message.from_template_and_variables(template_format=template_format, **self._attributes)\n self.status = prompt.text\n return prompt\n\n def _update_template(self, frontend_node: dict):\n prompt_template = frontend_node[\"template\"][\"template\"][\"value\"]\n use_double_brackets = frontend_node[\"template\"].get(\"use_double_brackets\", {}).get(\"value\", False)\n is_mustache = use_double_brackets is True\n\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(prompt_template)\n\n custom_fields = frontend_node[\"custom_fields\"]\n frontend_node_template = frontend_node[\"template\"]\n _ = process_prompt_template(\n template=prompt_template,\n name=\"template\",\n custom_fields=custom_fields,\n frontend_node_template=frontend_node_template,\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, don't add variables but allow component to be created\n logger.debug(\"Template validation failed in _update_template\", exc_info=e)\n return frontend_node\n\n async def update_frontend_node(self, new_frontend_node: dict, current_frontend_node: dict):\n \"\"\"This function is called after the code validation is done.\"\"\"\n frontend_node = await super().update_frontend_node(new_frontend_node, current_frontend_node)\n template = frontend_node[\"template\"][\"template\"][\"value\"]\n use_double_brackets = frontend_node[\"template\"].get(\"use_double_brackets\", {}).get(\"value\", False)\n is_mustache = use_double_brackets is True\n\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(template)\n\n # Kept it duplicated for backwards compatibility\n _ = process_prompt_template(\n template=template,\n name=\"template\",\n custom_fields=frontend_node[\"custom_fields\"],\n frontend_node_template=frontend_node[\"template\"],\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, don't add variables but allow component to be updated\n logger.debug(\"Template validation failed in update_frontend_node\", exc_info=e)\n # Now that template is updated, we need to grab any values that were set in the current_frontend_node\n # and update the frontend_node with those values\n update_template_values(new_template=frontend_node, previous_template=current_frontend_node[\"template\"])\n return frontend_node\n\n def _get_fallback_input(self, **kwargs):\n return DefaultPromptField(**kwargs)\n"
},
"filter": {
"advanced": false,
+ "api_editable": false,
"display_name": "filter",
"dynamic": false,
"field_type": "str",
@@ -1898,6 +1860,7 @@
},
"input": {
"advanced": false,
+ "api_editable": false,
"display_name": "input",
"dynamic": false,
"field_type": "str",
@@ -1921,6 +1884,7 @@
"template": {
"_input_type": "PromptInput",
"advanced": false,
+ "api_editable": false,
"display_name": "Template",
"dynamic": false,
"info": "",
@@ -1942,6 +1906,7 @@
"tool_placeholder": {
"_input_type": "MessageTextInput",
"advanced": true,
+ "api_editable": false,
"display_name": "Tool Placeholder",
"dynamic": false,
"info": "A placeholder input for tool mode.",
@@ -1967,6 +1932,7 @@
"use_double_brackets": {
"_input_type": "BoolInput",
"advanced": true,
+ "api_editable": false,
"display_name": "Use Double Brackets",
"dynamic": false,
"info": "Use {{variable}} syntax instead of {variable}.",
@@ -2190,15 +2156,15 @@
],
"frozen": false,
"icon": "Mcp",
- "last_updated": "2026-09-01T13:59:18.582Z",
+ "last_updated": "2026-09-08T21:06:51.865Z",
"legacy": false,
"metadata": {
- "code_hash": "12e2b4704b27",
+ "code_hash": "5a77bca15146",
"dependencies": {
"dependencies": [
{
"name": "langchain_core",
- "version": "1.6.1"
+ "version": "1.6.2"
},
{
"name": "pydantic",
@@ -2206,11 +2172,11 @@
},
{
"name": "lfx",
- "version": "1.11.6"
+ "version": "1.12.0"
},
{
"name": "langflow",
- "version": "0.11.6"
+ "version": "1.12.0"
}
],
"total_dependencies": 4
@@ -2245,7 +2211,7 @@
"value": "1098eea1-6649-4e1d-aed1-b77249fb8dd0"
},
"_frontend_node_folder_id": {
- "value": "fbc33683-53fb-4a7b-b1c8-505dcae74674"
+ "value": "7ff6c353-e65b-4821-9940-b18a52bf532b"
},
"_type": "Component",
"code": {
@@ -2265,7 +2231,7 @@
"show": true,
"title_case": false,
"type": "code",
- "value": "from __future__ import annotations\n\nimport asyncio\nimport hashlib\nimport json\nimport time\nimport uuid\nfrom types import UnionType\nfrom typing import Any, cast, get_args, get_origin\n\nfrom langchain_core.tools import StructuredTool # noqa: TC002\nfrom pydantic import BaseModel\n\nfrom lfx.base.agents.utils import maybe_unflatten_dict, safe_cache_get, safe_cache_set\nfrom lfx.base.mcp.util import (\n MCPStdioClient,\n MCPStreamableHttpClient,\n update_tools,\n)\nfrom lfx.base.tools.constants import TOOL_OUTPUT_DISPLAY_NAME, TOOL_OUTPUT_NAME\nfrom lfx.custom.custom_component.component_with_cache import ComponentWithCache\nfrom lfx.inputs.inputs import InputTypes # noqa: TC001\nfrom lfx.io import BoolInput, DictInput, DropdownInput, FloatInput, McpInput, MessageTextInput, Output\nfrom lfx.io.schema import schema_to_langflow_inputs\nfrom lfx.log.logger import logger\nfrom lfx.schema.dataframe import DataFrame\nfrom lfx.schema.message import Message\nfrom lfx.services.deps import get_storage_service, session_scope\n\n\ndef resolve_mcp_config(\n server_name: str, # noqa: ARG001\n server_config_from_value: dict | None,\n server_config_from_db: dict | None,\n) -> dict | None:\n \"\"\"Resolve MCP server config with proper precedence.\n\n Resolves the configuration for an MCP server with the following precedence:\n 1. Database config (takes priority) - ensures edits are reflected\n 2. Config from value/tweaks (fallback) - allows REST API to provide config for new servers\n\n Args:\n server_name: Name of the MCP server\n server_config_from_value: Config provided via value/tweaks (optional)\n server_config_from_db: Config from database (optional)\n\n Returns:\n Final config to use (DB takes priority, falls back to value)\n Returns None if no config found in either location\n \"\"\"\n if server_config_from_db:\n return server_config_from_db\n return server_config_from_value\n\n\n# TODO(legacy-cleanup): This file is ~800 lines, over the 500-line guideline. Split\n# helper functions (resolve_mcp_config, connection resolution) from the MCPToolsComponent\n# orchestration logic in a follow-up PR.\nclass MCPToolsComponent(ComponentWithCache):\n \"\"\"MCP Tools component.\n\n Behaviour notes:\n - Stale agent tools vs server were caused by Langflow caching the Toolset output\n (``Output.cache=True`` plus the persisted ``output.value`` in saved flow JSON), not\n only by the user-facing \"Use Cached Server\" (``use_cache``) toggle. ``_build_tool_output``\n declares the Toolset output with ``cache=False`` and ``map_outputs`` overrides the\n persisted value for existing flows so every run resolves a fresh tool list.\n - ``update_tool_list`` is serialized with an ``asyncio.Lock`` so concurrent calls do not\n share the same Streamable HTTP client session; overlapping POST/DELETE cycles otherwise\n surface as HTTP 404 and the MCP SDK reports ``Session terminated``.\n - All diagnostic logs are at DEBUG level to avoid swamping logs on hot paths (an agent\n may call ``_get_tools`` per step). Header values are never logged; only header *keys*.\n \"\"\"\n\n # Short-lived in-memory cache window (seconds) for ``_get_tools``. When the\n # same header-hash key is requested again within this window the cached tool\n # list is reused so parallel agent runs that share identical auth don't\n # each pay for a fresh MCP round-trip. Set to ``0`` to disable. This is\n # distinct from the \"Use Cached Server\" (``use_cache``) toggle which only\n # controls the shared cross-request server cache.\n TOOL_TTL_SECS: int = 30\n # Upper bound on the per-component-lineage TTL cache. Oldest entries are evicted\n # when the cap is reached. Keeps memory bounded for flows where the same\n # component handles many rotating auth contexts (e.g. per-tenant tokens).\n TOOL_TTL_MAX_ENTRIES: int = 32\n # Upper bound on the shared cross-request ``servers`` cache. Each\n # (server_name, header-hash) pair is a distinct entry; without a bound a\n # tenant that rotates session tokens would grow this map without limit.\n SHARED_SERVERS_CACHE_MAX_ENTRIES: int = 64\n\n schema_inputs: list = []\n tools: list[StructuredTool] = []\n _not_load_actions: bool = False\n _tool_cache: dict = {}\n _last_selected_server: str | None = None # Cache for the last selected server\n\n def __init__(self, **data) -> None:\n super().__init__(**data)\n # Initialize cache keys to avoid CacheMiss when accessing them\n self._ensure_cache_structure()\n\n # Initialize clients with access to the component cache.\n # Per-component timeout is normalized and applied immediately before MCP calls.\n self.stdio_client: MCPStdioClient = MCPStdioClient(component_cache=self._shared_component_cache)\n self.streamable_http_client: MCPStreamableHttpClient = MCPStreamableHttpClient(\n component_cache=self._shared_component_cache\n )\n # One MCP stdio/streamable client pair per component; concurrent update_tool_list calls\n # otherwise race (session DELETE vs POST) and the MCP SDK surfaces HTTP 404 as \"Session terminated\".\n self._update_tool_list_lock = asyncio.Lock()\n # Per-component-lineage TTL cache for ``_get_tools``:\n # {cache_key: (monotonic_ts, tools)}. Freshly instantiated components get their own\n # dict; ``__deepcopy__`` shares it only with that component's invocation copies.\n # A class-level dict would instead expose entries to every MCPToolsComponent in the\n # process, leaking tool lists across tenants that happen to hash to the same key.\n self._ttl_tool_cache: dict[str, tuple[float, list]] = {}\n\n def __deepcopy__(self, memo: dict) -> MCPToolsComponent:\n \"\"\"Keep the per-component tool cache available to isolated invocation copies.\"\"\"\n component_copy = cast(\"MCPToolsComponent\", super().__deepcopy__(memo))\n # Component tools are deep-copied for every invocation to isolate mutable inputs.\n # Those copies belong to the same component execution lineage, so sharing this\n # bounded, auth-scoped cache preserves its TTL without exposing it to independently\n # instantiated components.\n component_copy._ttl_tool_cache = self._ttl_tool_cache # noqa: SLF001\n return component_copy\n\n def _ensure_cache_structure(self):\n \"\"\"Ensure the cache has the required structure.\"\"\"\n # Check if servers key exists and is not CacheMiss\n servers_value = safe_cache_get(self._shared_component_cache, \"servers\")\n if servers_value is None:\n safe_cache_set(self._shared_component_cache, \"servers\", {})\n\n # Check if last_selected_server key exists and is not CacheMiss\n last_server_value = safe_cache_get(self._shared_component_cache, \"last_selected_server\")\n if last_server_value is None:\n safe_cache_set(self._shared_component_cache, \"last_selected_server\", \"\")\n\n def _normalized_headers_for_cache(self) -> dict[str, str]:\n \"\"\"Component headers as a dict for stable cache keying (auth / tweaks).\"\"\"\n component_headers = getattr(self, \"headers\", None) or []\n if isinstance(component_headers, list):\n return {\n str(item[\"key\"]): str(item[\"value\"])\n for item in component_headers\n if isinstance(item, dict) and \"key\" in item and \"value\" in item\n }\n if isinstance(component_headers, dict):\n return {str(k): str(v) for k, v in component_headers.items()}\n return {}\n\n def _normalize_tool_execution_timeout(self) -> float | None:\n \"\"\"Normalize the timeout input and reject negative values with a field-specific error.\"\"\"\n timeout_value = getattr(self, \"tool_execution_timeout\", 0.0)\n\n if timeout_value in (None, \"\"):\n return None\n\n try:\n val = float(timeout_value)\n except (ValueError, TypeError):\n return None\n\n if val < 0:\n msg = \"Tool Execution Timeout must be greater than or equal to 0.\"\n raise ValueError(msg)\n\n return val if val else None\n\n def _mcp_servers_cache_key(self, server_name: str) -> str:\n \"\"\"Cache key for shared servers map.\n\n Includes the authenticated user, headers, and timeout so tenant/auth/tweak/timeout\n changes get distinct entries.\n \"\"\"\n if not server_name:\n return \"\"\n\n raw_timeout = getattr(self, \"tool_execution_timeout\", 0.0) or 0.0\n normalized_timeout = max(0.0, float(raw_timeout))\n\n hdrs = self._normalized_headers_for_cache()\n\n # Build cache key components\n cache_data = {\n \"headers\": hdrs,\n \"timeout\": normalized_timeout,\n }\n\n user_id = self._mcp_cache_user_id()\n if user_id:\n cache_data[\"user_id\"] = user_id\n\n # Preserve the compact per-instance TTL key when there is no authenticated user.\n # Shared caching is disabled for that case in ``update_tool_list`` below.\n if not hdrs and normalized_timeout == 0.0 and not user_id:\n return server_name\n\n payload = json.dumps(cache_data, sort_keys=True)\n digest = hashlib.sha256(payload.encode()).hexdigest()[:16]\n return f\"{server_name}:{digest}\"\n\n def _mcp_cache_user_id(self) -> str | None:\n \"\"\"Return the authenticated user id without requiring a fully attached graph.\n\n Components are also instantiated without a vertex while the UI builds component\n metadata. Accessing ``self.user_id`` in that state raises, so inspect the backing\n fields directly and fail closed by returning ``None`` when no authenticated scope\n is available.\n \"\"\"\n user_id = getattr(self, \"_user_id\", None)\n if not user_id:\n graph = getattr(getattr(self, \"_vertex\", None), \"graph\", None)\n user_id = getattr(graph, \"user_id\", None)\n return str(user_id) if user_id else None\n\n def _build_tool_output(self) -> Output:\n # Do not cache Toolset output. This is separate from the MCP \"Use Cached Server\" (use_cache)\n # toggle: Langflow's Output.cache defaults to True and was memoizing the first to_toolkit()\n # result, so per-request tweaks/headers never refreshed bound tools even when use_cache=False.\n return Output(\n name=TOOL_OUTPUT_NAME,\n display_name=TOOL_OUTPUT_DISPLAY_NAME,\n method=\"to_toolkit\",\n types=[\"Tool\"],\n cache=False,\n )\n\n def map_outputs(self) -> None:\n \"\"\"Override the persisted ``component_as_tool`` cache flag from saved flow JSON.\n\n ``_build_tool_output`` already returns the output with ``cache=False``, but the\n flow JSON for existing flows often stores ``cache: true`` for ``component_as_tool``\n and that persisted value wins over the declaration. Forcing ``cache=False`` here\n guarantees saved flows also bypass Output memoization and get a fresh tool list\n on every run.\n \"\"\"\n super().map_outputs()\n if TOOL_OUTPUT_NAME in self._outputs_map:\n self._outputs_map[TOOL_OUTPUT_NAME].cache = False\n\n default_keys: list[str] = [\n \"code\",\n \"_type\",\n \"tool_mode\",\n \"tool_placeholder\",\n \"mcp_server\",\n \"tool\",\n \"use_cache\",\n \"verify_ssl\",\n \"headers\",\n \"tool_execution_timeout\",\n ]\n\n display_name = \"MCP Tools\"\n description = \"Connect to an MCP server to use its tools.\"\n documentation: str = \"https://docs.langflow.org/mcp-tools\"\n icon = \"Mcp\"\n name = \"MCPTools\"\n\n inputs = [\n McpInput(\n name=\"mcp_server\",\n display_name=\"MCP Server\",\n info=\"Select the MCP Server that will be used by this component\",\n real_time_refresh=True,\n ),\n BoolInput(\n name=\"use_cache\",\n display_name=\"Use Cached Server\",\n info=(\n \"Enable caching of MCP Server and tools to improve performance. \"\n \"Disable to always fetch fresh tools and server updates.\"\n ),\n value=False,\n advanced=True,\n ),\n BoolInput(\n name=\"verify_ssl\",\n display_name=\"Verify SSL Certificate\",\n info=(\n \"Enable SSL certificate verification for HTTPS connections. \"\n \"Disable only for development/testing with self-signed certificates.\"\n ),\n value=True,\n advanced=True,\n ),\n DictInput(\n name=\"headers\",\n display_name=\"Headers\",\n info=(\n \"HTTP headers to include with MCP server requests. \"\n \"Useful for authentication (e.g., Authorization header). \"\n \"These headers override any headers configured in the MCP server settings.\"\n ),\n advanced=True,\n is_list=True,\n ),\n FloatInput(\n name=\"tool_execution_timeout\",\n display_name=\"Tool Execution Timeout (seconds)\",\n info=(\n \"Maximum time to wait for tool execution before timing out. \"\n \"Supports decimal values for sub-second timeouts (e.g., 0.01 for 10ms). \"\n \"Set to 0 to use the system-configured MCP timeout.\"\n ),\n value=0.0,\n range_spec={\"min\": 0.0, \"max\": 3600.0, \"step\": 0.01},\n real_time_refresh=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"tool\",\n display_name=\"Tool\",\n options=[],\n value=\"\",\n info=\"Select the tool to execute\",\n show=False,\n required=True,\n real_time_refresh=True,\n refresh_button=True,\n ),\n MessageTextInput(\n name=\"tool_placeholder\",\n display_name=\"Tool Placeholder\",\n info=\"Placeholder for the tool\",\n value=\"\",\n show=False,\n # Tool Mode is a capability of the component, not of the selected\n # server. Advertising it up front keeps the toolbar from waiting\n # for the MCP server's tool-discovery request to finish.\n tool_mode=True,\n ),\n ]\n\n outputs = [\n Output(display_name=\"Response\", name=\"response\", method=\"build_output\"),\n ]\n\n async def _validate_schema_inputs(self, tool_obj) -> list[InputTypes]:\n \"\"\"Validate and process schema inputs for a tool.\"\"\"\n try:\n if not tool_obj or not hasattr(tool_obj, \"args_schema\"):\n msg = \"Invalid tool object or missing input schema\"\n raise ValueError(msg)\n\n input_schema = tool_obj.args_schema\n if not input_schema:\n msg = f\"Empty input schema for tool '{tool_obj.name}'\"\n raise ValueError(msg)\n\n schema_inputs = schema_to_langflow_inputs(input_schema)\n if not schema_inputs:\n msg = f\"No input parameters defined for tool '{tool_obj.name}'\"\n await logger.awarning(msg)\n return []\n\n except Exception as e:\n msg = f\"Error validating schema inputs: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n else:\n return schema_inputs\n\n async def _ensure_cached_mcp_stdio_access(self, server_config: dict) -> None:\n \"\"\"Reapply the current stdio policy before returning cached tools.\"\"\"\n try:\n from langflow.api.v2.mcp import ensure_mcp_stdio_access\n from langflow.services.database.models.user.crud import get_user_by_id\n\n from lfx.services.deps import get_settings_service\n except ModuleNotFoundError as e:\n missing_module = e.name or \"\"\n if missing_module != \"langflow\" and not missing_module.startswith(\"langflow.\"):\n raise\n return\n\n async with session_scope() as db:\n if not self.user_id:\n msg = \"User ID is required for fetching MCP tools.\"\n raise ValueError(msg)\n current_user = await get_user_by_id(db, self.user_id)\n\n ensure_mcp_stdio_access(server_config, current_user, get_settings_service().settings)\n\n async def update_tool_list(self, mcp_server_value=None):\n # Accepts mcp_server_value as dict {name, config} or uses self.mcp_server\n mcp_server = mcp_server_value if mcp_server_value is not None else getattr(self, \"mcp_server\", None)\n server_name = None\n server_config_from_value = None\n if isinstance(mcp_server, dict):\n server_name = mcp_server.get(\"name\")\n server_config_from_value = mcp_server.get(\"config\")\n else:\n server_name = mcp_server\n if not server_name:\n self.tools = []\n await logger.adebug(\"MCP update_tool_list: empty server_name, clearing tools\")\n return [], {\"name\": server_name, \"config\": server_config_from_value}\n\n servers_cache_key = self._mcp_servers_cache_key(server_name)\n\n # Check if caching is enabled, default to False. The cross-request cache must never\n # be used without an authenticated tenant scope; the per-instance TTL cache remains\n # available in standalone/UI contexts.\n use_cache = getattr(self, \"use_cache\", False)\n use_shared_cache = use_cache and self._mcp_cache_user_id() is not None\n header_keys = sorted(self._normalized_headers_for_cache().keys())\n await logger.adebug(\n \"MCP update_tool_list: start server=%r use_cache=%s use_shared_cache=%s shared_cache_key=%r header_keys=%s\",\n server_name,\n use_cache,\n use_shared_cache,\n servers_cache_key,\n header_keys,\n )\n\n async with self._update_tool_list_lock:\n # Use shared cache if available and caching is enabled\n cached = None\n if use_shared_cache:\n servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n cached = servers_cache.get(servers_cache_key) if isinstance(servers_cache, dict) else None\n\n if cached is not None:\n try:\n tools_from_cache = cached[\"tools\"]\n server_config_from_value = cached[\"config\"]\n except (TypeError, KeyError, AttributeError) as e:\n # Handle corrupted cache data by clearing it and continuing to fetch fresh tools\n msg = f\"Unable to use cached data for MCP Server{server_name}: {e}\"\n await logger.awarning(msg)\n # Clear the corrupted cache entry\n current_servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(current_servers_cache, dict) and servers_cache_key in current_servers_cache:\n current_servers_cache.pop(servers_cache_key)\n safe_cache_set(self._shared_component_cache, \"servers\", current_servers_cache)\n else:\n try:\n await self._ensure_cached_mcp_stdio_access(server_config_from_value)\n except Exception as e:\n msg = f\"Error updating tool list: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n else:\n self.tools = tools_from_cache\n self.tool_names = [t.name for t in self.tools if hasattr(t, \"name\")]\n self._tool_cache = cached[\"tool_cache\"]\n await logger.adebug(\n \"MCP update_tool_list: shared_servers_cache HIT count=%d server=%r\",\n len(self.tools),\n server_name,\n )\n return self.tools, {\"name\": server_name, \"config\": server_config_from_value}\n\n try:\n # Try to fetch from database first to ensure we have the latest config.\n # This ensures database updates (like editing a server) take effect.\n # When running in LFX standalone mode the full Langflow package and\n # database may not be available — in that case we skip the DB lookup\n # and fall back to the config embedded in the flow (server_config_from_value).\n server_config_from_db = None\n current_user = None\n settings_service = None\n ensure_mcp_stdio_access = None\n try:\n from langflow.api.v2.mcp import ensure_mcp_stdio_access, get_server\n from langflow.services.database.models.user.crud import get_user_by_id\n\n from lfx.services.deps import get_settings_service\n except ModuleNotFoundError as e:\n # Deliberately `except ModuleNotFoundError` (not `except ImportError`): a\n # plain ImportError here means `get_server` / `get_user_by_id` was removed\n # from an installed Langflow — a real API break that should NOT be\n # swallowed as \"standalone mode\". ModuleNotFoundError alone covers the\n # \"Langflow absent\" case.\n #\n # Even within ModuleNotFoundError, only treat this as LFX standalone mode\n # when one of the target Langflow modules is itself missing. Transitive\n # ModuleNotFoundError (e.g. a dependency like sqlmodel failing to import\n # inside langflow.*) indicates a real bug in the full Langflow stack and\n # must surface — otherwise we would silently use a stale flow-embedded\n # config when DB config should have taken precedence.\n missing_module = e.name or \"\"\n is_langflow_standalone = missing_module == \"langflow\" or missing_module.startswith(\"langflow.\")\n if not is_langflow_standalone:\n raise\n await logger.ainfo(\n \"Langflow package not available; using MCP server config from flow value (LFX standalone mode).\"\n )\n else:\n async with session_scope() as db:\n if not self.user_id:\n msg = \"User ID is required for fetching MCP tools.\"\n raise ValueError(msg)\n current_user = await get_user_by_id(db, self.user_id)\n settings_service = get_settings_service()\n\n # Try to get server config from DB/API\n server_config_from_db = await get_server(\n server_name,\n current_user,\n db,\n storage_service=get_storage_service(),\n settings_service=settings_service,\n )\n\n # Resolve config with proper precedence: DB takes priority, falls back to value\n server_config = resolve_mcp_config(\n server_name=server_name,\n server_config_from_value=server_config_from_value,\n server_config_from_db=server_config_from_db,\n )\n\n if not server_config:\n self.tools = []\n await logger.awarning(\n \"MCP update_tool_list: no server_config after resolve server=%r\",\n server_name,\n )\n msg = (\n f\"MCP server '{server_name}' is not configured. \"\n \"Add a server with this name in Settings > MCP Servers before running this flow.\"\n )\n raise ValueError(msg)\n\n # The REST API applies this policy when a stdio server is registered,\n # but imported flows can carry the same process-spawning config in the\n # MCP component value. Reapply the policy to the resolved config at the\n # component boundary before update_tools reaches the subprocess client.\n if ensure_mcp_stdio_access is not None and current_user is not None and settings_service is not None:\n ensure_mcp_stdio_access(server_config, current_user, settings_service.settings)\n\n # Add verify_ssl option to server config if not present\n if \"verify_ssl\" not in server_config:\n verify_ssl = getattr(self, \"verify_ssl\", True)\n server_config[\"verify_ssl\"] = verify_ssl\n\n # Merge headers from component input with server config headers\n # Component headers take precedence over server config headers\n component_headers = getattr(self, \"headers\", None) or []\n if component_headers:\n # Convert list of {\"key\": k, \"value\": v} to dict\n component_headers_dict = {}\n if isinstance(component_headers, list):\n for item in component_headers:\n if isinstance(item, dict) and \"key\" in item and \"value\" in item:\n component_headers_dict[item[\"key\"]] = item[\"value\"]\n elif isinstance(component_headers, dict):\n component_headers_dict = component_headers\n\n if component_headers_dict:\n existing_headers = server_config.get(\"headers\", {}) or {}\n # Ensure existing_headers is a dict (convert from list if needed)\n if isinstance(existing_headers, list):\n existing_dict = {}\n for item in existing_headers:\n if isinstance(item, dict) and \"key\" in item and \"value\" in item:\n existing_dict[item[\"key\"]] = item[\"value\"]\n existing_headers = existing_dict\n merged_headers = {**existing_headers, **component_headers_dict}\n server_config[\"headers\"] = merged_headers\n # Get request_variables from graph context for global variable resolution\n request_variables = None\n if hasattr(self, \"graph\") and self.graph and hasattr(self.graph, \"context\"):\n request_variables = self.graph.context.get(\"request_variables\")\n\n # Only load global variables from database if we have headers that might use them\n # This avoids unnecessary database queries when headers are empty.\n #\n # The database load must NOT be skipped just because the request carried\n # overrides: a request that overrides one variable still needs every other\n # header variable resolved from the database. Skipping the load there sends\n # the unresolved variable *name* upstream as the header value. Per-request\n # values win on conflict, matching ``CustomComponent.get_variable``.\n has_headers = server_config.get(\"headers\") and len(server_config.get(\"headers\", {})) > 0\n if has_headers:\n try:\n from lfx.services.deps import get_variable_service\n\n variable_service = get_variable_service()\n # ``get_all_decrypted_variables`` is DB-service-only; the minimal\n # lfx VariableService (now registered by ``lfx serve``) lacks it, so\n # skip cleanly rather than raising into the broad except below.\n if variable_service and hasattr(variable_service, \"get_all_decrypted_variables\"):\n async with session_scope() as db:\n db_variables = await variable_service.get_all_decrypted_variables(\n user_id=self.user_id, session=db\n )\n request_variables = {**(db_variables or {}), **(request_variables or {})}\n except Exception as e: # noqa: BLE001\n await logger.awarning(f\"Failed to load global variables for MCP component: {e}\")\n\n await logger.adebug(\n \"MCP update_tool_list: calling update_tools server=%r mode_headers=%s\",\n server_name,\n sorted((server_config.get(\"headers\") or {}).keys())\n if isinstance(server_config.get(\"headers\"), dict)\n else \"list-or-empty\",\n )\n\n timeout = self._normalize_tool_execution_timeout()\n\n _, tool_list, tool_cache = await update_tools(\n server_name=server_name,\n server_config=server_config,\n mcp_stdio_client=self.stdio_client,\n mcp_streamable_http_client=self.streamable_http_client,\n request_variables=request_variables,\n tool_execution_timeout=timeout,\n current_user_id=self.user_id,\n )\n\n self.tool_names = [tool.name for tool in tool_list if hasattr(tool, \"name\")]\n self._tool_cache = tool_cache\n self.tools = tool_list\n\n await logger.adebug(\n \"MCP update_tool_list: fetched from MCP count=%d server=%r\",\n len(tool_list),\n server_name,\n )\n\n # Cache the result only if caching is enabled\n if use_shared_cache:\n cache_data = {\n \"tools\": tool_list,\n \"tool_names\": self.tool_names,\n \"tool_cache\": tool_cache,\n \"config\": server_config,\n }\n\n # Safely update the servers cache with bounded size (FIFO eviction).\n current_servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(current_servers_cache, dict):\n # Because the cache key now includes a header hash, a tenant that\n # rotates session tokens would grow this map without bound. Drop\n # the oldest entry when over the limit.\n max_entries = self.SHARED_SERVERS_CACHE_MAX_ENTRIES\n while (\n len(current_servers_cache) >= max_entries and servers_cache_key not in current_servers_cache\n ):\n oldest_key = next(iter(current_servers_cache))\n current_servers_cache.pop(oldest_key, None)\n current_servers_cache[servers_cache_key] = cache_data\n safe_cache_set(self._shared_component_cache, \"servers\", current_servers_cache)\n await logger.adebug(\n \"MCP update_tool_list: wrote shared_servers_cache key=%r size=%d\",\n servers_cache_key,\n len(current_servers_cache),\n )\n\n except (TimeoutError, asyncio.TimeoutError) as e:\n msg = (\n f\"Timeout updating tool list: {e!s}. \"\n \"Raise ``LANGFLOW_MCP_SERVER_TIMEOUT`` for the deployment if the MCP \"\n \"server legitimately needs more time to respond.\"\n )\n await logger.aexception(msg)\n raise TimeoutError(msg) from e\n except Exception as e:\n msg = f\"Error updating tool list: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n else:\n return tool_list, {\"name\": server_name, \"config\": server_config}\n\n async def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None) -> dict:\n \"\"\"Toggle the visibility of connection-specific fields based on the selected mode.\"\"\"\n try:\n is_refresh = bool(build_config.get(\"is_refresh\", False))\n if field_name == \"tool\":\n try:\n # Always refresh tools when cache is disabled, or when tools list is empty\n # This ensures database edits are reflected immediately when cache is disabled\n use_cache = getattr(self, \"use_cache\", False)\n if is_refresh:\n self.tools = []\n if is_refresh or len(self.tools) == 0 or not use_cache:\n try:\n self.tools, build_config[\"mcp_server\"][\"value\"] = await self.update_tool_list()\n build_config[\"tool\"][\"options\"] = [tool.name for tool in self.tools]\n build_config[\"tool\"][\"placeholder\"] = \"Select a tool\"\n except (TimeoutError, asyncio.TimeoutError) as e:\n msg = f\"Timeout updating tool list: {e!s}\"\n await logger.aexception(msg)\n if not build_config[\"tools_metadata\"][\"show\"]:\n build_config[\"tool\"][\"show\"] = True\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"value\"] = \"\"\n build_config[\"tool\"][\"placeholder\"] = msg\n else:\n build_config[\"tool\"][\"show\"] = False\n except ValueError as e:\n msg = f\"Error updating tool list: {e!s}\"\n await logger.aexception(msg)\n if not build_config[\"tools_metadata\"][\"show\"]:\n build_config[\"tool\"][\"show\"] = True\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"value\"] = \"\"\n build_config[\"tool\"][\"placeholder\"] = msg\n else:\n build_config[\"tool\"][\"show\"] = False\n\n if field_value == \"\":\n return build_config\n tool_obj = None\n for tool in self.tools:\n if tool.name == field_value:\n tool_obj = tool\n break\n if tool_obj is None:\n msg = f\"Tool {field_value} not found in available tools: {self.tools}\"\n await logger.awarning(msg)\n return build_config\n await self._update_tool_config(build_config, field_value)\n except Exception as e:\n build_config[\"tool\"][\"options\"] = []\n msg = f\"Failed to update tools: {e!s}\"\n raise ValueError(msg) from e\n else:\n return build_config\n elif field_name == \"mcp_server\":\n if not field_value:\n build_config[\"tool\"][\"show\"] = False\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"value\"] = \"\"\n build_config[\"tool\"][\"placeholder\"] = \"\"\n build_config[\"tool_placeholder\"][\"tool_mode\"] = True\n self.remove_non_default_keys(build_config)\n return build_config\n\n build_config[\"tool_placeholder\"][\"tool_mode\"] = True\n\n current_server_name = field_value.get(\"name\") if isinstance(field_value, dict) else field_value\n build_config_server_value = build_config.get(\"mcp_server\", {}).get(\"value\")\n build_config_server_name = (\n build_config_server_value.get(\"name\")\n if isinstance(build_config_server_value, dict)\n else build_config_server_value\n )\n servers_cache_key_ui = self._mcp_servers_cache_key(current_server_name) if current_server_name else \"\"\n _last_selected_server = safe_cache_get(self._shared_component_cache, \"last_selected_server\", \"\")\n # Only treat as a server change if there was a previous server selection.\n # Cold cache (_last_selected_server=\"\") on initial flow load is NOT a server change —\n # the user didn't switch anything, the backend just hasn't seen this component yet.\n server_changed = bool(\n (_last_selected_server and current_server_name != _last_selected_server)\n or (build_config_server_name and current_server_name != build_config_server_name)\n )\n\n # Determine if \"Tool Mode\" is active by checking if the tool dropdown is hidden.\n is_in_tool_mode = build_config[\"tools_metadata\"][\"show\"]\n\n # Get use_cache setting to determine if we should use cached data\n use_cache = getattr(self, \"use_cache\", False)\n has_shared_cache_scope = self._mcp_cache_user_id() is not None\n use_shared_cache = use_cache and has_shared_cache_scope\n\n # Fast path: if server didn't change and we already have options, keep them as-is\n # BUT only if caching is enabled, we're in tool mode, or it's the initial load\n existing_options = build_config.get(\"tool\", {}).get(\"options\") or []\n if not is_refresh and not server_changed and existing_options:\n # In non-tool mode with cache disabled, skip the fast path to force refresh\n # BUT on initial load (cold cache), always preserve saved options from the flow\n if not is_in_tool_mode and not use_cache and _last_selected_server:\n pass # Continue to refresh logic below (user-initiated with cache disabled)\n else:\n if not is_in_tool_mode:\n build_config[\"tool\"][\"show\"] = True\n safe_cache_set(self._shared_component_cache, \"last_selected_server\", current_server_name)\n return build_config\n\n # To avoid unnecessary updates, only proceed if the server has actually changed\n # OR if caching is disabled (to force refresh in non-tool mode)\n if (\n not is_refresh\n and (_last_selected_server in (current_server_name, \"\"))\n and build_config[\"tool\"][\"show\"]\n and use_shared_cache\n ):\n if current_server_name:\n servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(servers_cache, dict):\n cached = servers_cache.get(servers_cache_key_ui)\n if cached is not None and cached.get(\"tool_names\"):\n cached_tools = cached[\"tool_names\"]\n current_tools = build_config[\"tool\"][\"options\"]\n if current_tools == cached_tools:\n return build_config\n else:\n return build_config\n safe_cache_set(self._shared_component_cache, \"last_selected_server\", current_server_name)\n\n # When cache is disabled, clear any cached data for this server\n # This ensures we always fetch fresh data from the database\n if (is_refresh or not use_cache) and current_server_name and has_shared_cache_scope:\n servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(servers_cache, dict) and servers_cache_key_ui in servers_cache:\n servers_cache.pop(servers_cache_key_ui)\n safe_cache_set(self._shared_component_cache, \"servers\", servers_cache)\n\n # Check if tools are already cached for this server before clearing\n cached_tools = None\n if current_server_name and use_shared_cache and not is_refresh:\n servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(servers_cache, dict):\n cached = servers_cache.get(servers_cache_key_ui)\n if cached is not None:\n try:\n cached_tools = cached[\"tools\"]\n self.tools = cached_tools\n self.tool_names = cached[\"tool_names\"]\n self._tool_cache = cached[\"tool_cache\"]\n except (TypeError, KeyError, AttributeError) as e:\n # Handle corrupted cache data by ignoring it\n msg = f\"Unable to use cached data for MCP Server,{current_server_name}: {e}\"\n await logger.awarning(msg)\n cached_tools = None\n\n # Clear tools when cache is disabled OR when we don't have cached tools\n # This ensures fresh tools are fetched after database edits\n if is_refresh or not cached_tools or not use_cache:\n self.tools = [] # Clear previous tools to force refresh\n\n # Clear previous tool inputs if:\n # 1. Server actually changed\n # 2. Cache is disabled (meaning tool list will be refreshed)\n if is_refresh or server_changed or not use_cache:\n self.remove_non_default_keys(build_config)\n\n # Only show the tool dropdown if not in tool_mode\n if not is_in_tool_mode:\n build_config[\"tool\"][\"show\"] = True\n if cached_tools:\n # Use cached tools to populate options immediately\n build_config[\"tool\"][\"options\"] = [tool.name for tool in cached_tools]\n build_config[\"tool\"][\"placeholder\"] = \"Select a tool\"\n else:\n # Actually fetch tools now instead of deferring to a frontend callback.\n # The frontend has no reliable mechanism to trigger a second\n # update_build_config call for the \"tool\" field after this response,\n # so we must populate the options here.\n try:\n self.tools, build_config[\"mcp_server\"][\"value\"] = await self.update_tool_list(\n mcp_server_value=field_value\n )\n build_config[\"tool\"][\"options\"] = [tool.name for tool in self.tools]\n build_config[\"tool\"][\"placeholder\"] = \"Select a tool\"\n except (TimeoutError, asyncio.TimeoutError) as e:\n msg = f\"Timeout loading tools for MCP server: {e!s}\"\n await logger.aexception(msg)\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"placeholder\"] = \"Timeout on MCP server\"\n except (ValueError, ImportError, ConnectionError, OSError, RuntimeError) as e:\n msg = f\"Error loading tools for MCP server: {e!s}\"\n await logger.aexception(msg)\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"placeholder\"] = (\n \"Error on MCP Server\" if \"'NoneType' object has no attribute 'id'\" in msg else msg\n )\n # Force a value refresh only when the user genuinely switched servers.\n # server_changed is only True for real user-initiated changes (not initial load).\n if server_changed:\n build_config[\"tool\"][\"value\"] = uuid.uuid4()\n else:\n # Keep the tool dropdown hidden if in tool_mode\n self._not_load_actions = True\n build_config[\"tool\"][\"show\"] = False\n\n elif field_name == \"tool_mode\":\n build_config[\"tool\"][\"placeholder\"] = \"\"\n build_config[\"tool\"][\"show\"] = not bool(field_value) and bool(build_config[\"mcp_server\"])\n self.remove_non_default_keys(build_config)\n self.tool = build_config[\"tool\"][\"value\"]\n if field_value:\n self._not_load_actions = True\n else:\n build_config[\"tool\"][\"value\"] = uuid.uuid4()\n build_config[\"tool\"][\"show\"] = True\n # Fetch tools immediately instead of showing \"Loading tools...\"\n try:\n self.tools, build_config[\"mcp_server\"][\"value\"] = await self.update_tool_list()\n build_config[\"tool\"][\"options\"] = [tool.name for tool in self.tools]\n build_config[\"tool\"][\"placeholder\"] = \"Select a tool\"\n except (TimeoutError, asyncio.TimeoutError) as e:\n msg = f\"Timeout loading tools when toggling tool mode: {e!s}\"\n await logger.aexception(msg)\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"placeholder\"] = msg\n except (ValueError, ImportError, ConnectionError, OSError, RuntimeError) as e:\n msg = f\"Error loading tools when toggling tool mode: {e!s}\"\n await logger.aexception(msg)\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"placeholder\"] = msg\n elif field_name == \"tool_execution_timeout\":\n try:\n val = float(field_value) if field_value not in (None, \"\") else 0.0\n except (ValueError, TypeError):\n val = 0.0\n if val < 0:\n build_config[\"tool_execution_timeout\"][\"placeholder\"] = (\n \"⚠ Value must be ≥ 0. Negative timeouts cause immediate failures.\"\n )\n build_config[\"tool_execution_timeout\"][\"value\"] = 0.0\n else:\n build_config[\"tool_execution_timeout\"][\"placeholder\"] = \"\"\n elif field_name == \"tools_metadata\":\n self._not_load_actions = False\n\n except Exception as e:\n msg = f\"Error in update_build_config: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n else:\n return build_config\n\n @staticmethod\n def _unwrap_optional_annotation(annotation: Any) -> Any:\n \"\"\"Remove a single None branch from a union annotation.\"\"\"\n if isinstance(annotation, UnionType):\n non_none = [item for item in get_args(annotation) if item is not type(None)]\n if len(non_none) == 1:\n return non_none[0]\n return annotation\n\n if get_origin(annotation) is None:\n return annotation\n\n non_none = [item for item in get_args(annotation) if item is not type(None)]\n if len(non_none) == 1 and len(non_none) != len(get_args(annotation)):\n return non_none[0]\n return annotation\n\n @classmethod\n def _is_object_like_annotation(cls, annotation: Any) -> bool:\n \"\"\"Return True when the annotation represents a dict-like payload.\"\"\"\n annotation = cls._unwrap_optional_annotation(annotation)\n origin = get_origin(annotation)\n if origin is dict:\n return True\n return annotation is dict or (isinstance(annotation, type) and issubclass(annotation, BaseModel))\n\n @classmethod\n def _should_include_tool_argument(cls, model_field: Any, value: Any) -> bool:\n \"\"\"Omit blank optional values so MCP server defaults remain intact.\"\"\"\n if value is None:\n return False\n\n if model_field.is_required():\n return True\n\n if isinstance(value, str) and value == \"\":\n return False\n\n return not (\n value == {} and model_field.default is None and cls._is_object_like_annotation(model_field.annotation)\n )\n\n def _build_tool_kwargs(self, args_schema: type[BaseModel]) -> dict[str, Any]:\n \"\"\"Collect tool kwargs from component inputs, omitting blank optional values.\"\"\"\n kwargs: dict[str, Any] = {}\n for arg_name, model_field in args_schema.model_fields.items():\n value = getattr(self, arg_name, None)\n if isinstance(value, Message):\n value = value.text\n\n if self._should_include_tool_argument(model_field, value):\n kwargs[arg_name] = value\n\n return kwargs\n\n def get_inputs_for_all_tools(self, tools: list) -> dict:\n \"\"\"Get input schemas for all tools.\"\"\"\n inputs = {}\n for tool in tools:\n if not tool or not hasattr(tool, \"name\"):\n continue\n try:\n langflow_inputs = schema_to_langflow_inputs(tool.args_schema)\n inputs[tool.name] = langflow_inputs\n except (AttributeError, ValueError, TypeError, KeyError) as e:\n msg = f\"Error getting inputs for tool {getattr(tool, 'name', 'unknown')}: {e!s}\"\n logger.exception(msg)\n continue\n return inputs\n\n def remove_non_default_keys(self, build_config: dict) -> None:\n \"\"\"Remove non-default keys from the build config.\"\"\"\n for key in list(build_config.keys()):\n if key not in self.default_keys:\n build_config.pop(key)\n\n async def _update_tool_config(self, build_config: dict, tool_name: str) -> None:\n \"\"\"Update tool configuration with proper error handling.\"\"\"\n if not self.tools:\n self.tools, build_config[\"mcp_server\"][\"value\"] = await self.update_tool_list()\n\n if not tool_name:\n return\n\n tool_obj = next((tool for tool in self.tools if tool.name == tool_name), None)\n if not tool_obj:\n msg = f\"Tool {tool_name} not found in available tools: {self.tools}\"\n self.remove_non_default_keys(build_config)\n build_config[\"tool\"][\"value\"] = \"\"\n await logger.awarning(msg)\n return\n\n try:\n # Store current values before removing inputs (only for the current tool)\n current_values = {}\n for key, value in build_config.items():\n if key not in self.default_keys and isinstance(value, dict) and \"value\" in value:\n current_values[key] = value[\"value\"]\n\n # Remove ALL non-default keys (all previous tool inputs)\n self.remove_non_default_keys(build_config)\n\n # Get and validate new inputs for the selected tool\n self.schema_inputs = await self._validate_schema_inputs(tool_obj)\n if not self.schema_inputs:\n msg = f\"No input parameters to configure for tool '{tool_name}'\"\n await logger.ainfo(msg)\n return\n\n # Add new inputs to build config for the selected tool only\n for schema_input in self.schema_inputs:\n if not schema_input or not hasattr(schema_input, \"name\"):\n msg = \"Invalid schema input detected, skipping\"\n await logger.awarning(msg)\n continue\n\n try:\n name = schema_input.name\n input_dict = schema_input.to_dict()\n input_dict.setdefault(\"value\", None)\n input_dict.setdefault(\"required\", True)\n\n build_config[name] = input_dict\n\n # Preserve existing value if the parameter name exists in current_values\n if name in current_values:\n build_config[name][\"value\"] = current_values[name]\n\n except (AttributeError, KeyError, TypeError) as e:\n msg = f\"Error processing schema input {schema_input}: {e!s}\"\n await logger.aexception(msg)\n continue\n except ValueError as e:\n msg = f\"Schema validation error for tool {tool_name}: {e!s}\"\n await logger.aexception(msg)\n self.schema_inputs = []\n return\n except (AttributeError, KeyError, TypeError) as e:\n msg = f\"Error updating tool config: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n\n async def build_output(self) -> DataFrame:\n \"\"\"Build output with improved error handling and validation.\"\"\"\n try:\n self.tools, _ = await self.update_tool_list()\n if self.tool != \"\":\n # Set session context for persistent MCP sessions using Langflow session ID\n session_context = self._get_session_context()\n if session_context:\n self.stdio_client.set_session_context(session_context)\n self.streamable_http_client.set_session_context(session_context)\n exec_tool = self._tool_cache[self.tool]\n kwargs = self._build_tool_kwargs(exec_tool.args_schema)\n unflattened_kwargs = maybe_unflatten_dict(kwargs)\n\n output = await exec_tool.coroutine(**unflattened_kwargs)\n if getattr(output, \"isError\", False):\n # isError=True is a FAILED call; treating its content as data makes it look successful.\n error_text = \" \".join(str(item.model_dump().get(\"text\") or \"\") for item in output.content).strip()\n msg = f\"MCP tool '{self.tool}' failed: {error_text or 'no error detail provided'}\"\n raise ValueError(msg)\n tool_content = []\n for item in output.content:\n item_dict = item.model_dump()\n item_dict = self.process_output_item(item_dict)\n tool_content.append(item_dict)\n\n if isinstance(tool_content, list) and all(isinstance(x, dict) for x in tool_content):\n return DataFrame(tool_content)\n return DataFrame(data=tool_content)\n return DataFrame(data=[{\"error\": \"You must select a tool\"}])\n except Exception as e:\n msg = f\"Error in build_output: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n\n def process_output_item(self, item_dict):\n \"\"\"Process the output of a tool.\"\"\"\n if item_dict.get(\"type\") == \"text\":\n text = item_dict.get(\"text\")\n try:\n parsed = json.loads(text)\n # Ensure we always return a dictionary for DataFrame compatibility\n if isinstance(parsed, dict):\n return parsed\n # Wrap non-dict parsed values in a dictionary\n return {\"text\": text, \"parsed_value\": parsed, \"type\": \"text\"} # noqa: TRY300\n except json.JSONDecodeError:\n return item_dict\n return item_dict\n\n def _get_session_context(self) -> str | None:\n \"\"\"Get the Langflow session ID for MCP session caching.\"\"\"\n # Try to get session ID from the component's execution context\n if hasattr(self, \"graph\") and hasattr(self.graph, \"session_id\"):\n session_id = self.graph.session_id\n # Include server name to ensure different servers get different sessions\n server_name = \"\"\n mcp_server = getattr(self, \"mcp_server\", None)\n if isinstance(mcp_server, dict):\n server_name = mcp_server.get(\"name\", \"\")\n elif mcp_server:\n server_name = str(mcp_server)\n return f\"{session_id}_{server_name}\" if session_id else None\n return None\n\n async def _get_tools(self):\n \"\"\"Load tools for the agent toolkit; always refresh from ``update_tool_list``.\n\n ``_not_load_actions`` only applies to UI build_config flows (tool dropdown). Agent\n runs must always bind the current tool list (including after header/tweak changes).\n\n A short-lived TTL cache (``TOOL_TTL_SECS``, header-hash-keyed) skips the MCP\n round-trip when the same auth context is re-queried quickly (e.g. parallel agent\n steps sharing the same tweaked headers). The cache is per component lineage (including\n isolated invocation copies) and bounded by ``TOOL_TTL_MAX_ENTRIES``; it is distinct from\n the \"Use Cached Server\" (``use_cache``) toggle which controls the shared cross-request cache.\n \"\"\"\n mcp_server = getattr(self, \"mcp_server\", None)\n srv = mcp_server.get(\"name\") if isinstance(mcp_server, dict) else mcp_server\n\n ttl = self.TOOL_TTL_SECS\n ttl_key = self._mcp_servers_cache_key(srv or \"\") if ttl > 0 and srv else \"\"\n\n # TTL cache lookup + expired-entry eviction.\n if ttl > 0 and ttl_key:\n cached = self._ttl_tool_cache.get(ttl_key)\n if cached is not None:\n ts, cached_tools = cached\n age = time.monotonic() - ts\n if age < ttl:\n await logger.adebug(\n \"MCP _get_tools: TTL cache hit count=%d age=%.1fs server=%r\",\n len(cached_tools),\n age,\n srv,\n )\n return cached_tools\n # Stale — drop it so the size check below stays tight.\n self._ttl_tool_cache.pop(ttl_key, None)\n\n await logger.adebug(\"MCP _get_tools: fetching tool list server=%r\", srv)\n tools, _ = await self.update_tool_list(mcp_server)\n await logger.adebug(\"MCP _get_tools: fetched %d tools server=%r\", len(tools), srv)\n\n # TTL cache store with bounded size (FIFO eviction of the oldest entry).\n if ttl > 0 and ttl_key and tools:\n if len(self._ttl_tool_cache) >= self.TOOL_TTL_MAX_ENTRIES:\n # dict preserves insertion order — pop the oldest entry.\n oldest_key = next(iter(self._ttl_tool_cache))\n self._ttl_tool_cache.pop(oldest_key, None)\n self._ttl_tool_cache[ttl_key] = (time.monotonic(), tools)\n\n return tools\n"
+ "value": "from __future__ import annotations\n\nimport asyncio\nimport hashlib\nimport json\nimport time\nimport uuid\nfrom types import UnionType\nfrom typing import Any, cast, get_args, get_origin\n\nfrom langchain_core.tools import StructuredTool # noqa: TC002\nfrom pydantic import BaseModel\n\nfrom lfx.base.agents.utils import maybe_unflatten_dict, safe_cache_get, safe_cache_set\nfrom lfx.base.mcp.util import (\n MCPStdioClient,\n MCPStreamableHttpClient,\n config_uses_global_variables,\n update_tools,\n)\nfrom lfx.base.tools.constants import TOOL_OUTPUT_DISPLAY_NAME, TOOL_OUTPUT_NAME\nfrom lfx.custom.custom_component.component_with_cache import ComponentWithCache\nfrom lfx.inputs.inputs import InputTypes # noqa: TC001\nfrom lfx.io import BoolInput, DictInput, DropdownInput, FloatInput, McpInput, MessageTextInput, Output\nfrom lfx.io.schema import schema_to_langflow_inputs\nfrom lfx.log.logger import logger\nfrom lfx.schema.dataframe import DataFrame\nfrom lfx.schema.message import Message\nfrom lfx.services.deps import get_storage_service, session_scope\n\n\ndef resolve_mcp_config(\n server_name: str, # noqa: ARG001\n server_config_from_value: dict | None,\n server_config_from_db: dict | None,\n) -> dict | None:\n \"\"\"Resolve MCP server config with proper precedence.\n\n Resolves the configuration for an MCP server with the following precedence:\n 1. Database config (takes priority) - ensures edits are reflected\n 2. Config from value/tweaks (fallback) - allows REST API to provide config for new servers\n\n Args:\n server_name: Name of the MCP server\n server_config_from_value: Config provided via value/tweaks (optional)\n server_config_from_db: Config from database (optional)\n\n Returns:\n Final config to use (DB takes priority, falls back to value)\n Returns None if no config found in either location\n \"\"\"\n if server_config_from_db:\n return server_config_from_db\n return server_config_from_value\n\n\n# TODO(legacy-cleanup): This file is ~800 lines, over the 500-line guideline. Split\n# helper functions (resolve_mcp_config, connection resolution) from the MCPToolsComponent\n# orchestration logic in a follow-up PR.\nclass MCPToolsComponent(ComponentWithCache):\n \"\"\"MCP Tools component.\n\n Behaviour notes:\n - Stale agent tools vs server were caused by Langflow caching the Toolset output\n (``Output.cache=True`` plus the persisted ``output.value`` in saved flow JSON), not\n only by the user-facing \"Use Cached Server\" (``use_cache``) toggle. ``_build_tool_output``\n declares the Toolset output with ``cache=False`` and ``map_outputs`` overrides the\n persisted value for existing flows so every run resolves a fresh tool list.\n - ``update_tool_list`` is serialized with an ``asyncio.Lock`` so concurrent calls do not\n share the same Streamable HTTP client session; overlapping POST/DELETE cycles otherwise\n surface as HTTP 404 and the MCP SDK reports ``Session terminated``.\n - All diagnostic logs are at DEBUG level to avoid swamping logs on hot paths (an agent\n may call ``_get_tools`` per step). Header values are never logged; only header *keys*.\n \"\"\"\n\n # Short-lived in-memory cache window (seconds) for ``_get_tools``. When the\n # same header-hash key is requested again within this window the cached tool\n # list is reused so parallel agent runs that share identical auth don't\n # each pay for a fresh MCP round-trip. Set to ``0`` to disable. This is\n # distinct from the \"Use Cached Server\" (``use_cache``) toggle which only\n # controls the shared cross-request server cache.\n TOOL_TTL_SECS: int = 30\n # Upper bound on the per-component-lineage TTL cache. Oldest entries are evicted\n # when the cap is reached. Keeps memory bounded for flows where the same\n # component handles many rotating auth contexts (e.g. per-tenant tokens).\n TOOL_TTL_MAX_ENTRIES: int = 32\n # Upper bound on the shared cross-request ``servers`` cache. Each\n # (server_name, header-hash) pair is a distinct entry; without a bound a\n # tenant that rotates session tokens would grow this map without limit.\n SHARED_SERVERS_CACHE_MAX_ENTRIES: int = 64\n\n schema_inputs: list = []\n tools: list[StructuredTool] = []\n _not_load_actions: bool = False\n _tool_cache: dict = {}\n _last_selected_server: str | None = None # Cache for the last selected server\n\n def __init__(self, **data) -> None:\n super().__init__(**data)\n # Initialize cache keys to avoid CacheMiss when accessing them\n self._ensure_cache_structure()\n\n # Initialize clients with access to the component cache.\n # Per-component timeout is normalized and applied immediately before MCP calls.\n self.stdio_client: MCPStdioClient = MCPStdioClient(component_cache=self._shared_component_cache)\n self.streamable_http_client: MCPStreamableHttpClient = MCPStreamableHttpClient(\n component_cache=self._shared_component_cache\n )\n # One MCP stdio/streamable client pair per component; concurrent update_tool_list calls\n # otherwise race (session DELETE vs POST) and the MCP SDK surfaces HTTP 404 as \"Session terminated\".\n self._update_tool_list_lock = asyncio.Lock()\n # Per-component-lineage TTL cache for ``_get_tools``:\n # {cache_key: (monotonic_ts, tools)}. Freshly instantiated components get their own\n # dict; ``__deepcopy__`` shares it only with that component's invocation copies.\n # A class-level dict would instead expose entries to every MCPToolsComponent in the\n # process, leaking tool lists across tenants that happen to hash to the same key.\n self._ttl_tool_cache: dict[str, tuple[float, list]] = {}\n\n def __deepcopy__(self, memo: dict) -> MCPToolsComponent:\n \"\"\"Keep the per-component tool cache available to isolated invocation copies.\"\"\"\n component_copy = cast(\"MCPToolsComponent\", super().__deepcopy__(memo))\n # Component tools are deep-copied for every invocation to isolate mutable inputs.\n # Those copies belong to the same component execution lineage, so sharing this\n # bounded, auth-scoped cache preserves its TTL without exposing it to independently\n # instantiated components.\n component_copy._ttl_tool_cache = self._ttl_tool_cache # noqa: SLF001\n return component_copy\n\n def _ensure_cache_structure(self):\n \"\"\"Ensure the cache has the required structure.\"\"\"\n # Check if servers key exists and is not CacheMiss\n servers_value = safe_cache_get(self._shared_component_cache, \"servers\")\n if servers_value is None:\n safe_cache_set(self._shared_component_cache, \"servers\", {})\n\n # Check if last_selected_server key exists and is not CacheMiss\n last_server_value = safe_cache_get(self._shared_component_cache, \"last_selected_server\")\n if last_server_value is None:\n safe_cache_set(self._shared_component_cache, \"last_selected_server\", \"\")\n\n def _normalized_headers_for_cache(self) -> dict[str, str]:\n \"\"\"Component headers as a dict for stable cache keying (auth / tweaks).\"\"\"\n component_headers = getattr(self, \"headers\", None) or []\n if isinstance(component_headers, list):\n return {\n str(item[\"key\"]): str(item[\"value\"])\n for item in component_headers\n if isinstance(item, dict) and \"key\" in item and \"value\" in item\n }\n if isinstance(component_headers, dict):\n return {str(k): str(v) for k, v in component_headers.items()}\n return {}\n\n def _normalize_tool_execution_timeout(self) -> float | None:\n \"\"\"Normalize the timeout input and reject negative values with a field-specific error.\"\"\"\n timeout_value = getattr(self, \"tool_execution_timeout\", 0.0)\n\n if timeout_value in (None, \"\"):\n return None\n\n try:\n val = float(timeout_value)\n except (ValueError, TypeError):\n return None\n\n if val < 0:\n msg = \"Tool Execution Timeout must be greater than or equal to 0.\"\n raise ValueError(msg)\n\n return val if val else None\n\n def _mcp_servers_cache_key(self, server_name: str) -> str:\n \"\"\"Cache key for shared servers map.\n\n Includes the authenticated user, headers, and timeout so tenant/auth/tweak/timeout\n changes get distinct entries.\n \"\"\"\n if not server_name:\n return \"\"\n\n raw_timeout = getattr(self, \"tool_execution_timeout\", 0.0) or 0.0\n normalized_timeout = max(0.0, float(raw_timeout))\n\n hdrs = self._normalized_headers_for_cache()\n\n # Build cache key components\n cache_data = {\n \"headers\": hdrs,\n \"timeout\": normalized_timeout,\n }\n\n user_id = self._mcp_cache_user_id()\n if user_id:\n cache_data[\"user_id\"] = user_id\n\n # Preserve the compact per-instance TTL key when there is no authenticated user.\n # Shared caching is disabled for that case in ``update_tool_list`` below.\n if not hdrs and normalized_timeout == 0.0 and not user_id:\n return server_name\n\n payload = json.dumps(cache_data, sort_keys=True)\n digest = hashlib.sha256(payload.encode()).hexdigest()[:16]\n return f\"{server_name}:{digest}\"\n\n def _mcp_cache_user_id(self) -> str | None:\n \"\"\"Return the authenticated user id without requiring a fully attached graph.\n\n Components are also instantiated without a vertex while the UI builds component\n metadata. Accessing ``self.user_id`` in that state raises, so inspect the backing\n fields directly and fail closed by returning ``None`` when no authenticated scope\n is available.\n \"\"\"\n user_id = getattr(self, \"_user_id\", None)\n if not user_id:\n graph = getattr(getattr(self, \"_vertex\", None), \"graph\", None)\n user_id = getattr(graph, \"user_id\", None)\n return str(user_id) if user_id else None\n\n def _build_tool_output(self) -> Output:\n # Do not cache Toolset output. This is separate from the MCP \"Use Cached Server\" (use_cache)\n # toggle: Langflow's Output.cache defaults to True and was memoizing the first to_toolkit()\n # result, so per-request tweaks/headers never refreshed bound tools even when use_cache=False.\n return Output(\n name=TOOL_OUTPUT_NAME,\n display_name=TOOL_OUTPUT_DISPLAY_NAME,\n method=\"to_toolkit\",\n types=[\"Tool\"],\n cache=False,\n )\n\n def map_outputs(self) -> None:\n \"\"\"Override the persisted ``component_as_tool`` cache flag from saved flow JSON.\n\n ``_build_tool_output`` already returns the output with ``cache=False``, but the\n flow JSON for existing flows often stores ``cache: true`` for ``component_as_tool``\n and that persisted value wins over the declaration. Forcing ``cache=False`` here\n guarantees saved flows also bypass Output memoization and get a fresh tool list\n on every run.\n \"\"\"\n super().map_outputs()\n if TOOL_OUTPUT_NAME in self._outputs_map:\n self._outputs_map[TOOL_OUTPUT_NAME].cache = False\n\n default_keys: list[str] = [\n \"code\",\n \"_type\",\n \"tool_mode\",\n \"tool_placeholder\",\n \"mcp_server\",\n \"tool\",\n \"use_cache\",\n \"verify_ssl\",\n \"headers\",\n \"tool_execution_timeout\",\n ]\n\n display_name = \"MCP Tools\"\n description = \"Connect to an MCP server to use its tools.\"\n documentation: str = \"https://docs.langflow.org/mcp-tools\"\n icon = \"Mcp\"\n name = \"MCPTools\"\n\n inputs = [\n McpInput(\n name=\"mcp_server\",\n display_name=\"MCP Server\",\n info=\"Select the MCP Server that will be used by this component\",\n real_time_refresh=True,\n ),\n BoolInput(\n name=\"use_cache\",\n display_name=\"Use Cached Server\",\n info=(\n \"Enable caching of MCP Server and tools to improve performance. \"\n \"Disable to always fetch fresh tools and server updates.\"\n ),\n value=False,\n advanced=True,\n ),\n BoolInput(\n name=\"verify_ssl\",\n display_name=\"Verify SSL Certificate\",\n info=(\n \"Enable SSL certificate verification for HTTPS connections. \"\n \"Disable only for development/testing with self-signed certificates.\"\n ),\n value=True,\n advanced=True,\n ),\n DictInput(\n name=\"headers\",\n display_name=\"Headers\",\n info=(\n \"HTTP headers to include with MCP server requests. \"\n \"Useful for authentication (e.g., Authorization header). \"\n \"These headers override any headers configured in the MCP server settings.\"\n ),\n advanced=True,\n is_list=True,\n ),\n FloatInput(\n name=\"tool_execution_timeout\",\n display_name=\"Tool Execution Timeout (seconds)\",\n info=(\n \"Maximum time to wait for tool execution before timing out. \"\n \"Supports decimal values for sub-second timeouts (e.g., 0.01 for 10ms). \"\n \"Set to 0 to use the system-configured MCP timeout.\"\n ),\n value=0.0,\n range_spec={\"min\": 0.0, \"max\": 3600.0, \"step\": 0.01},\n real_time_refresh=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"tool\",\n display_name=\"Tool\",\n options=[],\n value=\"\",\n info=\"Select the tool to execute\",\n show=False,\n required=True,\n real_time_refresh=True,\n refresh_button=True,\n ),\n MessageTextInput(\n name=\"tool_placeholder\",\n display_name=\"Tool Placeholder\",\n info=\"Placeholder for the tool\",\n value=\"\",\n show=False,\n # Tool Mode is a capability of the component, not of the selected\n # server. Advertising it up front keeps the toolbar from waiting\n # for the MCP server's tool-discovery request to finish.\n tool_mode=True,\n ),\n ]\n\n outputs = [\n Output(display_name=\"Response\", name=\"response\", method=\"build_output\"),\n ]\n\n async def _validate_schema_inputs(self, tool_obj) -> list[InputTypes]:\n \"\"\"Validate and process schema inputs for a tool.\"\"\"\n try:\n if not tool_obj or not hasattr(tool_obj, \"args_schema\"):\n msg = \"Invalid tool object or missing input schema\"\n raise ValueError(msg)\n\n input_schema = tool_obj.args_schema\n if not input_schema:\n msg = f\"Empty input schema for tool '{tool_obj.name}'\"\n raise ValueError(msg)\n\n schema_inputs = schema_to_langflow_inputs(input_schema)\n if not schema_inputs:\n msg = f\"No input parameters defined for tool '{tool_obj.name}'\"\n await logger.awarning(msg)\n return []\n\n except Exception as e:\n msg = f\"Error validating schema inputs: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n else:\n return schema_inputs\n\n async def _ensure_cached_mcp_stdio_access(self, server_config: dict) -> None:\n \"\"\"Reapply the current stdio policy before returning cached tools.\"\"\"\n try:\n from langflow.api.v2.mcp import ensure_mcp_stdio_access\n from langflow.services.database.models.user.crud import get_user_by_id\n\n from lfx.services.deps import get_settings_service\n except ModuleNotFoundError as e:\n missing_module = e.name or \"\"\n if missing_module != \"langflow\" and not missing_module.startswith(\"langflow.\"):\n raise\n return\n\n async with session_scope() as db:\n if not self.user_id:\n msg = \"User ID is required for fetching MCP tools.\"\n raise ValueError(msg)\n current_user = await get_user_by_id(db, self.user_id)\n\n ensure_mcp_stdio_access(server_config, current_user, get_settings_service().settings)\n\n async def update_tool_list(self, mcp_server_value=None):\n # Accepts mcp_server_value as dict {name, config} or uses self.mcp_server\n mcp_server = mcp_server_value if mcp_server_value is not None else getattr(self, \"mcp_server\", None)\n server_name = None\n server_config_from_value = None\n if isinstance(mcp_server, dict):\n server_name = mcp_server.get(\"name\")\n server_config_from_value = mcp_server.get(\"config\")\n else:\n server_name = mcp_server\n if not server_name:\n self.tools = []\n await logger.adebug(\"MCP update_tool_list: empty server_name, clearing tools\")\n return [], {\"name\": server_name, \"config\": server_config_from_value}\n\n servers_cache_key = self._mcp_servers_cache_key(server_name)\n\n # Check if caching is enabled, default to False. The cross-request cache must never\n # be used without an authenticated tenant scope; the per-instance TTL cache remains\n # available in standalone/UI contexts.\n use_cache = getattr(self, \"use_cache\", False)\n use_shared_cache = use_cache and self._mcp_cache_user_id() is not None\n header_keys = sorted(self._normalized_headers_for_cache().keys())\n await logger.adebug(\n \"MCP update_tool_list: start server=%r use_cache=%s use_shared_cache=%s shared_cache_key=%r header_keys=%s\",\n server_name,\n use_cache,\n use_shared_cache,\n servers_cache_key,\n header_keys,\n )\n\n async with self._update_tool_list_lock:\n # Use shared cache if available and caching is enabled\n cached = None\n if use_shared_cache:\n servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n cached = servers_cache.get(servers_cache_key) if isinstance(servers_cache, dict) else None\n\n if cached is not None:\n try:\n tools_from_cache = cached[\"tools\"]\n server_config_from_value = cached[\"config\"]\n except (TypeError, KeyError, AttributeError) as e:\n # Handle corrupted cache data by clearing it and continuing to fetch fresh tools\n msg = f\"Unable to use cached data for MCP Server{server_name}: {e}\"\n await logger.awarning(msg)\n # Clear the corrupted cache entry\n current_servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(current_servers_cache, dict) and servers_cache_key in current_servers_cache:\n current_servers_cache.pop(servers_cache_key)\n safe_cache_set(self._shared_component_cache, \"servers\", current_servers_cache)\n else:\n try:\n await self._ensure_cached_mcp_stdio_access(server_config_from_value)\n except Exception as e:\n msg = f\"Error updating tool list: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n else:\n self.tools = tools_from_cache\n self.tool_names = [t.name for t in self.tools if hasattr(t, \"name\")]\n self._tool_cache = cached[\"tool_cache\"]\n await logger.adebug(\n \"MCP update_tool_list: shared_servers_cache HIT count=%d server=%r\",\n len(self.tools),\n server_name,\n )\n return self.tools, {\"name\": server_name, \"config\": server_config_from_value}\n\n try:\n # Try to fetch from database first to ensure we have the latest config.\n # This ensures database updates (like editing a server) take effect.\n # When running in LFX standalone mode the full Langflow package and\n # database may not be available — in that case we skip the DB lookup\n # and fall back to the config embedded in the flow (server_config_from_value).\n server_config_from_db = None\n current_user = None\n settings_service = None\n ensure_mcp_stdio_access = None\n try:\n from langflow.api.v2.mcp import ensure_mcp_stdio_access, get_server\n from langflow.services.database.models.user.crud import get_user_by_id\n\n from lfx.services.deps import get_settings_service\n except ModuleNotFoundError as e:\n # Deliberately `except ModuleNotFoundError` (not `except ImportError`): a\n # plain ImportError here means `get_server` / `get_user_by_id` was removed\n # from an installed Langflow — a real API break that should NOT be\n # swallowed as \"standalone mode\". ModuleNotFoundError alone covers the\n # \"Langflow absent\" case.\n #\n # Even within ModuleNotFoundError, only treat this as LFX standalone mode\n # when one of the target Langflow modules is itself missing. Transitive\n # ModuleNotFoundError (e.g. a dependency like sqlmodel failing to import\n # inside langflow.*) indicates a real bug in the full Langflow stack and\n # must surface — otherwise we would silently use a stale flow-embedded\n # config when DB config should have taken precedence.\n missing_module = e.name or \"\"\n is_langflow_standalone = missing_module == \"langflow\" or missing_module.startswith(\"langflow.\")\n if not is_langflow_standalone:\n raise\n await logger.ainfo(\n \"Langflow package not available; using MCP server config from flow value (LFX standalone mode).\"\n )\n else:\n async with session_scope() as db:\n if not self.user_id:\n msg = \"User ID is required for fetching MCP tools.\"\n raise ValueError(msg)\n current_user = await get_user_by_id(db, self.user_id)\n settings_service = get_settings_service()\n\n # Try to get server config from DB/API\n server_config_from_db = await get_server(\n server_name,\n current_user,\n db,\n storage_service=get_storage_service(),\n settings_service=settings_service,\n )\n\n # Resolve config with proper precedence: DB takes priority, falls back to value\n server_config = resolve_mcp_config(\n server_name=server_name,\n server_config_from_value=server_config_from_value,\n server_config_from_db=server_config_from_db,\n )\n\n if not server_config:\n self.tools = []\n await logger.awarning(\n \"MCP update_tool_list: no server_config after resolve server=%r\",\n server_name,\n )\n msg = (\n f\"MCP server '{server_name}' is not configured. \"\n \"Add a server with this name in Settings > MCP Servers before running this flow.\"\n )\n raise ValueError(msg)\n\n # The REST API applies this policy when a stdio server is registered,\n # but imported flows can carry the same process-spawning config in the\n # MCP component value. Reapply the policy to the resolved config at the\n # component boundary before update_tools reaches the subprocess client.\n if ensure_mcp_stdio_access is not None and current_user is not None and settings_service is not None:\n ensure_mcp_stdio_access(server_config, current_user, settings_service.settings)\n\n # Add verify_ssl option to server config if not present\n if \"verify_ssl\" not in server_config:\n verify_ssl = getattr(self, \"verify_ssl\", True)\n server_config[\"verify_ssl\"] = verify_ssl\n\n # Merge headers from component input with server config headers\n # Component headers take precedence over server config headers\n component_headers = getattr(self, \"headers\", None) or []\n if component_headers:\n # Convert list of {\"key\": k, \"value\": v} to dict\n component_headers_dict = {}\n if isinstance(component_headers, list):\n for item in component_headers:\n if isinstance(item, dict) and \"key\" in item and \"value\" in item:\n component_headers_dict[item[\"key\"]] = item[\"value\"]\n elif isinstance(component_headers, dict):\n component_headers_dict = component_headers\n\n if component_headers_dict:\n existing_headers = server_config.get(\"headers\", {}) or {}\n # Ensure existing_headers is a dict (convert from list if needed)\n if isinstance(existing_headers, list):\n existing_dict = {}\n for item in existing_headers:\n if isinstance(item, dict) and \"key\" in item and \"value\" in item:\n existing_dict[item[\"key\"]] = item[\"value\"]\n existing_headers = existing_dict\n merged_headers = {**existing_headers, **component_headers_dict}\n server_config[\"headers\"] = merged_headers\n # Get request_variables from graph context for global variable resolution\n request_variables = None\n end_user_id = None\n if hasattr(self, \"graph\") and self.graph:\n if hasattr(self.graph, \"context\"):\n request_variables = self.graph.context.get(\"request_variables\")\n # Serving-plane end-user id (set by the entry-point scoping); forwarded only\n # to allowlisted internal MCP targets by update_tools (fail-closed).\n end_user_id = getattr(self.graph, \"end_user_id\", None)\n\n # Load global variables only when the config actually references them, so a\n # static config still costs no query -- but a URL-only reference now counts.\n # The load must NOT be skipped just because the request carried overrides: a\n # request that overrides one variable still needs every other referenced\n # variable resolved from the database.\n db_variables: dict[str, str] | None = None\n if config_uses_global_variables(server_config):\n try:\n from lfx.services.deps import get_variable_service\n\n variable_service = get_variable_service()\n # ``get_all_decrypted_variables`` is DB-service-only; the minimal\n # lfx VariableService (now registered by ``lfx serve``) lacks it, so\n # skip cleanly rather than raising into the broad except below.\n if variable_service and hasattr(variable_service, \"get_all_decrypted_variables\"):\n async with session_scope() as db:\n db_variables = await variable_service.get_all_decrypted_variables(\n user_id=self.user_id, session=db\n )\n except Exception as e: # noqa: BLE001\n await logger.awarning(\"Failed to load global variables for MCP component\", exc_info=e)\n\n # Headers may resolve from either source, per-request values winning on\n # conflict (matching ``CustomComponent.get_variable``). Dropping the database\n # side whenever the request carried anything would send an unresolved variable\n # *name* upstream as the header value (#14604).\n #\n # The URL still resolves from the database only, via ``url_variables`` below:\n # request_variables carry the caller's X-Langflow-Global-Var-* values, and a\n # caller must not be able to choose where this flow connects.\n request_variables = {**(db_variables or {}), **(request_variables or {})} or None\n\n await logger.adebug(\n \"MCP update_tool_list: calling update_tools server=%r mode_headers=%s\",\n server_name,\n sorted((server_config.get(\"headers\") or {}).keys())\n if isinstance(server_config.get(\"headers\"), dict)\n else \"list-or-empty\",\n )\n\n timeout = self._normalize_tool_execution_timeout()\n\n _, tool_list, tool_cache = await update_tools(\n server_name=server_name,\n server_config=server_config,\n mcp_stdio_client=self.stdio_client,\n mcp_streamable_http_client=self.streamable_http_client,\n request_variables=request_variables,\n url_variables=db_variables,\n tool_execution_timeout=timeout,\n current_user_id=self.user_id,\n end_user_id=end_user_id,\n )\n\n self.tool_names = [tool.name for tool in tool_list if hasattr(tool, \"name\")]\n self._tool_cache = tool_cache\n self.tools = tool_list\n\n await logger.adebug(\n \"MCP update_tool_list: fetched from MCP count=%d server=%r\",\n len(tool_list),\n server_name,\n )\n\n # Cache the result only if caching is enabled\n if use_shared_cache:\n cache_data = {\n \"tools\": tool_list,\n \"tool_names\": self.tool_names,\n \"tool_cache\": tool_cache,\n \"config\": server_config,\n }\n\n # Safely update the servers cache with bounded size (FIFO eviction).\n current_servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(current_servers_cache, dict):\n # Because the cache key now includes a header hash, a tenant that\n # rotates session tokens would grow this map without bound. Drop\n # the oldest entry when over the limit.\n max_entries = self.SHARED_SERVERS_CACHE_MAX_ENTRIES\n while (\n len(current_servers_cache) >= max_entries and servers_cache_key not in current_servers_cache\n ):\n oldest_key = next(iter(current_servers_cache))\n current_servers_cache.pop(oldest_key, None)\n current_servers_cache[servers_cache_key] = cache_data\n safe_cache_set(self._shared_component_cache, \"servers\", current_servers_cache)\n await logger.adebug(\n \"MCP update_tool_list: wrote shared_servers_cache key=%r size=%d\",\n servers_cache_key,\n len(current_servers_cache),\n )\n\n except (TimeoutError, asyncio.TimeoutError) as e:\n msg = (\n f\"Timeout updating tool list: {e!s}. \"\n \"Raise ``LANGFLOW_MCP_SERVER_TIMEOUT`` for the deployment if the MCP \"\n \"server legitimately needs more time to respond.\"\n )\n await logger.aexception(msg)\n raise TimeoutError(msg) from e\n except Exception as e:\n msg = f\"Error updating tool list: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n else:\n return tool_list, {\"name\": server_name, \"config\": server_config}\n\n async def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None) -> dict:\n \"\"\"Toggle the visibility of connection-specific fields based on the selected mode.\"\"\"\n try:\n is_refresh = bool(build_config.get(\"is_refresh\", False))\n if field_name == \"tool\":\n try:\n # Always refresh tools when cache is disabled, or when tools list is empty\n # This ensures database edits are reflected immediately when cache is disabled\n use_cache = getattr(self, \"use_cache\", False)\n if is_refresh:\n self.tools = []\n if is_refresh or len(self.tools) == 0 or not use_cache:\n try:\n self.tools, build_config[\"mcp_server\"][\"value\"] = await self.update_tool_list()\n build_config[\"tool\"][\"options\"] = [tool.name for tool in self.tools]\n build_config[\"tool\"][\"placeholder\"] = \"Select a tool\"\n except (TimeoutError, asyncio.TimeoutError) as e:\n msg = f\"Timeout updating tool list: {e!s}\"\n await logger.aexception(msg)\n if not build_config[\"tools_metadata\"][\"show\"]:\n build_config[\"tool\"][\"show\"] = True\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"value\"] = \"\"\n build_config[\"tool\"][\"placeholder\"] = msg\n else:\n build_config[\"tool\"][\"show\"] = False\n except ValueError as e:\n msg = f\"Error updating tool list: {e!s}\"\n await logger.aexception(msg)\n if not build_config[\"tools_metadata\"][\"show\"]:\n build_config[\"tool\"][\"show\"] = True\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"value\"] = \"\"\n build_config[\"tool\"][\"placeholder\"] = msg\n else:\n build_config[\"tool\"][\"show\"] = False\n\n if field_value == \"\":\n return build_config\n tool_obj = None\n for tool in self.tools:\n if tool.name == field_value:\n tool_obj = tool\n break\n if tool_obj is None:\n msg = f\"Tool {field_value} not found in available tools: {self.tools}\"\n await logger.awarning(msg)\n return build_config\n await self._update_tool_config(build_config, field_value)\n except Exception as e:\n build_config[\"tool\"][\"options\"] = []\n msg = f\"Failed to update tools: {e!s}\"\n raise ValueError(msg) from e\n else:\n return build_config\n elif field_name == \"mcp_server\":\n if not field_value:\n build_config[\"tool\"][\"show\"] = False\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"value\"] = \"\"\n build_config[\"tool\"][\"placeholder\"] = \"\"\n build_config[\"tool_placeholder\"][\"tool_mode\"] = True\n self.remove_non_default_keys(build_config)\n return build_config\n\n build_config[\"tool_placeholder\"][\"tool_mode\"] = True\n\n current_server_name = field_value.get(\"name\") if isinstance(field_value, dict) else field_value\n build_config_server_value = build_config.get(\"mcp_server\", {}).get(\"value\")\n build_config_server_name = (\n build_config_server_value.get(\"name\")\n if isinstance(build_config_server_value, dict)\n else build_config_server_value\n )\n servers_cache_key_ui = self._mcp_servers_cache_key(current_server_name) if current_server_name else \"\"\n _last_selected_server = safe_cache_get(self._shared_component_cache, \"last_selected_server\", \"\")\n # Only treat as a server change if there was a previous server selection.\n # Cold cache (_last_selected_server=\"\") on initial flow load is NOT a server change —\n # the user didn't switch anything, the backend just hasn't seen this component yet.\n server_changed = bool(\n (_last_selected_server and current_server_name != _last_selected_server)\n or (build_config_server_name and current_server_name != build_config_server_name)\n )\n\n # Determine if \"Tool Mode\" is active by checking if the tool dropdown is hidden.\n is_in_tool_mode = build_config[\"tools_metadata\"][\"show\"]\n\n # Get use_cache setting to determine if we should use cached data\n use_cache = getattr(self, \"use_cache\", False)\n has_shared_cache_scope = self._mcp_cache_user_id() is not None\n use_shared_cache = use_cache and has_shared_cache_scope\n\n # Fast path: if server didn't change and we already have options, keep them as-is\n # BUT only if caching is enabled, we're in tool mode, or it's the initial load\n existing_options = build_config.get(\"tool\", {}).get(\"options\") or []\n if not is_refresh and not server_changed and existing_options:\n # In non-tool mode with cache disabled, skip the fast path to force refresh\n # BUT on initial load (cold cache), always preserve saved options from the flow\n if not is_in_tool_mode and not use_cache and _last_selected_server:\n pass # Continue to refresh logic below (user-initiated with cache disabled)\n else:\n if not is_in_tool_mode:\n build_config[\"tool\"][\"show\"] = True\n safe_cache_set(self._shared_component_cache, \"last_selected_server\", current_server_name)\n return build_config\n\n # To avoid unnecessary updates, only proceed if the server has actually changed\n # OR if caching is disabled (to force refresh in non-tool mode)\n if (\n not is_refresh\n and (_last_selected_server in (current_server_name, \"\"))\n and build_config[\"tool\"][\"show\"]\n and use_shared_cache\n ):\n if current_server_name:\n servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(servers_cache, dict):\n cached = servers_cache.get(servers_cache_key_ui)\n if cached is not None and cached.get(\"tool_names\"):\n cached_tools = cached[\"tool_names\"]\n current_tools = build_config[\"tool\"][\"options\"]\n if current_tools == cached_tools:\n return build_config\n else:\n return build_config\n safe_cache_set(self._shared_component_cache, \"last_selected_server\", current_server_name)\n\n # When cache is disabled, clear any cached data for this server\n # This ensures we always fetch fresh data from the database\n if (is_refresh or not use_cache) and current_server_name and has_shared_cache_scope:\n servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(servers_cache, dict) and servers_cache_key_ui in servers_cache:\n servers_cache.pop(servers_cache_key_ui)\n safe_cache_set(self._shared_component_cache, \"servers\", servers_cache)\n\n # Check if tools are already cached for this server before clearing\n cached_tools = None\n if current_server_name and use_shared_cache and not is_refresh:\n servers_cache = safe_cache_get(self._shared_component_cache, \"servers\", {})\n if isinstance(servers_cache, dict):\n cached = servers_cache.get(servers_cache_key_ui)\n if cached is not None:\n try:\n cached_tools = cached[\"tools\"]\n self.tools = cached_tools\n self.tool_names = cached[\"tool_names\"]\n self._tool_cache = cached[\"tool_cache\"]\n except (TypeError, KeyError, AttributeError) as e:\n # Handle corrupted cache data by ignoring it\n msg = f\"Unable to use cached data for MCP Server,{current_server_name}: {e}\"\n await logger.awarning(msg)\n cached_tools = None\n\n # Clear tools when cache is disabled OR when we don't have cached tools\n # This ensures fresh tools are fetched after database edits\n if is_refresh or not cached_tools or not use_cache:\n self.tools = [] # Clear previous tools to force refresh\n\n # Clear previous tool inputs if:\n # 1. Server actually changed\n # 2. Cache is disabled (meaning tool list will be refreshed)\n if is_refresh or server_changed or not use_cache:\n self.remove_non_default_keys(build_config)\n\n # Only show the tool dropdown if not in tool_mode\n if not is_in_tool_mode:\n build_config[\"tool\"][\"show\"] = True\n if cached_tools:\n # Use cached tools to populate options immediately\n build_config[\"tool\"][\"options\"] = [tool.name for tool in cached_tools]\n build_config[\"tool\"][\"placeholder\"] = \"Select a tool\"\n else:\n # Actually fetch tools now instead of deferring to a frontend callback.\n # The frontend has no reliable mechanism to trigger a second\n # update_build_config call for the \"tool\" field after this response,\n # so we must populate the options here.\n try:\n self.tools, build_config[\"mcp_server\"][\"value\"] = await self.update_tool_list(\n mcp_server_value=field_value\n )\n build_config[\"tool\"][\"options\"] = [tool.name for tool in self.tools]\n build_config[\"tool\"][\"placeholder\"] = \"Select a tool\"\n except (TimeoutError, asyncio.TimeoutError) as e:\n msg = f\"Timeout loading tools for MCP server: {e!s}\"\n await logger.aexception(msg)\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"placeholder\"] = \"Timeout on MCP server\"\n except (ValueError, ImportError, ConnectionError, OSError, RuntimeError) as e:\n msg = f\"Error loading tools for MCP server: {e!s}\"\n await logger.aexception(msg)\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"placeholder\"] = (\n \"Error on MCP Server\" if \"'NoneType' object has no attribute 'id'\" in msg else msg\n )\n # Force a value refresh only when the user genuinely switched servers.\n # server_changed is only True for real user-initiated changes (not initial load).\n if server_changed:\n build_config[\"tool\"][\"value\"] = uuid.uuid4()\n else:\n # Keep the tool dropdown hidden if in tool_mode\n self._not_load_actions = True\n build_config[\"tool\"][\"show\"] = False\n\n elif field_name == \"tool_mode\":\n build_config[\"tool\"][\"placeholder\"] = \"\"\n build_config[\"tool\"][\"show\"] = not bool(field_value) and bool(build_config[\"mcp_server\"])\n self.remove_non_default_keys(build_config)\n self.tool = build_config[\"tool\"][\"value\"]\n if field_value:\n self._not_load_actions = True\n else:\n build_config[\"tool\"][\"value\"] = uuid.uuid4()\n build_config[\"tool\"][\"show\"] = True\n # Fetch tools immediately instead of showing \"Loading tools...\"\n try:\n self.tools, build_config[\"mcp_server\"][\"value\"] = await self.update_tool_list()\n build_config[\"tool\"][\"options\"] = [tool.name for tool in self.tools]\n build_config[\"tool\"][\"placeholder\"] = \"Select a tool\"\n except (TimeoutError, asyncio.TimeoutError) as e:\n msg = f\"Timeout loading tools when toggling tool mode: {e!s}\"\n await logger.aexception(msg)\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"placeholder\"] = msg\n except (ValueError, ImportError, ConnectionError, OSError, RuntimeError) as e:\n msg = f\"Error loading tools when toggling tool mode: {e!s}\"\n await logger.aexception(msg)\n build_config[\"tool\"][\"options\"] = []\n build_config[\"tool\"][\"placeholder\"] = msg\n elif field_name == \"tool_execution_timeout\":\n try:\n val = float(field_value) if field_value not in (None, \"\") else 0.0\n except (ValueError, TypeError):\n val = 0.0\n if val < 0:\n build_config[\"tool_execution_timeout\"][\"placeholder\"] = (\n \"⚠ Value must be ≥ 0. Negative timeouts cause immediate failures.\"\n )\n build_config[\"tool_execution_timeout\"][\"value\"] = 0.0\n else:\n build_config[\"tool_execution_timeout\"][\"placeholder\"] = \"\"\n elif field_name == \"tools_metadata\":\n self._not_load_actions = False\n\n except Exception as e:\n msg = f\"Error in update_build_config: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n else:\n return build_config\n\n @staticmethod\n def _unwrap_optional_annotation(annotation: Any) -> Any:\n \"\"\"Remove a single None branch from a union annotation.\"\"\"\n if isinstance(annotation, UnionType):\n non_none = [item for item in get_args(annotation) if item is not type(None)]\n if len(non_none) == 1:\n return non_none[0]\n return annotation\n\n if get_origin(annotation) is None:\n return annotation\n\n non_none = [item for item in get_args(annotation) if item is not type(None)]\n if len(non_none) == 1 and len(non_none) != len(get_args(annotation)):\n return non_none[0]\n return annotation\n\n @classmethod\n def _is_object_like_annotation(cls, annotation: Any) -> bool:\n \"\"\"Return True when the annotation represents a dict-like payload.\"\"\"\n annotation = cls._unwrap_optional_annotation(annotation)\n origin = get_origin(annotation)\n if origin is dict:\n return True\n return annotation is dict or (isinstance(annotation, type) and issubclass(annotation, BaseModel))\n\n @classmethod\n def _should_include_tool_argument(cls, model_field: Any, value: Any) -> bool:\n \"\"\"Omit blank optional values so MCP server defaults remain intact.\"\"\"\n if value is None:\n return False\n\n if model_field.is_required():\n return True\n\n if isinstance(value, str) and value == \"\":\n return False\n\n return not (\n value == {} and model_field.default is None and cls._is_object_like_annotation(model_field.annotation)\n )\n\n def _build_tool_kwargs(self, args_schema: type[BaseModel]) -> dict[str, Any]:\n \"\"\"Collect tool kwargs from component inputs, omitting blank optional values.\"\"\"\n kwargs: dict[str, Any] = {}\n for arg_name, model_field in args_schema.model_fields.items():\n value = getattr(self, arg_name, None)\n if isinstance(value, Message):\n value = value.text\n\n if self._should_include_tool_argument(model_field, value):\n kwargs[arg_name] = value\n\n return kwargs\n\n def get_inputs_for_all_tools(self, tools: list) -> dict:\n \"\"\"Get input schemas for all tools.\"\"\"\n inputs = {}\n for tool in tools:\n if not tool or not hasattr(tool, \"name\"):\n continue\n try:\n langflow_inputs = schema_to_langflow_inputs(tool.args_schema)\n inputs[tool.name] = langflow_inputs\n except (AttributeError, ValueError, TypeError, KeyError) as e:\n msg = f\"Error getting inputs for tool {getattr(tool, 'name', 'unknown')}: {e!s}\"\n logger.exception(msg)\n continue\n return inputs\n\n def remove_non_default_keys(self, build_config: dict) -> None:\n \"\"\"Remove non-default keys from the build config.\"\"\"\n for key in list(build_config.keys()):\n if key not in self.default_keys:\n build_config.pop(key)\n\n async def _update_tool_config(self, build_config: dict, tool_name: str) -> None:\n \"\"\"Update tool configuration with proper error handling.\"\"\"\n if not self.tools:\n self.tools, build_config[\"mcp_server\"][\"value\"] = await self.update_tool_list()\n\n if not tool_name:\n return\n\n tool_obj = next((tool for tool in self.tools if tool.name == tool_name), None)\n if not tool_obj:\n msg = f\"Tool {tool_name} not found in available tools: {self.tools}\"\n self.remove_non_default_keys(build_config)\n build_config[\"tool\"][\"value\"] = \"\"\n await logger.awarning(msg)\n return\n\n try:\n # Store current values before removing inputs (only for the current tool)\n current_values = {}\n for key, value in build_config.items():\n if key not in self.default_keys and isinstance(value, dict) and \"value\" in value:\n current_values[key] = value[\"value\"]\n\n # Remove ALL non-default keys (all previous tool inputs)\n self.remove_non_default_keys(build_config)\n\n # Get and validate new inputs for the selected tool\n self.schema_inputs = await self._validate_schema_inputs(tool_obj)\n if not self.schema_inputs:\n msg = f\"No input parameters to configure for tool '{tool_name}'\"\n await logger.ainfo(msg)\n return\n\n # Add new inputs to build config for the selected tool only\n for schema_input in self.schema_inputs:\n if not schema_input or not hasattr(schema_input, \"name\"):\n msg = \"Invalid schema input detected, skipping\"\n await logger.awarning(msg)\n continue\n\n try:\n name = schema_input.name\n input_dict = schema_input.to_dict()\n input_dict.setdefault(\"value\", None)\n input_dict.setdefault(\"required\", True)\n\n build_config[name] = input_dict\n\n # Preserve existing value if the parameter name exists in current_values\n if name in current_values:\n build_config[name][\"value\"] = current_values[name]\n\n except (AttributeError, KeyError, TypeError) as e:\n msg = f\"Error processing schema input {schema_input}: {e!s}\"\n await logger.aexception(msg)\n continue\n except ValueError as e:\n msg = f\"Schema validation error for tool {tool_name}: {e!s}\"\n await logger.aexception(msg)\n self.schema_inputs = []\n return\n except (AttributeError, KeyError, TypeError) as e:\n msg = f\"Error updating tool config: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n\n async def build_output(self) -> DataFrame:\n \"\"\"Build output with improved error handling and validation.\"\"\"\n try:\n self.tools, _ = await self.update_tool_list()\n if self.tool != \"\":\n # Set session context for persistent MCP sessions using Langflow session ID\n session_context = self._get_session_context()\n if session_context:\n self.stdio_client.set_session_context(session_context)\n self.streamable_http_client.set_session_context(session_context)\n exec_tool = self._tool_cache[self.tool]\n kwargs = self._build_tool_kwargs(exec_tool.args_schema)\n unflattened_kwargs = maybe_unflatten_dict(kwargs)\n\n output = await exec_tool.coroutine(**unflattened_kwargs)\n if getattr(output, \"isError\", False):\n # isError=True is a FAILED call; treating its content as data makes it look successful.\n error_text = \" \".join(str(item.model_dump().get(\"text\") or \"\") for item in output.content).strip()\n msg = f\"MCP tool '{self.tool}' failed: {error_text or 'no error detail provided'}\"\n raise ValueError(msg)\n tool_content = []\n for item in output.content:\n item_dict = item.model_dump()\n item_dict = self.process_output_item(item_dict)\n tool_content.append(item_dict)\n\n if isinstance(tool_content, list) and all(isinstance(x, dict) for x in tool_content):\n return DataFrame(tool_content)\n return DataFrame(data=tool_content)\n return DataFrame(data=[{\"error\": \"You must select a tool\"}])\n except Exception as e:\n msg = f\"Error in build_output: {e!s}\"\n await logger.aexception(msg)\n raise ValueError(msg) from e\n\n def process_output_item(self, item_dict):\n \"\"\"Process the output of a tool.\"\"\"\n if item_dict.get(\"type\") == \"text\":\n text = item_dict.get(\"text\")\n try:\n parsed = json.loads(text)\n # Ensure we always return a dictionary for DataFrame compatibility\n if isinstance(parsed, dict):\n return parsed\n # Wrap non-dict parsed values in a dictionary\n return {\"text\": text, \"parsed_value\": parsed, \"type\": \"text\"} # noqa: TRY300\n except json.JSONDecodeError:\n return item_dict\n return item_dict\n\n def _get_session_context(self) -> str | None:\n \"\"\"Get the Langflow session ID for MCP session caching.\"\"\"\n # Try to get session ID from the component's execution context\n if hasattr(self, \"graph\") and hasattr(self.graph, \"session_id\"):\n session_id = self.graph.session_id\n # Include server name to ensure different servers get different sessions\n server_name = \"\"\n mcp_server = getattr(self, \"mcp_server\", None)\n if isinstance(mcp_server, dict):\n server_name = mcp_server.get(\"name\", \"\")\n elif mcp_server:\n server_name = str(mcp_server)\n return f\"{session_id}_{server_name}\" if session_id else None\n return None\n\n async def _get_tools(self):\n \"\"\"Load tools for the agent toolkit; always refresh from ``update_tool_list``.\n\n ``_not_load_actions`` only applies to UI build_config flows (tool dropdown). Agent\n runs must always bind the current tool list (including after header/tweak changes).\n\n A short-lived TTL cache (``TOOL_TTL_SECS``, header-hash-keyed) skips the MCP\n round-trip when the same auth context is re-queried quickly (e.g. parallel agent\n steps sharing the same tweaked headers). The cache is per component lineage (including\n isolated invocation copies) and bounded by ``TOOL_TTL_MAX_ENTRIES``; it is distinct from\n the \"Use Cached Server\" (``use_cache``) toggle which controls the shared cross-request cache.\n \"\"\"\n mcp_server = getattr(self, \"mcp_server\", None)\n srv = mcp_server.get(\"name\") if isinstance(mcp_server, dict) else mcp_server\n\n ttl = self.TOOL_TTL_SECS\n ttl_key = self._mcp_servers_cache_key(srv or \"\") if ttl > 0 and srv else \"\"\n\n # TTL cache lookup + expired-entry eviction.\n if ttl > 0 and ttl_key:\n cached = self._ttl_tool_cache.get(ttl_key)\n if cached is not None:\n ts, cached_tools = cached\n age = time.monotonic() - ts\n if age < ttl:\n await logger.adebug(\n \"MCP _get_tools: TTL cache hit count=%d age=%.1fs server=%r\",\n len(cached_tools),\n age,\n srv,\n )\n return cached_tools\n # Stale — drop it so the size check below stays tight.\n self._ttl_tool_cache.pop(ttl_key, None)\n\n await logger.adebug(\"MCP _get_tools: fetching tool list server=%r\", srv)\n tools, _ = await self.update_tool_list(mcp_server)\n await logger.adebug(\"MCP _get_tools: fetched %d tools server=%r\", len(tools), srv)\n\n # TTL cache store with bounded size (FIFO eviction of the oldest entry).\n if ttl > 0 and ttl_key and tools:\n if len(self._ttl_tool_cache) >= self.TOOL_TTL_MAX_ENTRIES:\n # dict preserves insertion order — pop the oldest entry.\n oldest_key = next(iter(self._ttl_tool_cache))\n self._ttl_tool_cache.pop(oldest_key, None)\n self._ttl_tool_cache[ttl_key] = (time.monotonic(), tools)\n\n return tools\n"
},
"headers": {
"_input_type": "DictInput",
@@ -2585,7 +2551,7 @@
"api_editable": false,
"display_name": "OpenAI API Base",
"dynamic": false,
- "info": "Must end with /v1 (for example http://openrag-backend:8000/v1). Bound to OPENRAG_LLM_BASE_URL at runtime. Same URL as chat.",
+ "info": "Bound to OPENRAG_LLM_BASE_URL at runtime. It is either the public /v1 base or the private router base. Same URL as chat.",
"list": false,
"list_add_label": "Add More",
"load_from_db": true,
@@ -2772,7 +2738,7 @@
],
"frozen": false,
"icon": "OpenSearch",
- "last_updated": "2026-09-01T13:59:27.213Z",
+ "last_updated": "2026-09-08T21:06:51.867Z",
"legacy": false,
"metadata": {
"code_hash": "a3727d7c66eb",
@@ -2831,7 +2797,7 @@
"value": "1098eea1-6649-4e1d-aed1-b77249fb8dd0"
},
"_frontend_node_folder_id": {
- "value": "fbc33683-53fb-4a7b-b1c8-505dcae74674"
+ "value": "7ff6c353-e65b-4821-9940-b18a52bf532b"
},
"_type": "Component",
"auth_mode": {
@@ -3531,7 +3497,6 @@
"type": "tools",
"value": [
{
- "_uniqueId": "search_documents_search_documents_0",
"approval_actions": [],
"args": {
"search_query": {
@@ -3552,7 +3517,6 @@
]
},
{
- "_uniqueId": "raw_search_raw_search_1",
"approval_actions": [],
"args": {
"search_query": {
@@ -3573,7 +3537,6 @@
]
},
{
- "_uniqueId": "as_vector_store_as_vector_store_2",
"approval_actions": [],
"args": {
"search_query": {
@@ -3793,7 +3756,7 @@
"api_editable": false,
"display_name": "OpenAI API Base",
"dynamic": false,
- "info": "Must end with /v1 (for example http://openrag-backend:8000/v1). Bound to OPENRAG_LLM_BASE_URL at runtime. Same URL as embeddings.",
+ "info": "Bound to OPENRAG_LLM_BASE_URL at runtime. It is either the public /v1 base or the private router base. Same URL as embeddings.",
"list": false,
"list_add_label": "Add More",
"load_from_db": true,
@@ -4042,20 +4005,20 @@
}
],
"viewport": {
- "x": -3.0935806849109895,
- "y": -361.77141497237756,
- "zoom": 0.4342296476657653
+ "x": -111.32170987938878,
+ "y": -588.5599385922874,
+ "zoom": 0.5590566540681183
}
},
"description": "OpenRAG OpenSearch Agent",
"endpoint_name": null,
"id": "1098eea1-6649-4e1d-aed1-b77249fb8dd0",
"is_component": false,
- "last_tested_version": "0.11.6",
+ "last_tested_version": "1.12.0",
"locked": true,
"name": "OpenRAG OpenSearch Agent Flow",
"tags": [
"assistants",
"agents"
]
-}
+}
\ No newline at end of file
diff --git a/flows/openrag_nudges.json b/flows/openrag_nudges.json
index dea4e3c48..9219cafb8 100644
--- a/flows/openrag_nudges.json
+++ b/flows/openrag_nudges.json
@@ -227,26 +227,21 @@
"display_name": "Prompt Template",
"documentation": "https://docs.langflow.org/components-prompts",
"edited": false,
- "error": null,
"field_order": [
"template",
"use_double_brackets",
"tool_placeholder"
],
"frozen": false,
- "full_path": null,
"icon": "prompts",
- "is_composition": null,
- "is_input": null,
- "is_output": null,
"legacy": false,
"metadata": {
- "code_hash": "3d3fd7b8a36f",
+ "code_hash": "e3714ffe5d15",
"dependencies": {
"dependencies": [
{
"name": "lfx",
- "version": "0.4.0"
+ "version": "1.12.0"
}
],
"total_dependencies": 1
@@ -254,7 +249,6 @@
"module": "custom_components.prompt_template"
},
"minimized": false,
- "name": "",
"output_types": [],
"outputs": [
{
@@ -277,12 +271,11 @@
}
],
"pinned": false,
- "priority": null,
- "replacement": null,
"template": {
"_type": "Component",
"code": {
"advanced": true,
+ "api_editable": false,
"dynamic": true,
"fileTypes": [],
"file_path": "",
@@ -297,10 +290,11 @@
"show": true,
"title_case": false,
"type": "code",
- "value": "from typing import Any\n\nfrom lfx.base.prompts.api_utils import process_prompt_template\nfrom lfx.custom.custom_component.component import Component\nfrom lfx.inputs.input_mixin import FieldTypes\nfrom lfx.inputs.inputs import DefaultPromptField\nfrom lfx.io import BoolInput, MessageTextInput, Output, PromptInput\nfrom lfx.log.logger import logger\nfrom lfx.schema.dotdict import dotdict\nfrom lfx.schema.message import Message\nfrom lfx.template.utils import update_template_values\nfrom lfx.utils.mustache_security import validate_mustache_template\n\n\nclass PromptComponent(Component):\n display_name: str = \"Prompt Template\"\n description: str = \"Create a prompt template with dynamic variables.\"\n documentation: str = \"https://docs.langflow.org/components-prompts\"\n icon = \"prompts\"\n trace_type = \"prompt\"\n name = \"Prompt Template\"\n\n inputs = [\n PromptInput(name=\"template\", display_name=\"Template\"),\n BoolInput(\n name=\"use_double_brackets\",\n display_name=\"Use Double Brackets\",\n value=False,\n advanced=True,\n info=\"Use {{variable}} syntax instead of {variable}.\",\n real_time_refresh=True,\n ),\n MessageTextInput(\n name=\"tool_placeholder\",\n display_name=\"Tool Placeholder\",\n tool_mode=True,\n advanced=True,\n show=False,\n info=\"A placeholder input for tool mode.\",\n ),\n ]\n\n outputs = [\n Output(display_name=\"Prompt\", name=\"prompt\", method=\"build_prompt\"),\n ]\n\n def update_build_config(self, build_config: dotdict, field_value: Any, field_name: str | None = None) -> dotdict:\n \"\"\"Update the template field type based on the selected mode.\"\"\"\n if field_name == \"use_double_brackets\":\n # Change the template field type based on mode\n is_mustache = field_value is True\n if is_mustache:\n build_config[\"template\"][\"type\"] = FieldTypes.MUSTACHE_PROMPT.value\n else:\n build_config[\"template\"][\"type\"] = FieldTypes.PROMPT.value\n\n # Re-process the template to update variables when mode changes\n template_value = build_config.get(\"template\", {}).get(\"value\", \"\")\n if template_value:\n # Ensure custom_fields is properly initialized\n if \"custom_fields\" not in build_config:\n build_config[\"custom_fields\"] = {}\n\n # Clean up fields from the OLD mode before processing with NEW mode\n # This ensures we don't keep fields with wrong syntax even if validation fails\n old_custom_fields = build_config[\"custom_fields\"].get(\"template\", [])\n for old_field in list(old_custom_fields):\n # Remove the field from custom_fields and template\n if old_field in old_custom_fields:\n old_custom_fields.remove(old_field)\n build_config.pop(old_field, None)\n\n # Try to process template with new mode to add new variables\n # If validation fails, at least we cleaned up old fields\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(template_value)\n\n # Re-process template with new mode to add new variables\n _ = process_prompt_template(\n template=template_value,\n name=\"template\",\n custom_fields=build_config[\"custom_fields\"],\n frontend_node_template=build_config,\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, we still updated the mode and cleaned old fields\n # User will see error when they try to save\n logger.debug(f\"Template validation failed during mode switch: {e}\")\n return build_config\n\n async def build_prompt(self) -> Message:\n use_double_brackets = self.use_double_brackets if hasattr(self, \"use_double_brackets\") else False\n template_format = \"mustache\" if use_double_brackets else \"f-string\"\n prompt = await Message.from_template_and_variables(template_format=template_format, **self._attributes)\n self.status = prompt.text\n return prompt\n\n def _update_template(self, frontend_node: dict):\n prompt_template = frontend_node[\"template\"][\"template\"][\"value\"]\n use_double_brackets = frontend_node[\"template\"].get(\"use_double_brackets\", {}).get(\"value\", False)\n is_mustache = use_double_brackets is True\n\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(prompt_template)\n\n custom_fields = frontend_node[\"custom_fields\"]\n frontend_node_template = frontend_node[\"template\"]\n _ = process_prompt_template(\n template=prompt_template,\n name=\"template\",\n custom_fields=custom_fields,\n frontend_node_template=frontend_node_template,\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, don't add variables but allow component to be created\n logger.debug(f\"Template validation failed in _update_template: {e}\")\n return frontend_node\n\n async def update_frontend_node(self, new_frontend_node: dict, current_frontend_node: dict):\n \"\"\"This function is called after the code validation is done.\"\"\"\n frontend_node = await super().update_frontend_node(new_frontend_node, current_frontend_node)\n template = frontend_node[\"template\"][\"template\"][\"value\"]\n use_double_brackets = frontend_node[\"template\"].get(\"use_double_brackets\", {}).get(\"value\", False)\n is_mustache = use_double_brackets is True\n\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(template)\n\n # Kept it duplicated for backwards compatibility\n _ = process_prompt_template(\n template=template,\n name=\"template\",\n custom_fields=frontend_node[\"custom_fields\"],\n frontend_node_template=frontend_node[\"template\"],\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, don't add variables but allow component to be updated\n logger.debug(f\"Template validation failed in update_frontend_node: {e}\")\n # Now that template is updated, we need to grab any values that were set in the current_frontend_node\n # and update the frontend_node with those values\n update_template_values(new_template=frontend_node, previous_template=current_frontend_node[\"template\"])\n return frontend_node\n\n def _get_fallback_input(self, **kwargs):\n return DefaultPromptField(**kwargs)\n"
+ "value": "from typing import Any\n\nfrom lfx.base.prompts.api_utils import process_prompt_template\nfrom lfx.custom.custom_component.component import Component\nfrom lfx.inputs.input_mixin import FieldTypes\nfrom lfx.inputs.inputs import DefaultPromptField\nfrom lfx.io import BoolInput, MessageTextInput, Output, PromptInput\nfrom lfx.log.logger import logger\nfrom lfx.schema.dotdict import dotdict\nfrom lfx.schema.message import Message\nfrom lfx.template.utils import update_template_values\nfrom lfx.utils.mustache_security import validate_mustache_template\n\n\nclass PromptComponent(Component):\n display_name: str = \"Prompt Template\"\n description: str = \"Create a prompt template with dynamic variables.\"\n documentation: str = \"https://docs.langflow.org/components-prompts\"\n icon = \"prompts\"\n trace_type = \"prompt\"\n name = \"Prompt Template\"\n\n inputs = [\n PromptInput(name=\"template\", display_name=\"Template\"),\n BoolInput(\n name=\"use_double_brackets\",\n display_name=\"Use Double Brackets\",\n value=False,\n advanced=True,\n info=\"Use {{variable}} syntax instead of {variable}.\",\n real_time_refresh=True,\n ),\n MessageTextInput(\n name=\"tool_placeholder\",\n display_name=\"Tool Placeholder\",\n tool_mode=True,\n advanced=True,\n show=False,\n info=\"A placeholder input for tool mode.\",\n ),\n ]\n\n outputs = [\n Output(display_name=\"Prompt\", name=\"prompt\", method=\"build_prompt\"),\n ]\n\n def update_build_config(self, build_config: dotdict, field_value: Any, field_name: str | None = None) -> dotdict:\n \"\"\"Update the template field type based on the selected mode.\"\"\"\n if field_name == \"use_double_brackets\":\n # Change the template field type based on mode\n is_mustache = field_value is True\n if is_mustache:\n build_config[\"template\"][\"type\"] = FieldTypes.MUSTACHE_PROMPT.value\n else:\n build_config[\"template\"][\"type\"] = FieldTypes.PROMPT.value\n\n # Re-process the template to update variables when mode changes\n template_value = build_config.get(\"template\", {}).get(\"value\", \"\")\n if template_value:\n # Ensure custom_fields is properly initialized\n if \"custom_fields\" not in build_config:\n build_config[\"custom_fields\"] = {}\n\n # Clean up fields from the OLD mode before processing with NEW mode\n # This ensures we don't keep fields with wrong syntax even if validation fails\n old_custom_fields = build_config[\"custom_fields\"].get(\"template\", [])\n for old_field in list(old_custom_fields):\n # Remove the field from custom_fields and template\n if old_field in old_custom_fields:\n old_custom_fields.remove(old_field)\n build_config.pop(old_field, None)\n\n # Try to process template with new mode to add new variables\n # If validation fails, at least we cleaned up old fields\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(template_value)\n\n # Re-process template with new mode to add new variables\n _ = process_prompt_template(\n template=template_value,\n name=\"template\",\n custom_fields=build_config[\"custom_fields\"],\n frontend_node_template=build_config,\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, we still updated the mode and cleaned old fields\n # User will see error when they try to save\n logger.debug(\"Template validation failed during mode switch\", exc_info=e)\n return build_config\n\n async def build_prompt(self) -> Message:\n use_double_brackets = self.use_double_brackets if hasattr(self, \"use_double_brackets\") else False\n template_format = \"mustache\" if use_double_brackets else \"f-string\"\n prompt = await Message.from_template_and_variables(template_format=template_format, **self._attributes)\n self.status = prompt.text\n return prompt\n\n def _update_template(self, frontend_node: dict):\n prompt_template = frontend_node[\"template\"][\"template\"][\"value\"]\n use_double_brackets = frontend_node[\"template\"].get(\"use_double_brackets\", {}).get(\"value\", False)\n is_mustache = use_double_brackets is True\n\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(prompt_template)\n\n custom_fields = frontend_node[\"custom_fields\"]\n frontend_node_template = frontend_node[\"template\"]\n _ = process_prompt_template(\n template=prompt_template,\n name=\"template\",\n custom_fields=custom_fields,\n frontend_node_template=frontend_node_template,\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, don't add variables but allow component to be created\n logger.debug(\"Template validation failed in _update_template\", exc_info=e)\n return frontend_node\n\n async def update_frontend_node(self, new_frontend_node: dict, current_frontend_node: dict):\n \"\"\"This function is called after the code validation is done.\"\"\"\n frontend_node = await super().update_frontend_node(new_frontend_node, current_frontend_node)\n template = frontend_node[\"template\"][\"template\"][\"value\"]\n use_double_brackets = frontend_node[\"template\"].get(\"use_double_brackets\", {}).get(\"value\", False)\n is_mustache = use_double_brackets is True\n\n try:\n # Validate mustache templates for security\n if is_mustache:\n validate_mustache_template(template)\n\n # Kept it duplicated for backwards compatibility\n _ = process_prompt_template(\n template=template,\n name=\"template\",\n custom_fields=frontend_node[\"custom_fields\"],\n frontend_node_template=frontend_node[\"template\"],\n is_mustache=is_mustache,\n )\n except ValueError as e:\n # If validation fails, don't add variables but allow component to be updated\n logger.debug(\"Template validation failed in update_frontend_node\", exc_info=e)\n # Now that template is updated, we need to grab any values that were set in the current_frontend_node\n # and update the frontend_node with those values\n update_template_values(new_template=frontend_node, previous_template=current_frontend_node[\"template\"])\n return frontend_node\n\n def _get_fallback_input(self, **kwargs):\n return DefaultPromptField(**kwargs)\n"
},
"docs": {
"advanced": false,
+ "api_editable": false,
"display_name": "docs",
"dynamic": false,
"field_type": "str",
@@ -323,6 +317,7 @@
},
"prompt": {
"advanced": false,
+ "api_editable": false,
"display_name": "prompt",
"dynamic": false,
"field_type": "str",
@@ -346,6 +341,7 @@
"template": {
"_input_type": "PromptInput",
"advanced": false,
+ "api_editable": false,
"display_name": "Template",
"dynamic": false,
"info": "",
@@ -367,6 +363,7 @@
"tool_placeholder": {
"_input_type": "MessageTextInput",
"advanced": true,
+ "api_editable": false,
"display_name": "Tool Placeholder",
"dynamic": false,
"info": "A placeholder input for tool mode.",
@@ -392,6 +389,7 @@
"use_double_brackets": {
"_input_type": "BoolInput",
"advanced": true,
+ "api_editable": false,
"display_name": "Use Double Brackets",
"dynamic": false,
"info": "Use {{variable}} syntax instead of {variable}.",
@@ -2406,7 +2404,7 @@
"api_editable": false,
"display_name": "OpenAI API Base",
"dynamic": false,
- "info": "Must end with /v1 (for example http://openrag-backend:8000/v1). Bound to OPENRAG_LLM_BASE_URL at runtime. Same URL as chat.",
+ "info": "Bound to OPENRAG_LLM_BASE_URL at runtime. It is either the public /v1 base or the private router base. Same URL as chat.",
"list": false,
"list_add_label": "Add More",
"load_from_db": true,
@@ -2636,7 +2634,7 @@
"api_editable": false,
"display_name": "OpenAI API Base",
"dynamic": false,
- "info": "Must end with /v1 (for example http://openrag-backend:8000/v1). Bound to OPENRAG_LLM_BASE_URL at runtime. Same URL as embeddings.",
+ "info": "Bound to OPENRAG_LLM_BASE_URL at runtime. It is either the public /v1 base or the private router base. Same URL as embeddings.",
"list": false,
"list_add_label": "Add More",
"load_from_db": true,
@@ -2885,20 +2883,20 @@
}
],
"viewport": {
- "x": 218.55846372585756,
- "y": -682.4564731762473,
- "zoom": 0.6224371176910848
+ "x": 62.972880126394784,
+ "y": -487.04165750950597,
+ "zoom": 0.6467039747513049
}
},
"description": "OpenRAG OpenSearch Nudges generator, based on the OpenSearch documents and the chat history.",
"endpoint_name": null,
"id": "ebc01d31-1976-46ce-a385-b0240327226c",
"is_component": false,
- "last_tested_version": "0.11.6",
+ "last_tested_version": "1.12.0",
"locked": true,
"name": "OpenRAG OpenSearch Nudges Flow",
"tags": [
"assistants",
"agents"
]
-}
+}
\ No newline at end of file