Agent Zero AI framework
Edit: Cleaned up MCP logs and check attempts.
deci673435c7728e
diff --git a/initialize.py b/initialize.pyindex 0ca586999..ddb6b39d6 100644--- a/initialize.py+++ b/initialize.py@@ -8,6 +8,9 @@ import shutilfrom python.helpers.print_style import PrintStyle+_NPM_CHECKS_DONE = False++# Helper function to ensure an MCP package is globally installeddef _ensure_mcp_package_globally_installed(package_name: str, executable_name: str):PrintStyle(background_color="blue", font_color="white", padding=True).print(@@ -56,10 +59,11 @@ def _ensure_mcp_package_globally_installed(package_name: str, executable_name: sPrintStyle(font_color="red", padding=True).print(f"ERROR: 'npm' command not found. Cannot check for or install '{executable_name}' from '{package_name}'.")- PrintStyle().print() # For a blank line after each attempt+ # PrintStyle().print() # For a blank line after each attemptdef initialize():+ global _NPM_CHECKS_DONEcurrent_settings = settings.get_settings()mcp_servers_json_string = current_settings.get("mcp_servers", "[]")@@ -76,48 +80,50 @@ def initialize():)mcp_server_configs = []- if shutil.which("npm"):- for server_config in mcp_server_configs:- if not isinstance(server_config, dict):- PrintStyle(font_color="orange", padding=True).print(- f"Warning: Skipping MCP server config item as it's not a dictionary: {server_config}"- )- continue-- command = server_config.get("command")- args = server_config.get("args", [])- server_name = server_config.get("name", "Unknown MCP Server")-- if command == "npx" and "--package" in args:- try:- package_keyword_index = args.index("--package")- # Expect package name at +1 and executable name at +2 from "--package"- if package_keyword_index + 2 < len(args):- package_name = args[package_keyword_index + 1]- executable_name = args[package_keyword_index + 2]- if package_name and executable_name: # Ensure they are not empty strings- _ensure_mcp_package_globally_installed(package_name, executable_name)+ if not _NPM_CHECKS_DONE:+ if shutil.which("npm"):+ for server_config in mcp_server_configs:+ if not isinstance(server_config, dict):+ PrintStyle(font_color="orange", padding=True).print(+ f"Warning: Skipping MCP server config item as it's not a dictionary: {server_config}"+ )+ continue++ command = server_config.get("command")+ args = server_config.get("args", [])+ server_name = server_config.get("name", "Unknown MCP Server")++ if command == "npx" and "--package" in args:+ try:+ package_keyword_index = args.index("--package")+ # Expect package name at +1 and executable name at +2 from "--package"+ if package_keyword_index + 2 < len(args):+ package_name = args[package_keyword_index + 1]+ executable_name = args[package_keyword_index + 2]+ if package_name and executable_name: # Ensure they are not empty strings+ _ensure_mcp_package_globally_installed(package_name, executable_name)+ else:+ PrintStyle(font_color="orange", padding=True).print(+ f"Warning: Skipping MCP server '{server_name}' due to empty package or executable name extracted from args: {args}"+ )else:PrintStyle(font_color="orange", padding=True).print(- f"Warning: Skipping MCP server '{server_name}' due to empty package or executable name extracted from args: {args}"+ f"Warning: Skipping MCP server '{server_name}' as package name or executable name could not be determined from args: {args}")- else:+ except ValueError: # Should not happen if "--package" is in args, but good for safetyPrintStyle(font_color="orange", padding=True).print(- f"Warning: Skipping MCP server '{server_name}' as package name or executable name could not be determined from args: {args}"+ f"Warning: '--package' keyword found but .index() failed for args: {args} in server '{server_name}'")- except ValueError: # Should not happen if "--package" is in args, but good for safety- PrintStyle(font_color="orange", padding=True).print(- f"Warning: '--package' keyword found but .index() failed for args: {args} in server '{server_name}'"- )- except Exception as e:- PrintStyle(font_color="red", padding=True).print(- f"Error processing npx args for server '{server_name}': {e}. Args: {args}"- )- else:- PrintStyle(font_color="red", padding=True).print(- "ERROR: 'npm' command not found. Cannot attempt to install any MCP server packages."- )- PrintStyle().print() # Extra blank line after all attempts or npm not found message+ except Exception as e:+ PrintStyle(font_color="red", padding=True).print(+ f"Error processing npx args for server '{server_name}': {e}. Args: {args}"+ )+ else:+ PrintStyle(font_color="red", padding=True).print(+ "ERROR: 'npm' command not found. Cannot attempt to install any MCP server packages."+ )+ PrintStyle().print() # Extra blank line after all attempts or npm not found message+ _NPM_CHECKS_DONE = True# chat model from user settingschat_llm = ModelConfig(diff --git a/python/helpers/mcp_handler.py b/python/helpers/mcp_handler.pyindex 1393ad7be..de51ebc90 100644--- a/python/helpers/mcp_handler.py+++ b/python/helpers/mcp_handler.py@@ -326,7 +326,7 @@ class MCPConfig(BaseModel):from collections.abc import Mapping, Iterable# DEBUG: Print the received servers_list- PrintStyle(background_color="blue", font_color="white", padding=True).print(f"MCPConfig.__init__ received servers_list: {servers_list}")+ if 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)`,@@ -501,11 +501,11 @@ class MCPClientBase(ABC):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}'...")+ # 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...")+ # PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name} - {operation_name}): Transport created. Initializing session...")session = await temp_stack.enter_async_context(ClientSession(stdio,@@ -514,11 +514,11 @@ class MCPClientBase(ABC):))await session.initialize()- PrintStyle(font_color="green").print(f"MCPClientBase ({self.server.name} - {operation_name}): Session initialized.")+ # 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.")+ # PrintStyle(font_color="green").print(f"MCPClientBase ({self.server.name} - {operation_name}): Operation successful.")return resultexcept Exception as e:PrintStyle(background_color="#AA4455", font_color="white", padding=False).print(@@ -534,7 +534,7 @@ class MCPClientBase(ABC):raise RuntimeError(f"MCPClientBase ({self.server.name} - {operation_name}): _execute_with_session exited 'async with' block unexpectedly.")async def update_tools(self) -> "MCPClientBase":- PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name}): Starting 'update_tools' operation...")+ # 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()@@ -571,7 +571,7 @@ class MCPClientBase(ABC):return self.toolsasync def call_tool(self, tool_name: str, input_data: Dict[str, Any]) -> CallToolResult:- PrintStyle(font_color="cyan").print(f"MCPClientBase ({self.server.name}): Preparing for 'call_tool' operation for tool '{tool_name}'.")+ # 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):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@@ -581,9 +581,9 @@ class MCPClientBase(ABC):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...")+ # 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.")+ # PrintStyle(font_color="green").print(f"MCPClientBase ({self.server.name}): Tool '{tool_name}' call successful via session.")return responsetry: