Skip to content

Agent Zero AI framework

Update: Improved MCP setup and config, async handling for sessions, auto mcp install if present in settings config (on compose)

decicafcef00e1da
diff --git a/docker/run/Dockerfile.cuda b/docker/run/Dockerfile.cuda
new file mode 100644
index 000000000..392090838
--- /dev/null
+++ b/docker/run/Dockerfile.cuda
@@ -0,0 +1,174 @@
+# Use the NVIDIA CUDA base image with Ubuntu
+FROM nvidia/cuda:12.8.1-base-ubuntu22.04
+
+# Set non-interactive installation and timezone
+ENV DEBIAN_FRONTEND=noninteractive
+ENV TZ=UTC
+
+# Check if the argument is provided, else throw an error
+ARG BRANCH
+RUN if [ -z "$BRANCH" ]; then echo "ERROR: BRANCH is not set!" >&2; exit 1; fi
+ENV BRANCH=$BRANCH
+
+# Set locale to en_US.UTF-8 and timezone to UTC (matching main Dockerfile)
+RUN apt-get update && apt-get install -y locales tzdata
+RUN sed -i -e 's/# \(en_US\.UTF-8 .*\)/\1/' /etc/locale.gen && \
+ dpkg-reconfigure --frontend=noninteractive locales && \
+ update-locale LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_ALL=en_US.UTF-8
+RUN ln -sf /usr/share/zoneinfo/UTC /etc/localtime
+RUN echo "UTC" > /etc/timezone
+RUN dpkg-reconfigure -f noninteractive tzdata
+ENV LANG=en_US.UTF-8
+ENV LANGUAGE=en_US:en
+ENV LC_ALL=en_US.UTF-8
+ENV TZ=UTC
+
+# Copy contents of the project to root directory
+COPY ./fs/ /
+
+# Fix permissions for cron files from pre_install.sh
+RUN chmod 0644 /etc/cron.d/*
+
+# Install essential packages (from pre_install.sh but avoiding supervisor from apt)
+# Node.js and npm will be installed separately using NodeSource for a specific version
+RUN apt-get update && apt-get upgrade -y && apt-get -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install -y \
+ python3 \
+ python3-venv \
+ python3-pip \
+ openssh-server \
+ sudo \
+ curl \
+ wget \
+ git \
+ ffmpeg \
+ nginx \
+ cron \
+ libmagic-dev \
+ poppler-utils \
+ tesseract-ocr \
+ qpdf \
+ libreoffice \
+ pandoc \
+ libgtk-3-0 \
+ libnss3 \
+ libatk1.0-0 \
+ libatk-bridge2.0-0 \
+ libcups2 \
+ libasound2 \
+ libasound2-data \
+ cargo
+
+# Install Node.js 20.x (LTS) and a compatible npm
+RUN apt-get update && apt-get install -y ca-certificates curl gnupg
+RUN mkdir -p /etc/apt/keyrings
+RUN curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
+RUN echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
+RUN apt-get update && apt-get install -y nodejs || { echo "CRITICAL ERROR: Failed to install Node.js from NodeSource." ; exit 1; }
+
+# Prepare SSH daemon (from pre_install.sh)
+RUN bash /ins/setup_ssh.sh $BRANCH
+
+# Configure Python 3.12 (specific to Ubuntu-based CUDA image)
+RUN apt-get update && apt-get install -y \
+ software-properties-common && \
+ add-apt-repository -y ppa:deadsnakes/ppa && \
+ apt-get update && \
+ apt-get install -y python3.12 python3.12-venv python3.12-dev && \
+ update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 1 && \
+ update-alternatives --set python3 /usr/bin/python3.12
+
+# Bootstrap pip for Python 3.12 and install supervisor
+RUN python3 -m ensurepip --upgrade && \
+ python3 -m pip install --upgrade pip setuptools wheel && \
+ python3 -m pip install supervisor
+
+# Create supervisor directories
+RUN mkdir -p /var/log/supervisor /etc/supervisor/conf.d
+
+# Create root dotfiles with appropriate permissions
+RUN touch /root/.bashrc /root/.profile && \
+ chmod 644 /root/.bashrc /root/.profile
+
+# Create a symlink for supervisord to the expected location
+RUN ln -sf $(which supervisord) /usr/bin/supervisord
+
+# Install additional software
+RUN bash /ins/install_additional.sh $BRANCH
+
+# Install core CUDA dependencies (minimized to essentials)
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ cuda-cudart-dev-12-8 \
+ libcublas-dev-12-8 \
+ libcudnn8 \
+ && apt-get clean \
+ && rm -rf /var/lib/apt/lists/*
+
+# Set CUDA environment variables
+ENV PATH=/usr/local/cuda/bin:${PATH}
+ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:${LD_LIBRARY_PATH}
+ENV CUDA_HOME=/usr/local/cuda
+ENV CUDA_VERSION=12.8.1
+
+# Install A0
+RUN bash /ins/install_A0.sh $BRANCH
+
+# Create and set up the shared instruments virtual environment
+ENV INSTRUMENTS_VENV_PATH=/opt/instruments_venv
+RUN python3 -m venv $INSTRUMENTS_VENV_PATH
+
+# Switch to bash for the next RUN step (required for set -o pipefail)
+SHELL ["/bin/bash", "-c"]
+
+# Install all heavy dependencies into the instruments venv, with explicit checks
+RUN set -euxo pipefail; \
+ . $INSTRUMENTS_VENV_PATH/bin/activate; \
+ echo "=== Upgrading pip, setuptools, wheel ==="; \
+ pip install --upgrade pip setuptools wheel; \
+ echo "=== Installing PyTorch with CUDA ==="; \
+ pip install --no-cache-dir torch==2.6.0+cu124 torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124; \
+ echo "=== Installing other heavy dependencies ==="; \
+ pip install --no-cache-dir \
+ huggingface-hub==0.20.3 \
+ safetensors==0.4.1 \
+ accelerate==0.21.0 \
+ diffusers==0.25.0 \
+ transformers==4.38.2 \
+ scipy==1.15.2 \
+ xformers==0.0.29.post3; \
+ echo "=== Checking all critical imports ==="; \
+ python -c "import torch; print(f'PyTorch {torch.__version__} imported successfully. CUDA: {getattr(torch, 'cuda', None) and torch.cuda.is_available()}')" || (echo 'PyTorch import failed!' && exit 1); \
+ python -c "import torchvision; print(f'Torchvision {torchvision.__version__} imported successfully.')" || (echo 'Torchvision import failed!' && exit 1); \
+ python -c "import torchaudio; print(f'Torchaudio {torchaudio.__version__} imported successfully.')" || (echo 'Torchaudio import failed!' && exit 1); \
+ python -c "import diffusers; print(f'Diffusers {diffusers.__version__} imported successfully.')" || (echo 'Diffusers import failed!' && exit 1); \
+ python -c "import transformers; print(f'Transformers {transformers.__version__} imported successfully.')" || (echo 'Transformers import failed!' && exit 1); \
+ python -c "import xformers; print(f'Xformers {xformers.__version__} imported successfully.')" || (echo 'Xformers import failed!' && exit 1); \
+ python -c "import accelerate; print(f'Accelerate {accelerate.__version__} imported successfully.')" || (echo 'Accelerate import failed!' && exit 1); \
+ python -c "import safetensors; print(f'Safetensors {safetensors.__version__} imported successfully.')" || (echo 'Safetensors import failed!' && exit 1); \
+ python -c "import scipy; print(f'Scipy {scipy.__version__} imported successfully.')" || (echo 'Scipy import failed!' && exit 1); \
+ python -c "import huggingface_hub; print(f'Huggingface_hub {huggingface_hub.__version__} imported successfully.')" || (echo 'Huggingface_hub import failed!' && exit 1); \
+ echo "=== All critical imports succeeded ==="
+
+# Optionally revert to sh for subsequent steps if needed
+SHELL ["/bin/sh", "-c"]
+
+# The existing global PyTorch install for /opt/venv (A0's main venv) is below.
+# It might be used by other core A0 components, so we keep it.
+# Our instruments will use the dedicated $INSTRUMENTS_VENV_PATH.
+RUN . /opt/venv/bin/activate && \
+ pip uninstall -y torch torchvision && \
+ pip install --no-cache-dir torch torchvision --index-url https://download.pytorch.org/whl/cu124
+
+# Cleanup repo and install A0 without caching, this speeds up builds
+ARG CACHE_DATE=none
+RUN echo "cache buster $CACHE_DATE" && bash /ins/install_A02.sh $BRANCH
+
+# Post installation steps
+RUN bash /ins/post_install.sh $BRANCH
+
+# Expose ports
+EXPOSE 22 80
+
+RUN chmod +x /exe/initialize.sh /exe/run_A0.sh /exe/run_searxng.sh
+
+# Initialize runtime
+CMD ["/exe/initialize.sh", "$BRANCH"]
diff --git a/docker/run/fs/ins/pre_install.sh b/docker/run/fs/ins/pre_install.sh
index d901d1200..ff54962d6 100644
--- a/docker/run/fs/ins/pre_install.sh
+++ b/docker/run/fs/ins/pre_install.sh
@@ -14,8 +14,6 @@ apt-get update && apt-get upgrade -y && apt-get -o Dpkg::Options::="--force-conf
python3 \
python3-venv \
python3-pip \
- nodejs \
- npm \
openssh-server \
sudo \
curl \
@@ -38,15 +36,21 @@ apt-get update && apt-get upgrade -y && apt-get -o Dpkg::Options::="--force-conf
libcups2 \
libasound2 \
libasound2-data \
- cargo
+ cargo \
+ ca-certificates \
+ gnupg
echo "=====MID UPDATE====="
-# for some reason npm crashes builds on amd64 in this version and has to be installed separately
-# A0 can install it when needed
-# The line below is now redundant as npm is included in the main install list above
-# apt-get install -y \
-# npm
+# Install Node.js 20.x (LTS) and a compatible npm using NodeSource
+echo "Setting up NodeSource repository for Node.js 20.x..."
+mkdir -p /etc/apt/keyrings
+curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
+echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
+
+echo "Installing Node.js..."
+apt-get update # Update package list again after adding new source
+apt-get install -y nodejs || { echo "CRITICAL ERROR: Failed to install Node.js from NodeSource." ; exit 1; }
echo "=====AFTER UPDATE====="
diff --git a/initialize.py b/initialize.py
index 9e92a2270..0e5a467c3 100644
--- a/initialize.py
+++ b/initialize.py
@@ -2,10 +2,63 @@ import asyncio
import models
from agent import AgentConfig, ModelConfig
from python.helpers import dotenv, files, rfc_exchange, runtime, settings, docker, log
+import subprocess
+import shutil
+from python.helpers.print_style import PrintStyle
def initialize():
+ PrintStyle(background_color="blue", font_color="white", padding=True).print(
+ "Attempting to ensure MCP server 'mcp-server-sequential-thinking' is available..."
+ )
+ # Check if npm is available first, as it's needed for the install.
+ if shutil.which("npm"):
+ if not shutil.which("mcp-server-sequential-thinking"):
+ PrintStyle(font_color="yellow", padding=True).print(
+ "'mcp-server-sequential-thinking' not found in PATH. Attempting global npm install..."
+ )
+ try:
+ # Attempt to install @modelcontextprotocol/server-sequential-thinking globally
+ npm_command = ["npm", "i", "-g", "@modelcontextprotocol/server-sequential-thinking", "--no-fund", "--no-audit"]
+ process = subprocess.run(npm_command, capture_output=True, text=True, check=False)
+ if process.returncode == 0:
+ PrintStyle(font_color="green", padding=True).print(
+ "Successfully installed @modelcontextprotocol/server-sequential-thinking globally via npm."
+ )
+ # Re-check if it's available in PATH now. This depends on npm's global bin location being in PATH.
+ if shutil.which("mcp-server-sequential-thinking"):
+ PrintStyle(font_color="green", padding=True).print(
+ "'mcp-server-sequential-thinking' is now available in PATH after install."
+ )
+ else:
+ PrintStyle(font_color="orange", padding=True).print(
+ "WARNING: npm install reported success, but 'mcp-server-sequential-thinking' still not found in PATH by shutil.which(). " +
+ "The 'npx' command in settings.json might still be necessary and hopefully works."
+ )
+ else:
+ PrintStyle(font_color="red", padding=True).print(
+ f"Failed to install @modelcontextprotocol/server-sequential-thinking globally via npm. Return code: {process.returncode}"
+ )
+ PrintStyle(font_color="red", padding=False).print(f"npm stdout: {process.stdout.strip()}")
+ PrintStyle(font_color="red", padding=False).print(f"npm stderr: {process.stderr.strip()}")
+ except FileNotFoundError:
+ PrintStyle(font_color="red", padding=True).print(
+ "ERROR: 'npm' command not found. Cannot attempt to install @modelcontextprotocol/server-sequential-thinking."
+ )
+ except Exception as e:
+ PrintStyle(font_color="red", padding=True).print(
+ f"Exception during npm install of @modelcontextprotocol/server-sequential-thinking: {e}"
+ )
+ else:
+ PrintStyle(font_color="green", padding=True).print(
+ "'mcp-server-sequential-thinking' already found in PATH."
+ )
+ else:
+ PrintStyle(font_color="red", padding=True).print(
+ "ERROR: 'npm' command not found. Cannot check for or install 'mcp-server-sequential-thinking'."
+ )
+
current_settings = settings.get_settings()
# chat model from user settings
diff --git a/python/helpers/mcp_handler.py b/python/helpers/mcp_handler.py
index fdd935ab8..666a85362 100644
--- a/python/helpers/mcp_handler.py
+++ b/python/helpers/mcp_handler.py
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
-from typing import List, Dict, Optional, Any, Union, Literal, Annotated, ClassVar, cast
+from typing import List, Dict, Optional, Any, Union, Literal, Annotated, ClassVar, cast, Callable, Awaitable, TypeVar
import threading
import asyncio
from contextlib import AsyncExitStack
@@ -7,7 +7,7 @@ from shutil import which
from datetime import timedelta
import os
-print(f"DEBUG: Listing /opt/venv/lib/python3.11/site-packages/ before mcp import: {os.listdir('/opt/venv/lib/python3.11/site-packages/')}")
+# print(f"DEBUG: Listing /opt/venv/lib/python3.11/site-packages/ before mcp import: {os.listdir('/opt/venv/lib/python3.11/site-packages/')}") # This line caused FileNotFoundError, **FOR CUDA CHANGE TO '3.12'**
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
@@ -202,21 +202,98 @@ class MCPConfig(BaseModel):
@classmethod
def update(cls, config_str: str) -> Any:
- """Parse the MCP config string into a MCPConfig object."""
with cls.__lock:
- try:
- servers = DirtyJson.parse_string(config_str)
- except Exception as e:
- raise ValueError(f"Failed to parse MCP config: {e}") from e
- cls.get_instance().__init__(servers_list=servers)
+ servers_data: List[Dict[str, Any]] = [] # Default to empty list
+
+ if config_str and config_str.strip(): # Only parse if non-empty and not just whitespace
+ try:
+ # Try with standard json.loads first, as it should handle escaped strings correctly
+ import json
+ parsed_value = json.loads(config_str)
+
+ if isinstance(parsed_value, list):
+ valid_servers = []
+ for item in parsed_value:
+ if isinstance(item, dict):
+ valid_servers.append(item)
+ else:
+ PrintStyle(background_color="yellow", font_color="black", padding=True).print(
+ f"Warning: MCP config item (from json.loads) was not a dictionary and was ignored: {item}"
+ )
+ servers_data = valid_servers
+ else:
+ PrintStyle(background_color="red", font_color="white", padding=True).print(
+ f"Error: Parsed MCP config (from json.loads) top-level structure is not a list. Config string was: '{config_str}'"
+ )
+ # servers_data remains empty
+ except Exception as e_json: # Catch json.JSONDecodeError specifically if possible, or general Exception
+ # Fallback to DirtyJson or log error if standard json.loads fails
+ PrintStyle(background_color="orange", font_color="black", padding=True).print(
+ f"Standard json.loads failed for MCP config: {e_json}. Attempting DirtyJson as fallback."
+ )
+ try:
+ parsed_value = DirtyJson.parse_string(config_str)
+ if isinstance(parsed_value, list):
+ valid_servers = []
+ for item in parsed_value:
+ if isinstance(item, dict):
+ valid_servers.append(item)
+ else:
+ PrintStyle(background_color="yellow", font_color="black", padding=True).print(
+ f"Warning: MCP config item (from DirtyJson) was not a dictionary and was ignored: {item}"
+ )
+ servers_data = valid_servers
+ else:
+ PrintStyle(background_color="red", font_color="white", padding=True).print(
+ f"Error: Parsed MCP config (from DirtyJson) top-level structure is not a list. Config string was: '{config_str}'"
+ )
+ # servers_data remains empty
+ except Exception as e_dirty:
+ PrintStyle(background_color="red", font_color="white", padding=True).print(
+ f"Error parsing MCP config string with DirtyJson as well: {e_dirty}. Config string was: '{config_str}'"
+ )
+ # servers_data remains empty, allowing graceful degradation
+
+ # Initialize/update the singleton instance with the (potentially empty) list of server data
+ instance = cls.get_instance()
+ # Directly update the servers attribute of the existing instance or re-initialize carefully
+ # For simplicity and to ensure __init__ logic runs if needed for setup:
+ new_instance_data = {'servers': servers_data} # Prepare data for re-initialization or update
+
+ # Option 1: Re-initialize the existing instance (if __init__ is idempotent for other fields)
+ instance.__init__(servers_list=servers_data)
+
+ # Option 2: Or, if __init__ has side effects we don't want to repeat,
+ # and 'servers' is the primary thing 'update' changes:
+ # instance.servers = [] # Clear existing servers first
+ # for server_item_data in servers_data:
+ # try:
+ # if server_item_data.get("url", None):
+ # instance.servers.append(MCPServerRemote(server_item_data))
+ # else:
+ # instance.servers.append(MCPServerLocal(server_item_data))
+ # except Exception as e_init:
+ # PrintStyle(background_color="grey", font_color="red", padding=True).print(
+ # f"MCPConfig.update: Failed to create MCPServer from item '{server_item_data.get('name', 'Unknown')}': {e_init}"
+ # )
+
cls.__initialized = True
- return cls.get_instance()
+ return instance
def __init__(self, servers_list: List[Dict[str, Any]]):
from collections.abc import Mapping, Iterable
- # This empties the servers list
- super().__init__()
+ # DEBUG: Print the received servers_list
+ PrintStyle(background_color="blue", font_color="white", padding=True).print(f"MCPConfig.__init__ received servers_list: {servers_list}")
+
+ # This empties the servers list if MCPConfig is a Pydantic model and servers is a field.
+ # If servers is a field like `servers: List[MCPServer] = Field(default_factory=list)`,
+ # then super().__init__() might try to initialize it.
+ # We are re-assigning self.servers later in this __init__.
+ super().__init__()
+
+ # Clear any servers potentially initialized by super().__init__() before we populate based on servers_list
+ self.servers = []
if not isinstance(servers_list, Iterable):
(
@@ -343,7 +420,7 @@ class MCPConfig(BaseModel):
def get_tool(self, agent: Any, tool_name: str) -> MCPTool | None:
if not self.has_tool(tool_name):
return None
- return MCPTool(agent, tool_name, {}, "", **{})
+ return MCPTool(agent=agent, name=tool_name, method=None, args={}, message="")
async def call_tool(self, tool_name: str, input_data: Dict[str, Any]) -> CallToolResult:
"""Call a tool with the given input data"""
@@ -357,68 +434,87 @@ class MCPConfig(BaseModel):
raise ValueError(f"Tool {tool_name} not found")
-class MCPClientBase(ABC):
- session: Optional[ClientSession] = None
- exit_stack: AsyncExitStack = AsyncExitStack()
- stdio: Optional[MemoryObjectReceiveStream[JSONRPCMessage | Exception]] = None
- write: Optional[MemoryObjectSendStream[JSONRPCMessage]] = None
+T = TypeVar('T')
- tools: List[dict[str, Any]] = []
- server: Optional[Union[MCPServerLocal, MCPServerRemote]] = None
+class MCPClientBase(ABC):
+ # server: Union[MCPServerLocal, MCPServerRemote] # Defined in __init__
+ # tools: List[dict[str, Any]] # Defined in __init__
+ # No self.session, self.exit_stack, self.stdio, self.write as persistent instance fields
__lock: ClassVar[threading.Lock] = threading.Lock()
def __init__(self, server: Union[MCPServerLocal, MCPServerRemote]):
self.server = server
+ self.tools: List[dict[str, Any]] = [] # Tools are cached on the client instance
# Protected method
@abstractmethod
- async def _connect_client(self) -> tuple[MemoryObjectReceiveStream[JSONRPCMessage | Exception], MemoryObjectSendStream[JSONRPCMessage]]:
- """Connect to an MCP server, init client and save stdio/write streams"""
+ async def _create_stdio_transport(self, current_exit_stack: AsyncExitStack) -> tuple[MemoryObjectReceiveStream[JSONRPCMessage | Exception], MemoryObjectSendStream[JSONRPCMessage]]:
+ """Create stdio/write streams using the provided exit_stack."""
...
- async def __connect_to_server(self) -> Any:
- """Connect to an MCP server"""
- with self.__lock:
- self.stdio, self.write = await self._connect_client()
-
- self.session = (
- await self.exit_stack.enter_async_context(
+ async def _execute_with_session(self, coro_func: Callable[[ClientSession], Awaitable[T]]) -> T:
+ """
+ Manages the lifecycle of an MCP session for a single operation.
+ Creates a temporary session, executes coro_func with it, and ensures cleanup.
+ """
+ operation_name = coro_func.__name__ # For logging
+ PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name}): Creating new session for operation '{operation_name}'...")
+ async with AsyncExitStack() as temp_stack:
+ try:
+ stdio, write = await self._create_stdio_transport(temp_stack)
+ PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name} - {operation_name}): Transport created. Initializing session...")
+ session = await temp_stack.enter_async_context(
ClientSession(
- self.stdio,
- self.write,
- read_timeout_seconds=timedelta(seconds=15)
+ stdio,
+ write,
+ read_timeout_seconds=timedelta(seconds=600)
)
)
- )
-
- # Initialize session
- await self.session.initialize()
- return self
-
- async def update_tools(self) -> Any:
- """List available tools from the server"""
- try:
- await self.__connect_to_server()
- with self.__lock:
- response: ListToolsResult = await self.session.list_tools()
- available_tools = [{
+ await session.initialize()
+ PrintStyle(font_color="green").print(f"MCPClientBase ({self.server.name} - {operation_name}): Session initialized.")
+
+ result = await coro_func(session)
+
+ PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name} - {operation_name}): Operation successful.")
+ return result
+ except Exception as e:
+ PrintStyle(background_color="#AA4455", font_color="white", padding=False).print(
+ f"MCPClientBase ({self.server.name} - {operation_name}): Error during operation: {type(e).__name__}: {e}"
+ )
+ raise # Re-raise the exception to be handled by the caller of update_tools/call_tool
+ finally:
+ PrintStyle(font_color="cyan").print(
+ f"MCPClientBase ({self.server.name} - {operation_name}): Session and transport will be closed by AsyncExitStack."
+ )
+ # temp_stack.aclose() is called automatically here.
+
+ async def update_tools(self) -> "MCPClientBase":
+ PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name}): Starting 'update_tools' operation...")
+
+ async def list_tools_op(current_session: ClientSession):
+ response: ListToolsResult = await current_session.list_tools()
+ with self.__lock:
+ self.tools = [{
"name": tool.name,
"description": tool.description,
"input_schema": tool.inputSchema
} for tool in response.tools]
+ PrintStyle(font_color="green").print(f"MCPClientBase ({self.server.name}): Tools updated. Found {len(self.tools)} tools.")
- self.tools = available_tools
- await self.exit_stack.aclose()
- return self
+ try:
+ await self._execute_with_session(list_tools_op)
except Exception as e:
- PrintStyle(
- background_color="#CC34C3", font_color="white", bold=True, padding=True
- ).print("MCPClientLocal::Failed to update tools:")
- PrintStyle(background_color="#AA4455", font_color="white", padding=False).print(str(e))
+ # Error already logged by _execute_with_session, this is for specific handling if needed
+ PrintStyle(background_color="#CC34C3", font_color="white", bold=True, padding=True).print(
+ f"MCPClientBase ({self.server.name}): 'update_tools' operation failed: {e}"
+ )
+ with self.__lock:
+ self.tools = [] # Ensure tools are cleared on failure
+ return self
def has_tool(self, tool_name: str) -> bool:
- """Check if a tool is available"""
+ """Check if a tool is available (uses cached tools)"""
with self.__lock:
for tool in self.tools:
if tool["name"] == tool_name:
@@ -426,42 +522,44 @@ class MCPClientBase(ABC):
return False
def get_tools(self) -> List[dict[str, Any]]:
- """Get all tools from the server"""
+ """Get all tools from the server (uses cached tools)"""
with self.__lock:
return self.tools
async def call_tool(self, tool_name: str, input_data: Dict[str, Any]) -> CallToolResult:
- """Call a tool with the given input data"""
+ PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name}): Preparing for 'call_tool' operation for tool '{tool_name}'.")
if not self.has_tool(tool_name):
- await self.update_tools()
-
- await self.__connect_to_server()
+ PrintStyle(font_color="orange").print(f"MCPClientBase ({self.server.name}): Tool '{tool_name}' not in cache for 'call_tool', refreshing tools...")
+ await self.update_tools() # This will use its own properly managed session
+ if not self.has_tool(tool_name):
+ PrintStyle(font_color="red").print(f"MCPClientBase ({self.server.name}): Tool '{tool_name}' not found after refresh. Raising ValueError.")
+ raise ValueError(f"Tool {tool_name} not found after refreshing tool list for server {self.server.name}.")
+ PrintStyle(font_color="green").print(f"MCPClientBase ({self.server.name}): Tool '{tool_name}' found after updating tools.")
+
+ async def call_tool_op(current_session: ClientSession):
+ PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name}): Executing 'call_tool' for '{tool_name}' via MCP session...")
+ response: CallToolResult = await current_session.call_tool(tool_name, input_data)
+ PrintStyle(font_color="green").print(f"MCPClientBase ({self.server.name}): Tool '{tool_name}' call successful via session.")
+ return response
- with self.__lock:
- for tool in self.tools:
- if tool["name"] == tool_name:
- response: CallToolResult = await self.session.call_tool(tool_name, input_data)
- # after connect have to close the stack within this function
- await self.exit_stack.aclose()
- return response
- raise ValueError(f"Tool {tool_name} not found")
+ try:
+ return await self._execute_with_session(call_tool_op)
+ except Exception as e:
+ # Error logged by _execute_with_session. Re-raise a specific error for the caller.
+ PrintStyle(background_color="#AA4455", font_color="white", padding=True).print(
+ f"MCPClientBase ({self.server.name}): 'call_tool' operation for '{tool_name}' failed: {type(e).__name__}: {e}"
+ )
+ raise ConnectionError(f"MCPClientBase::Failed to call tool '{tool_name}' on server '{self.server.name}'. Original error: {type(e).__name__}: {e}")
class MCPClientLocal(MCPClientBase):
- async def _connect_client(self) -> tuple[MemoryObjectReceiveStream[JSONRPCMessage | Exception], MemoryObjectSendStream[JSONRPCMessage]]:
+ async def _create_stdio_transport(self, current_exit_stack: AsyncExitStack) -> tuple[MemoryObjectReceiveStream[JSONRPCMessage | Exception], MemoryObjectSendStream[JSONRPCMessage]]:
"""Connect to an MCP server, init client and save stdio/write streams"""
server: MCPServerLocal = cast(MCPServerLocal, self.server)
if not which(server.command):
raise ValueError(f"Command {server.command} not found")
- # which_args = 0
- # for arg in server.args:
- # if which(arg):
- # which_args = which_args + 1
- # if which_args == 0:
- # raise ValueError(f"None of the arguments {server.args} is a file")
-
server_params = StdioServerParameters(
command=server.command,
args=server.args,
@@ -469,15 +567,15 @@ class MCPClientLocal(MCPClientBase):
encoding=server.encoding,
encoding_error_handler=server.encoding_error_handler
)
- stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
+ stdio_transport = await current_exit_stack.enter_async_context(stdio_client(server_params))
return stdio_transport
class MCPClientRemote(MCPClientBase):
- async def _connect_client(self) -> tuple[MemoryObjectReceiveStream[JSONRPCMessage | Exception], MemoryObjectSendStream[JSONRPCMessage]]:
+ async def _create_stdio_transport(self, current_exit_stack: AsyncExitStack) -> tuple[MemoryObjectReceiveStream[JSONRPCMessage | Exception], MemoryObjectSendStream[JSONRPCMessage]]:
"""Connect to an MCP server, init client and save stdio/write streams"""
server: MCPServerRemote = cast(MCPServerRemote, self.server)
- stdio_transport = await self.exit_stack.enter_async_context(
+ stdio_transport = await current_exit_stack.enter_async_context(
sse_client(url=server.url, headers=server.headers, timeout=server.timeout, sse_read_timeout=server.sse_read_timeout)
)
return stdio_transport
diff --git a/python/helpers/settings.py b/python/helpers/settings.py
index 9e45f2b87..c163c8051 100644
--- a/python/helpers/settings.py
+++ b/python/helpers/settings.py
@@ -890,13 +890,16 @@ def _apply_settings(previous: Settings | None):
async def update_mcp_settings(mcp_servers: str):
PrintStyle(background_color="black", font_color="white", padding=True).print("Updating MCP config...")
- AgentContext.first().log.log(type="info", content="Updating MCP settings...", temp=True)
+ first_context = AgentContext.first()
+ if first_context:
+ first_context.log.log(type="info", content="Updating MCP settings...", temp=True)
mcp_config = MCPConfig.get_instance()
try:
MCPConfig.update(mcp_servers)
except Exception as e:
- AgentContext.first().log.log(type="warning", content=f"Failed to update MCP settings: {e}", temp=False)
+ if first_context:
+ first_context.log.log(type="warning", content=f"Failed to update MCP settings: {e}", temp=False)
(
PrintStyle(background_color="red", font_color="black", padding=True)
.print("Failed to update MCP settings")
@@ -913,7 +916,8 @@ def _apply_settings(previous: Settings | None):
PrintStyle(background_color="#334455", font_color="white", padding=False)
.print(mcp_config.model_dump_json())
)
- AgentContext.first().log.log(type="info", content="Finished updating MCP settings :)", temp=True)
+ if first_context:
+ first_context.log.log(type="info", content="Finished updating MCP settings :)", temp=True)
task2 = defer.DeferredTask().start_task(
update_mcp_settings, config.mcp_servers