Agent Zero AI framework
MCP client merge
frdel922a4a71d570
diff --git a/docker/base/fs/ins/install_base_packages.sh b/docker/base/fs/ins/install_base_packages.shindex b0d768ee7..b6071b2e9 100644--- a/docker/base/fs/ins/install_base_packages.sh+++ b/docker/base/fs/ins/install_base_packages.sh@@ -6,4 +6,8 @@ echo "====================BASE PACKAGES START===================="apt-get install -y --no-install-recommends \nodejs npm openssh-server sudo curl wget git ffmpeg supervisor cron+echo "====================BASE PACKAGES NPM===================="++npm i -g npx shx+echo "====================BASE PACKAGES END===================="diff --git a/initialize.py b/initialize.pyindex a1bab8a07..c7789327a 100644--- a/initialize.py+++ b/initialize.py@@ -8,182 +8,182 @@ import shutilfrom python.helpers.print_style import PrintStyle-_NPM_CHECKS_DONE = False+# _NPM_CHECKS_DONE = False-# Helper function to ensure an MCP package is globally installed-def _ensure_mcp_package_globally_installed(package_name: str, executable_name: str):- PrintStyle(background_color="blue", font_color="white", padding=True).print(- f"Attempting to ensure MCP server executable '{executable_name}' (from package '{package_name}') is available..."- )- if shutil.which("npm"):- if not shutil.which(executable_name):- PrintStyle(font_color="yellow", padding=True).print(- f"'{executable_name}' not found in PATH. Attempting global npm install of '{package_name}'..."- )- try:- npm_command = ["npm", "i", "-g", package_name, "--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(- f"Successfully installed '{package_name}' globally via npm."- )- if shutil.which(executable_name):- PrintStyle(font_color="green", padding=True).print(- f"'{executable_name}' is now available in PATH after install."- )- return True # Successfully installed and found- else:- PrintStyle(font_color="orange", padding=True).print(- f"WARNING: npm install of '{package_name}' reported success, but '{executable_name}' still not found in PATH. " +- "The 'npx' command in settings.json might still be necessary or there might be an issue with PATH."- )- return False # Install reported success, but executable not found- else:- PrintStyle(font_color="red", padding=True).print(- f"Failed to install '{package_name}' 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()}")- return False # Install failed- except FileNotFoundError:- PrintStyle(font_color="red", padding=True).print(- f"ERROR: 'npm' command not found. Cannot attempt to install '{package_name}'."- )- return False # npm not found- except Exception as e:- PrintStyle(font_color="red", padding=True).print(- f"Exception during npm install of '{package_name}': {e}"- )- return False # Other exception during install- else:- PrintStyle(font_color="green", padding=True).print(- f"'{executable_name}' (from package '{package_name}') already found in PATH."- )- return True # Already found in PATH- else:- PrintStyle(font_color="red", padding=True).print(- f"ERROR: 'npm' command not found. Cannot check for or install '{executable_name}' from '{package_name}'."- )- return False # npm command not found, cannot check or install- # Fallback, though logic above should cover all paths to return explicitly- return False+# # Helper function to ensure an MCP package is globally installed+# def _ensure_mcp_package_globally_installed(package_name: str, executable_name: str):+# PrintStyle(background_color="blue", font_color="white", padding=True).print(+# f"Attempting to ensure MCP server executable '{executable_name}' (from package '{package_name}') is available..."+# )+# if shutil.which("npm"):+# if not shutil.which(executable_name):+# PrintStyle(font_color="yellow", padding=True).print(+# f"'{executable_name}' not found in PATH. Attempting global npm install of '{package_name}'..."+# )+# try:+# npm_command = ["npm", "i", "-g", package_name, "--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(+# f"Successfully installed '{package_name}' globally via npm."+# )+# if shutil.which(executable_name):+# PrintStyle(font_color="green", padding=True).print(+# f"'{executable_name}' is now available in PATH after install."+# )+# return True # Successfully installed and found+# else:+# PrintStyle(font_color="orange", padding=True).print(+# f"WARNING: npm install of '{package_name}' reported success, but '{executable_name}' still not found in PATH. " ++# "The 'npx' command in settings.json might still be necessary or there might be an issue with PATH."+# )+# return False # Install reported success, but executable not found+# else:+# PrintStyle(font_color="red", padding=True).print(+# f"Failed to install '{package_name}' 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()}")+# return False # Install failed+# except FileNotFoundError:+# PrintStyle(font_color="red", padding=True).print(+# f"ERROR: 'npm' command not found. Cannot attempt to install '{package_name}'."+# )+# return False # npm not found+# except Exception as e:+# PrintStyle(font_color="red", padding=True).print(+# f"Exception during npm install of '{package_name}': {e}"+# )+# return False # Other exception during install+# else:+# PrintStyle(font_color="green", padding=True).print(+# f"'{executable_name}' (from package '{package_name}') already found in PATH."+# )+# return True # Already found in PATH+# else:+# PrintStyle(font_color="red", padding=True).print(+# f"ERROR: 'npm' command not found. Cannot check for or install '{executable_name}' from '{package_name}'."+# )+# return False # npm command not found, cannot check or install+# # Fallback, though logic above should cover all paths to return explicitly+# return Falsedef initialize():- global _NPM_CHECKS_DONE+ # global _NPM_CHECKS_DONEcurrent_settings = settings.get_settings()- mcp_servers_json_string = current_settings.get("mcp_servers", "[]")+ # mcp_servers_json_string = current_settings.get("mcp_servers", "[]")- try:- mcp_server_configs = json.loads(mcp_servers_json_string)- if not isinstance(mcp_server_configs, list):- PrintStyle(font_color="red", padding=True).print(- f"Error: Parsed mcp_servers from settings is not a list. Value: {mcp_server_configs}"- )- mcp_server_configs = []- except json.JSONDecodeError as e:- PrintStyle(font_color="red", padding=True).print(- f"Error decoding mcp_servers JSON string from settings: {e}. String was: '{mcp_servers_json_string}'"- )- mcp_server_configs = []+ # try:+ # mcp_server_configs = json.loads(mcp_servers_json_string)+ # if not isinstance(mcp_server_configs, list):+ # PrintStyle(font_color="red", padding=True).print(+ # f"Error: Parsed mcp_servers from settings is not a list. Value: {mcp_server_configs}"+ # )+ # mcp_server_configs = []+ # except json.JSONDecodeError as e:+ # PrintStyle(font_color="red", padding=True).print(+ # f"Error decoding mcp_servers JSON string from settings: {e}. String was: '{mcp_servers_json_string}'"+ # )+ # mcp_server_configs = []- 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+ # 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")+ # command = server_config.get("command")+ # args = server_config.get("args", [])+ # server_name = server_config.get("name", "Unknown MCP Server")- if command == "npx":- package_name_for_install = None- executable_name_to_check = None+ # if command == "npx":+ # package_name_for_install = None+ # executable_name_to_check = None- if "--package" in args: # Original logic for npx --package <pkg> <exec>- 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_for_install = args[package_keyword_index + 1]- executable_name_to_check = args[package_keyword_index + 2]- else:- PrintStyle(font_color="orange", padding=True).print(- f"Warning: Skipping MCP server '{server_name}' (npx --package) as package or executable name could not be determined from args: {args}"- )- 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 --package args for server '{server_name}': {e}. Args: {args}"- )- else: # New logic for npx <pkg_arg> syntax- parsed_npx_pkg_arg = None- arg_idx = 0- while arg_idx < len(args):- current_arg = args[arg_idx]- # npx's own -p/--package option for temporary installs, distinct from the --package marker we check above- if current_arg == "-p" or current_arg == "--package":- arg_idx += 1 # Move to the value of -p/--package- if arg_idx < len(args): # Ensure there is a value- arg_idx += 1 # Skip the value itself- continue+ # if "--package" in args: # Original logic for npx --package <pkg> <exec>+ # 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_for_install = args[package_keyword_index + 1]+ # executable_name_to_check = args[package_keyword_index + 2]+ # else:+ # PrintStyle(font_color="orange", padding=True).print(+ # f"Warning: Skipping MCP server '{server_name}' (npx --package) as package or executable name could not be determined from args: {args}"+ # )+ # 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 --package args for server '{server_name}': {e}. Args: {args}"+ # )+ # else: # New logic for npx <pkg_arg> syntax+ # parsed_npx_pkg_arg = None+ # arg_idx = 0+ # while arg_idx < len(args):+ # current_arg = args[arg_idx]+ # # npx's own -p/--package option for temporary installs, distinct from the --package marker we check above+ # if current_arg == "-p" or current_arg == "--package":+ # arg_idx += 1 # Move to the value of -p/--package+ # if arg_idx < len(args): # Ensure there is a value+ # arg_idx += 1 # Skip the value itself+ # continue- if current_arg.startswith("-"): # Skip other options like -y, --yes, --no-install etc.- arg_idx += 1- continue+ # if current_arg.startswith("-"): # Skip other options like -y, --yes, --no-install etc.+ # arg_idx += 1+ # continue- # Found what we assume is the main package argument for npx- parsed_npx_pkg_arg = current_arg- break # Found the package, stop parsing args for this purpose+ # # Found what we assume is the main package argument for npx+ # parsed_npx_pkg_arg = current_arg+ # break # Found the package, stop parsing args for this purpose- if parsed_npx_pkg_arg:- package_name_for_install = parsed_npx_pkg_arg- # Derive assumed executable name based on convention from error: "mcp-server-google-maps" for "@.../server-google-maps"- # For "@scope/pkg-name" -> "pkg-name". For "pkg-name" -> "pkg-name".- name_part = parsed_npx_pkg_arg.split("/")[-1]- executable_name_to_check = f"mcp-{name_part}"- PrintStyle(font_color="blue", padding=True).print(- f"Info: For MCP server '{server_name}' (npx <pkg_arg> type), attempting to ensure global install of package '{package_name_for_install}' and expecting executable '{executable_name_to_check}'."- )- else:- PrintStyle(font_color="orange", padding=True).print(- f"Warning: Skipping MCP server '{server_name}' (npx <pkg_arg> type) as main package argument could not be identified from args: {args}"- )+ # if parsed_npx_pkg_arg:+ # package_name_for_install = parsed_npx_pkg_arg+ # # Derive assumed executable name based on convention from error: "mcp-server-google-maps" for "@.../server-google-maps"+ # # For "@scope/pkg-name" -> "pkg-name". For "pkg-name" -> "pkg-name".+ # name_part = parsed_npx_pkg_arg.split("/")[-1]+ # executable_name_to_check = f"mcp-{name_part}"+ # PrintStyle(font_color="blue", padding=True).print(+ # f"Info: For MCP server '{server_name}' (npx <pkg_arg> type), attempting to ensure global install of package '{package_name_for_install}' and expecting executable '{executable_name_to_check}'."+ # )+ # else:+ # PrintStyle(font_color="orange", padding=True).print(+ # f"Warning: Skipping MCP server '{server_name}' (npx <pkg_arg> type) as main package argument could not be identified from args: {args}"+ # )- # Unified call to ensure package is installed- if package_name_for_install and executable_name_to_check:- # Ensure they are not empty strings or just whitespace- if package_name_for_install.strip() and executable_name_to_check.strip():- install_successful = _ensure_mcp_package_globally_installed(package_name_for_install.strip(), executable_name_to_check.strip())- if not install_successful:- PrintStyle(font_color="red", padding=True).print(- f"Disabling MCP server '{server_name}' due to failed setup/validation for package '{package_name_for_install}' and/or executable '{executable_name_to_check}'."- )- server_config["disabled"] = True # Disable this server config- else:- PrintStyle(font_color="orange", padding=True).print(- f"Warning: Skipping MCP server '{server_name}' due to empty package or executable name derived: pkg='{package_name_for_install}', exec='{executable_name_to_check}' from args: {args}. Not attempting install."- )- # Optionally, consider if these should also be marked as disabled,- # though current logic implies they weren't valid enough to attempt install.- # server_config["disabled"] = True- # If package_name_for_install or executable_name_to_check are None or empty,- # it means previous logic decided not to proceed or couldn't determine them,- # and appropriate warnings would have been printed.- 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+ # # Unified call to ensure package is installed+ # if package_name_for_install and executable_name_to_check:+ # # Ensure they are not empty strings or just whitespace+ # if package_name_for_install.strip() and executable_name_to_check.strip():+ # install_successful = _ensure_mcp_package_globally_installed(package_name_for_install.strip(), executable_name_to_check.strip())+ # if not install_successful:+ # PrintStyle(font_color="red", padding=True).print(+ # f"Disabling MCP server '{server_name}' due to failed setup/validation for package '{package_name_for_install}' and/or executable '{executable_name_to_check}'."+ # )+ # server_config["disabled"] = True # Disable this server config+ # else:+ # PrintStyle(font_color="orange", padding=True).print(+ # f"Warning: Skipping MCP server '{server_name}' due to empty package or executable name derived: pkg='{package_name_for_install}', exec='{executable_name_to_check}' from args: {args}. Not attempting install."+ # )+ # # Optionally, consider if these should also be marked as disabled,+ # # though current logic implies they weren't valid enough to attempt install.+ # # server_config["disabled"] = True+ # # If package_name_for_install or executable_name_to_check are None or empty,+ # # it means previous logic decided not to proceed or couldn't determine them,+ # # and appropriate warnings would have been printed.+ # 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 de51ebc90..2f0d9f75e 100644--- a/python/helpers/mcp_handler.py+++ b/python/helpers/mcp_handler.py@@ -417,19 +417,20 @@ class MCPConfig(BaseModel):)tool_args = ""- properties: dict[str, Any] = tool["input_schema"]["properties"]- for key, value in properties.items():- tool_args += f" \"{key}\": \"...\",\n"- examples = ""- description = ""- if "examples" in value:- examples = f"(examples: {value['examples']})"- if "description" in value:- description = f": {value['description']}"- prompt += (- f" * {key} ({value['type']}){description} {examples}\n"- )- prompt += "\n"+ if "input_schema" in tool and "properties" in tool["input_schema"]:+ properties: dict[str, Any] = tool["input_schema"]["properties"]+ for key, value in properties.items():+ tool_args += f" \"{key}\": \"...\",\n"+ examples = ""+ description = ""+ if "examples" in value:+ examples = f"(examples: {value['examples']})"+ if "description" in value:+ description = f": {value['description']}"+ prompt += (+ f" * {key} ({value['type']}){description} {examples}\n"+ )+ prompt += "\n"prompt += (f"#### Usage:\n"diff --git a/python/helpers/settings.py b/python/helpers/settings.pyindex 46aed8c01..da45b6571 100644--- a/python/helpers/settings.py+++ b/python/helpers/settings.py@@ -537,16 +537,6 @@ def convert_out(settings: Settings) -> SettingsOutput:})- agent_fields.append(- {- "id": "mcp_servers",- "title": "MCP Servers",- "description": "(JSON list of) >> RemoteServer <<: [name, url, headers, timeout (opt), sse_read_timeout (opt), disabled (opt)] / >> Local Server <<: [name, command, args, env, encoding (opt), encoding_error_handler (opt), disabled (opt)]",- "type": "textarea",- "value": settings["mcp_servers"],- }- )-agent_section: SettingsSection = {"id": "agent","title": "Agent Config",@@ -693,7 +683,28 @@ def convert_out(settings: Settings) -> SettingsOutput:"tab": "agent",}+# MCP section+ mcp_client_fields: list[SettingsField] = []++ mcp_client_fields.append(+ {+ "id": "mcp_servers",+ "title": "MCP Servers",+ "description": "(JSON list of) >> RemoteServer <<: [name, url, headers, timeout (opt), sse_read_timeout (opt), disabled (opt)] / >> Local Server <<: [name, command, args, env, encoding (opt), encoding_error_handler (opt), disabled (opt)]",+ "type": "textarea",+ "value": settings["mcp_servers"],+ }+ )++ mcp_client_section: SettingsSection = {+ "id": "mcp_client",+ "title": "External MCP Servers",+ "description": "Agent Zero can use external MCP servers, local or remote as tools.",+ "fields": mcp_client_fields,+ "tab": "mcp",+ }+mcp_server_fields: list[SettingsField] = []mcp_server_fields.append(@@ -727,6 +738,7 @@ def convert_out(settings: Settings) -> SettingsOutput:stt_section,api_keys_section,auth_section,+ mcp_client_section,mcp_server_section,dev_section,]@@ -868,7 +880,6 @@ def get_default_settings() -> Settings:agent_prompts_subdir="default",agent_memory_subdir="default",agent_knowledge_subdir="custom",- mcp_servers="",rfc_auto_docker=True,rfc_url="localhost",rfc_password="",@@ -879,6 +890,7 @@ def get_default_settings() -> Settings:stt_silence_threshold=0.3,stt_silence_duration=1000,stt_waiting_timeout=2000,+ mcp_servers="",mcp_server_enabled=False,)