Skip to content

Agent Zero AI framework

mcp wip

frdeld3b798cb476e
diff --git a/initialize.py b/initialize.py
index c7789327a..9c85acf68 100644
--- a/initialize.py
+++ b/initialize.py
@@ -2,188 +2,16 @@ import asyncio
import json
import models
from agent import AgentConfig, ModelConfig
-from python.helpers import dotenv, files, rfc_exchange, runtime, settings, docker, log
+from python.helpers import dotenv, files, rfc_exchange, runtime, settings, docker, log, defer
import subprocess
import shutil
from python.helpers.print_style import PrintStyle
+from python.helpers.mcp_handler import initialize_mcp
-# _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
-
def initialize():
- # global _NPM_CHECKS_DONE
current_settings = settings.get_settings()
- # 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 = []
-
- # 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":
- # 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 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
-
- # 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
# chat model from user settings
chat_llm = ModelConfig(
@@ -253,23 +81,28 @@ def initialize():
# update config with runtime args
args_override(config)
- import python.helpers.mcp_handler as mcp_helper
- import agent as agent_helper
- import python.helpers.print_style as print_style_helper
- if not mcp_helper.MCPConfig.get_instance().is_initialized():
- try:
- mcp_helper.MCPConfig.update(config.mcp_servers)
- except Exception as e:
- first_context = agent_helper.AgentContext.first()
- if first_context:
- (
- first_context.log
- .log(type="warning", content=f"Failed to update MCP settings: {e}", temp=False)
- )
- (
- print_style_helper.PrintStyle(background_color="black", font_color="red", padding=True)
- .print(f"Failed to update MCP settings: {e}")
- )
+ # initialize MCP in deferred task to prevent blocking the main thread
+ async def initialize_mcp_async(mcp_servers_config: str):
+ return initialize_mcp(mcp_servers_config)
+ defer.DeferredTask(thread_name="mcp-initializer").start_task(initialize_mcp_async, config.mcp_servers)
+
+ # import python.helpers.mcp_handler as mcp_helper
+ # import agent as agent_helper
+ # import python.helpers.print_style as print_style_helper
+ # if not mcp_helper.MCPConfig.get_instance().is_initialized():
+ # try:
+ # mcp_helper.MCPConfig.update(config.mcp_servers)
+ # except Exception as e:
+ # first_context = agent_helper.AgentContext.first()
+ # if first_context:
+ # (
+ # first_context.log
+ # .log(type="warning", content=f"Failed to update MCP settings: {e}", temp=False)
+ # )
+ # (
+ # print_style_helper.PrintStyle(background_color="black", font_color="red", padding=True)
+ # .print(f"Failed to update MCP settings: {e}")
+ # )
# return config object
return config
diff --git a/python/api/mcp_servers_status.py b/python/api/mcp_servers_status.py
new file mode 100644
index 000000000..8d25dcb7b
--- /dev/null
+++ b/python/api/mcp_servers_status.py
@@ -0,0 +1,16 @@
+from python.helpers.api import ApiHandler
+from flask import Request, Response
+
+from typing import Any
+
+from python.helpers.mcp_handler import MCPConfig
+
+
+class McpServersStatuss(ApiHandler):
+ async def process(self, input: dict[Any, Any], request: Request) -> dict[Any, Any] | Response:
+
+ # try:
+ status = MCPConfig.get_instance().get_servers_status()
+ return {"success": True, "status": status}
+ # except Exception as e:
+ # return {"success": False, "error": str(e)}
diff --git a/python/helpers/mcp_handler.py b/python/helpers/mcp_handler.py
index 2f0d9f75e..d96b62f7f 100644
--- a/python/helpers/mcp_handler.py
+++ b/python/helpers/mcp_handler.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+import re
from typing import List, Dict, Optional, Any, Union, Literal, Annotated, ClassVar, cast, Callable, Awaitable, TypeVar
import threading
import asyncio
@@ -20,10 +21,36 @@ from anyio.streams.memory import (
)
from pydantic import BaseModel, Field, Discriminator, Tag, PrivateAttr
+from python.helpers import dirty_json
from python.helpers.dirty_json import DirtyJson
from python.helpers.print_style import PrintStyle
from python.helpers.tool import Tool, Response
+def normalize_name(name: str) -> str:
+ # Lowercase and strip whitespace
+ name = name.strip().lower()
+ # Replace all non-alphanumeric (unicode) chars with underscore
+ # \W matches non-alphanumeric, but also matches underscore, so use [^\w] with re.UNICODE
+ # To also replace underscores from non-latin chars, use [^a-zA-Z0-9] with re.UNICODE
+ name = re.sub(r'[^\w]', '_', name, flags=re.UNICODE)
+ return name
+
+def initialize_mcp(mcp_servers_config:str):
+ if not MCPConfig.get_instance().is_initialized():
+ try:
+ MCPConfig.update(mcp_servers_config)
+ except Exception as e:
+ from agent import AgentContext
+ first_context = AgentContext.first() # TODO replace with better reporting
+ if first_context:
+ (
+ first_context.log
+ .log(type="warning", content=f"Failed to update MCP settings: {e}", temp=False)
+ )
+ (
+ PrintStyle(background_color="black", font_color="red", padding=True)
+ .print(f"Failed to update MCP settings: {e}")
+ )
class MCPTool(Tool):
"""MCP Tool wrapper"""
@@ -159,7 +186,7 @@ class MCPServerRemote(BaseModel):
for key, value in config.items():
if key in ["name", "description", "url", "headers", "timeout", "sse_read_timeout", "disabled"]:
if key == "name":
- value = value.strip().lower().replace(" ", "_").replace("-", "_").replace(".", "_")
+ value = normalize_name(value)
setattr(self, key, value)
# We already run in an event loop, dont believe Pylance
return asyncio.run(self.__on_update())
@@ -208,7 +235,7 @@ class MCPServerLocal(BaseModel):
for key, value in config.items():
if key in ["name", "description", "command", "args", "env", "encoding", "encoding_error_handler", "disabled"]:
if key == "name":
- value = value.strip().lower().replace(" ", "_").replace("-", "_").replace(".", "_")
+ value = normalize_name(value)
setattr(self, key, value)
# We already run in an event loop, dont believe Pylance
return asyncio.run(self.__on_update())
@@ -228,11 +255,9 @@ MCPServer = Annotated[
class MCPConfig(BaseModel):
- servers: List[MCPServer] = Field(default_factory=list[MCPServer])
-
+ servers: list[MCPServer] = Field(default_factory=list)
+ disconnected_servers: list[dict[str, Any]] = Field(default_factory=list)
__lock: ClassVar[threading.Lock] = PrivateAttr(default=threading.Lock())
-
- # Singleton instance
__instance: ClassVar[Any] = PrivateAttr(default=None)
__initialized: ClassVar[bool] = PrivateAttr(default=False)
@@ -250,12 +275,12 @@ class MCPConfig(BaseModel):
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)
+ parsed_value = dirty_json.try_parse(config_str)
+ normalized = cls.normalize_config(parsed_value)
- if isinstance(parsed_value, list):
+ if isinstance(normalized, list):
valid_servers = []
- for item in parsed_value:
+ for item in normalized:
if isinstance(item, dict):
valid_servers.append(item)
else:
@@ -269,32 +294,34 @@ class MCPConfig(BaseModel):
)
# 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
+ PrintStyle.error(f"Error parsing MCP config string: {e_json}. Config string was: '{config_str}'")
+
+ # # 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()
@@ -322,6 +349,29 @@ class MCPConfig(BaseModel):
cls.__initialized = True
return instance
+ @classmethod
+ def normalize_config(cls, servers: Any):
+ normalized = []
+ if isinstance(servers, list):
+ for server in servers:
+ if isinstance(server, dict):
+ normalized.append(server)
+ elif isinstance(servers, dict):
+ if "mcpServers" in servers:
+ if isinstance(servers["mcpServers"], dict):
+ for key, value in servers["mcpServers"].items():
+ if isinstance(value, dict):
+ value["name"] = key
+ normalized.append(value)
+ elif isinstance(servers["mcpServers"], list):
+ for server in servers["mcpServers"]:
+ if isinstance(server, dict):
+ normalized.append(server)
+ else:
+ normalized.append(servers) # single server?
+ return normalized
+
+
def __init__(self, servers_list: List[Dict[str, Any]]):
from collections.abc import Mapping, Iterable
@@ -335,7 +385,9 @@ class MCPConfig(BaseModel):
super().__init__()
# Clear any servers potentially initialized by super().__init__() before we populate based on servers_list
- self.servers = []
+ self.servers = []
+ # initialize failed servers list
+ self.disconnected_servers = []
if not isinstance(servers_list, Iterable):
(
@@ -346,21 +398,49 @@ class MCPConfig(BaseModel):
for server_item in servers_list:
if not isinstance(server_item, Mapping):
+ # log the error
+ error_msg = "server_item must be a mapping"
(
PrintStyle(background_color="grey", font_color="red", padding=True)
- .print("MCPConfig::__init__::server_item must be a mapping")
+ .print(f"MCPConfig::__init__::{error_msg}")
)
+ # add to failed servers with generic name
+ self.disconnected_servers.append({
+ "config": server_item if isinstance(server_item, dict) else {"raw": str(server_item)},
+ "error": error_msg,
+ "name": "invalid_server_config"
+ })
continue
if server_item.get("disabled", False):
+ # get server name if available
+ server_name = server_item.get("name", "unnamed_server")
+ # normalize server name if it exists
+ if server_name != "unnamed_server":
+ server_name = normalize_name(server_name)
+
+ # add to failed servers
+ self.disconnected_servers.append({
+ "config": server_item,
+ "error": "Disabled in config",
+ "name": server_name
+ })
continue
server_name = server_item.get("name", "__not__found__")
if server_name == "__not__found__":
+ # log the error
+ error_msg = "server_name is required"
(
PrintStyle(background_color="grey", font_color="red", padding=True)
- .print("MCPConfig::__init__::server_name is required")
+ .print(f"MCPConfig::__init__::{error_msg}")
)
+ # add to failed servers
+ self.disconnected_servers.append({
+ "config": server_item,
+ "error": error_msg,
+ "name": "unnamed_server"
+ })
continue
try:
@@ -370,12 +450,53 @@ class MCPConfig(BaseModel):
else:
self.servers.append(MCPServerLocal(server_item))
except Exception as e:
+ # log the error
+ error_msg = str(e)
(
PrintStyle(background_color="grey", font_color="red", padding=True)
- .print(f"MCPConfig::__init__: Failedto create MCPServer '{server_name}': {e}")
+ .print(f"MCPConfig::__init__: Failed to create MCPServer '{server_name}': {error_msg}")
)
- continue
-
+ # add to failed servers
+ self.disconnected_servers.append({
+ "config": server_item,
+ "error": error_msg,
+ "name": server_name
+ })
+
+ def get_servers_status(self) -> list[dict[str, Any]]:
+ """Get status of all servers"""
+ result = []
+ with self.__lock:
+ # add connected/working servers
+ for server in self.servers:
+ # get server name
+ name = server.name
+ # get tool count
+ tool_count = len(server.get_tools())
+ # check if server is connected
+ connected = tool_count > 0
+ # get error message if any
+ error = ""
+
+ # add server status to result
+ result.append({
+ "name": name,
+ "connected": connected,
+ "error": error,
+ "tool_count": tool_count
+ })
+
+ # add failed servers
+ for disconnected in self.disconnected_servers:
+ result.append({
+ "name": disconnected["name"],
+ "connected": False,
+ "error": disconnected["error"],
+ "tool_count": 0
+ })
+
+ return result
+
def is_initialized(self) -> bool:
"""Check if the client is initialized"""
with self.__lock:
@@ -511,10 +632,17 @@ class MCPClientBase(ABC):
ClientSession(
stdio,
write,
- read_timeout_seconds=timedelta(seconds=600)
+ read_timeout_seconds=timedelta(seconds=600)
)
)
- await session.initialize()
+ try:
+ # Add timeout to session.initialize
+ await asyncio.wait_for(session.initialize(), timeout=10)
+ except Exception as e:
+ PrintStyle(background_color="#AA4455", font_color="white", padding=False).print(
+ f"MCPClientBase ({self.server.name} - {operation_name}): Session initialization failed: {type(e).__name__}: {e}"
+ )
+ raise
# PrintStyle(font_color="green").print(f"MCPClientBase ({self.server.name} - {operation_name}): Session initialized.")
result = await coro_func(session)
diff --git a/python/helpers/settings.py b/python/helpers/settings.py
index 4d81ab65c..c2078cde8 100644
--- a/python/helpers/settings.py
+++ b/python/helpers/settings.py
@@ -912,7 +912,7 @@ def get_default_settings() -> Settings:
stt_silence_threshold=0.3,
stt_silence_duration=1000,
stt_waiting_timeout=2000,
- mcp_servers="",
+ mcp_servers='{\n "mcpServers": {}\n}',
mcp_server_enabled=False,
)
diff --git a/webui/components/settings/mcp/client/mcp-servers-store.js b/webui/components/settings/mcp/client/mcp-servers-store.js
index cb7954a5d..9b0b24598 100644
--- a/webui/components/settings/mcp/client/mcp-servers-store.js
+++ b/webui/components/settings/mcp/client/mcp-servers-store.js
@@ -1,17 +1,13 @@
import { createStore } from "/js/AlpineStore.js";
import { scrollModal } from "/js/modals.js";
import sleep from "/js/sleep.js";
+import * as API from "/js/api.js";
const model = {
editor: null,
- settingsJsonField: settingsModalProxy.settings.sections
- .filter((x) => x.id == "mcp_client")[0]
- .fields.filter((x) => x.id == "mcp_servers")[0],
- servers: [
- { connected: true, name: "Server 1", tools: 10 },
- { connected: false, name: "Server 2", tools: 0, error: "Server is disabled in configuration" },
- ],
+ servers: [],
loading: false,
+ statusCheck: false,
async initialize() {
// Initialize the JSON Viewer after the modal is rendered
@@ -27,11 +23,13 @@ const model = {
}
editor.session.setMode("ace/mode/json");
- const json = this.settingsJsonField.value;
+ const json = this.getSettingsFieldConfigJson().value;
editor.setValue(json);
editor.clearSelection();
this.editor = editor;
}
+
+ this.startStatusCheck();
},
formatJson() {
@@ -55,18 +53,56 @@ const model = {
}
},
+ getEditorValue() {
+ return this.editor.getValue();
+ },
+
+ getSettingsFieldConfigJson() {
+ return settingsModalProxy.settings.sections
+ .filter((x) => x.id == "mcp_client")[0]
+ .fields.filter((x) => x.id == "mcp_servers")[0];
+ },
+
onClose() {
- const val = this.editor.getValue();
- this.settingsJsonField.value = val;
+ const val = this.getEditorValue();
+ this.getSettingsFieldConfigJson().value = val;
+ this.stopStatusCheck();
+ },
+
+ async startStatusCheck() {
+ this.statusCheck = true;
+
+ while (this.statusCheck) {
+ await this._statusCheck();
+ await sleep(3000);
+ }
+ },
+
+ async _statusCheck() {
+ const resp = await API.callJsonApi("mcp_servers_status", null);
+ if (resp.success) {
+ this.servers = resp.status;
+ }
+ },
+
+ async stopStatusCheck() {
+ this.statusCheck = false;
},
async applyNow() {
if (this.loading) return;
this.loading = true;
+ try {
scrollModal("mcp-servers-status");
- await sleep(1000);
+ await API.callJsonApi("mcp_servers_apply", {
+ mcp_servers: this.getEditorValue(),
+ });
scrollModal("mcp-servers-status");
- this.loading = false;
+ } catch (error) {
+ console.error("Failed to apply MCP servers:", error);
+ alert("Failed to apply MCP servers: " + error.message);
+ }
+ this.loading = false;
},
};
diff --git a/webui/components/settings/mcp/client/mcp-servers.html b/webui/components/settings/mcp/client/mcp-servers.html
index 6d95a7b63..eba391bb4 100644
--- a/webui/components/settings/mcp/client/mcp-servers.html
+++ b/webui/components/settings/mcp/client/mcp-servers.html
@@ -21,21 +21,30 @@
</h3>
<div id="mcp-servers-config-json"></div>
- <h3 id="mcp-servers-status">Status</h3>
+ <h3 id="mcp-servers-status">Servers status (refreshing automatically)</h3>
<div class="server-list">
<template x-for="server in $store.mcpServersStore.servers" :key="server.name">
<div class="server-item">
- <span class="status-indicator"
- :class="server.connected ? 'connected' : 'disconnected'"></span>
+ <div class="status-icon" style="margin-right: 0.5em;" x-data="{ connected: server.connected }">
+ <svg viewBox="0 0 30 30">
+ <!-- Connected State (filled circle) -->
+ <circle class="connected-circle" cx="15" cy="15" r="8"
+ x-bind:fill="server.connected ? '#00c340' : 'none'" x-bind:opacity="server.connected ? 1 : 0" />
+
+ <!-- Disconnected State (outline circle) -->
+ <circle class="disconnected-circle" cx="15" cy="15" r="9" fill="none" stroke="#e40138"
+ stroke-width="3" x-bind:opacity="server.connected ? 0 : 1" />
+ </svg>
+ </div>
<span class="server-name" x-text="server.name"></span>
<span class="server-tools"
- x-text="'- ' + (server.tools ? server.tools : 0) + ' tools'"></span>
+ x-text="'- ' + (server.tool_count ? server.tool_count : 0) + ' tools'"></span>
<span class="server-error" x-show="server.error" x-text="server.error"></span>
</div>
</template>
<div x-show="$store.mcpServersStore.servers.length === 0" class="no-servers">
- No servers connected
+ No servers
</div>
</div>
diff --git a/webui/js/api.js b/webui/js/api.js
new file mode 100644
index 000000000..d5f1d9ba1
--- /dev/null
+++ b/webui/js/api.js
@@ -0,0 +1,23 @@
+/**
+ * Call a JSON-in JSON-out API endpoint
+ * Data is automatically serialized
+ * @param {string} endpoint - The API endpoint to call
+ * @param {any} data - The data to send to the API
+ * @returns {Promise<any>} The JSON response from the API
+ */
+export async function callJsonApi(endpoint, data) {
+ const response = await fetch(endpoint, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(error);
+ }
+ const jsonResponse = await response.json();
+ return jsonResponse;
+}