Agent Zero AI framework
mcp prototype
frdel5126dc9732bc
diff --git a/docker/base/fs/ins/install_python.sh b/docker/base/fs/ins/install_python.shindex 2745b5618..94bc6d995 100644--- a/docker/base/fs/ins/install_python.sh+++ b/docker/base/fs/ins/install_python.sh@@ -51,6 +51,6 @@ pip install torch --index-url https://download.pytorch.org/whl/cpuecho "====================PYTHON UV ===================="-curl -Ls https://astral.sh/uv/install.sh | sh+curl -Ls https://astral.sh/uv/install.sh | UV_INSTALL_DIR=/usr/local/bin shecho "====================PYTHON END===================="diff --git a/docker/run/fs/ins/post_install.sh b/docker/run/fs/ins/post_install.shindex 410ff19a7..c77f188e2 100644--- a/docker/run/fs/ins/post_install.sh+++ b/docker/run/fs/ins/post_install.sh@@ -2,4 +2,4 @@# Cleanup package listrm -rf /var/lib/apt/lists/*-apt-get clean\ No newline at end of file+# apt-get clean\ No newline at end of filediff --git a/python/api/mcp_servers_apply.py b/python/api/mcp_servers_apply.pyindex 9ebaab689..f5ebdd128 100644--- a/python/api/mcp_servers_apply.py+++ b/python/api/mcp_servers_apply.py@@ -3,15 +3,17 @@ from flask import Request, Responsefrom typing import Any-from python.helpers.mcp_handler import MCPConfig+# from python.helpers.mcp_handler import MCPConfig+from python.helpers.settings import set_settings_deltaclass McpServersApply(ApiHandler):async def process(self, input: dict[Any, Any], request: Request) -> dict[Any, Any] | Response:mcp_servers = input["mcp_servers"]- mcp_config = MCPConfig.get_instance()try:- MCPConfig.update(mcp_servers)+ # MCPConfig.update(mcp_servers) # done in settings automatically+ set_settings_delta({"mcp_servers": mcp_servers})+except Exception as e:return {"success": False, "error": str(e)}return {"success": True}diff --git a/python/helpers/mcp_handler.py b/python/helpers/mcp_handler.pyindex 68c3de190..8ff18ea8e 100644--- a/python/helpers/mcp_handler.py+++ b/python/helpers/mcp_handler.py@@ -167,24 +167,28 @@ class MCPTool(Tool):user_message_text[:max_user_context_len] + "... (truncated)")- contextual_block = f"""-\n--- End of Results for MCP Tool: {self.name} ---+# commented out for now, output should be unified between tools and MCPs-**Original Tool Call Details:**-* **Tool:** `{self.name}`-* **Arguments Given:**- ```json-{json.dumps(self.args, indent=2)}- ```+# contextual_block = f"""+# \n--- End of Results for MCP Tool: {self.name} ----**Related User Request Context:**-{user_message_text}+# **Original Tool Call Details:**+# * **Tool:** `{self.name}`+# * **Arguments Given:**+# ```json+# {json.dumps(self.args, indent=2)}+# ```-**Next Steps Reminder for {self.name}:**-If this action is part of an ongoing sequence, consider the next step with this tool or another appropriate tool. If the sequence is complete or this was a one-off action, analyze the final output and report to the user or proceed with the overall plan.-"""+# **Related User Request Context:**+# {user_message_text}- final_text_for_agent = raw_tool_response + contextual_block+# **Next Steps Reminder for {self.name}:**+# If this action is part of an ongoing sequence, consider the next step with this tool or another appropriate tool. If the sequence is complete or this was a one-off action, analyze the final output and report to the user or proceed with the overall plan.+# """++# final_text_for_agent = raw_tool_response + contextual_block++ final_text_for_agent = raw_tool_responseself.agent.hist_add_tool_result(self.name, final_text_for_agent)(@@ -211,8 +215,8 @@ class MCPServerRemote(BaseModel):description: Optional[str] = Field(default="Remote SSE Server")url: str = Field(default_factory=str)headers: dict[str, Any] | None = Field(default_factory=dict[str, Any])- timeout: float = Field(default=5.0)- sse_read_timeout: float = Field(default=60.0 * 5.0)+ init_timeout: int = Field(default=0)+ tool_timeout: int = Field(default=0)disabled: bool = Field(default=False)__lock: ClassVar[threading.Lock] = PrivateAttr(default=threading.Lock())@@ -257,8 +261,8 @@ class MCPServerRemote(BaseModel):"description","url","headers",- "timeout",- "sse_read_timeout",+ "init_timeout",+ "tool_timeout","disabled",]:if key == "name":@@ -282,6 +286,8 @@ class MCPServerLocal(BaseModel):encoding_error_handler: Literal["strict", "ignore", "replace"] = Field(default="strict")+ init_timeout: int = Field(default=0)+ tool_timeout: int = Field(default=0)disabled: bool = Field(default=False)__lock: ClassVar[threading.Lock] = PrivateAttr(default=threading.Lock())@@ -329,6 +335,8 @@ class MCPServerLocal(BaseModel):"env","encoding","encoding_error_handler",+ "init_timeout",+ "tool_timeout","disabled",]:if key == "name":@@ -695,9 +703,9 @@ class MCPConfig(BaseModel):f"#### Usage:\n"f"~~~json\n"f"{{\n"- f' "observations": ["..."],\n'+ # f' "observations": ["..."],\n' # TODO: this should be a prompt file with placeholdersf' "thoughts": ["..."],\n'- f' "reflection": ["..."],\n'+ # f' "reflection": ["..."],\n' # TODO: this should be a prompt file with placeholdersf" \"tool_name\": \"{server_name}.{tool['name']}\",\n"f' "tool_args": {{\n'f"{tool_args}"@@ -848,7 +856,7 @@ class MCPClientBase(ABC):try:set = settings.get_settings()- await self._execute_with_session(list_tools_op, read_timeout_seconds=set["mcp_client_init_timeout"])+ await self._execute_with_session(list_tools_op, read_timeout_seconds=self.server.init_timeout or set["mcp_client_init_timeout"])except Exception as e:# e = eg.exceptions[0]error_text = errors.format_error(e, 0, 0)@@ -989,12 +997,13 @@ class MCPClientRemote(MCPClientBase):]:"""Connect to an MCP server, init client and save stdio/write streams"""server: MCPServerRemote = cast(MCPServerRemote, self.server)+ set = settings.get_settings()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,+ timeout=server.init_timeout or set["mcp_client_init_timeout"],+ sse_read_timeout=server.tool_timeout or set["mcp_client_tool_timeout"],))return stdio_transportdiff --git a/python/helpers/settings.py b/python/helpers/settings.pyindex 62ae8671f..9ddcfb603 100644--- a/python/helpers/settings.py+++ b/python/helpers/settings.py@@ -751,7 +751,7 @@ def convert_out(settings: Settings) -> SettingsOutput:mcp_server_section: SettingsSection = {"id": "mcp_server","title": "A0 MCP Server",- "description": "Agent Zero can be exposed as an SSE MCP server. It can then be accessed by MCP clients on the URL and port of the web UI + /mcp/sse, for example http://localhost:5000/mcp/sse. The same applies to public URL using Cloudflare Tunnel.",+ "description": "Agent Zero can be exposed as an SSE MCP server. See <a href=\"javascript:openModal('settings/mcp/server/example.html')\">connection example</a>.","fields": mcp_server_fields,"tab": "mcp",}@@ -811,18 +811,19 @@ def get_settings() -> Settings:return norm-def set_settings(settings: Settings):+def set_settings(settings: Settings, apply: bool = True):global _settingsprevious = _settings_settings = normalize_settings(settings)_write_settings_file(_settings)- _apply_settings(previous)+ if apply:+ _apply_settings(previous)-def set_settings_delta(delta: dict):+def set_settings_delta(delta: dict, apply: bool = True):current = get_settings()new = {**current, **delta}- set_settings(new) # type: ignore+ set_settings(new, apply) # type: ignoredef normalize_settings(settings: Settings) -> Settings:@@ -957,12 +958,13 @@ def _apply_settings(previous: Settings | None):agent = agent.get_data(agent.DATA_NAME_SUBORDINATE)# reload whisper model if necessary- task = defer.DeferredTask().start_task(- whisper.preload, _settings["stt_model_size"]- ) # TODO overkill, replace with background task+ if not previous or _settings["stt_model_size"] != previous["stt_model_size"]:+ task = defer.DeferredTask().start_task(+ whisper.preload, _settings["stt_model_size"]+ ) # TODO overkill, replace with background task# force memory reload on embedding model change- if previous and (+ if not previous or (_settings["embed_model_name"] != previous["embed_model_name"]or _settings["embed_model_provider"] != previous["embed_model_provider"]or _settings["embed_model_kwargs"] != previous["embed_model_kwargs"]@@ -972,55 +974,56 @@ def _apply_settings(previous: Settings | None):memory_reload()# update mcp settings if necessary- from python.helpers.mcp_handler import MCPConfig-- async def update_mcp_settings(mcp_servers: str):- PrintStyle(- background_color="black", font_color="white", padding=True- ).print("Updating MCP config...")- first_context = AgentContext.first()- if first_context:- first_context.log.log(- type="info", content="Updating MCP settings...", temp=True- )+ if not previous or _settings["mcp_servers"] != previous["mcp_servers"]:+ from python.helpers.mcp_handler import MCPConfig- mcp_config = MCPConfig.get_instance()- try:- MCPConfig.update(mcp_servers)- except Exception as e:+ async def update_mcp_settings(mcp_servers: str):+ PrintStyle(+ background_color="black", font_color="white", padding=True+ ).print("Updating MCP config...")+ first_context = AgentContext.first()if first_context:first_context.log.log(- type="warning",- content=f"Failed to update MCP settings: {e}",- temp=False,+ type="info", content="Updating MCP settings...", temp=True+ )++ mcp_config = MCPConfig.get_instance()+ try:+ MCPConfig.update(mcp_servers)+ except Exception as e:+ 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")+ )+ (+ PrintStyle(+ background_color="black", font_color="red", padding=True+ ).print(f"{e}"))- (- PrintStyle(- background_color="red", font_color="black", padding=True- ).print("Failed to update MCP settings")- )- (- PrintStyle(- background_color="black", font_color="red", padding=True- ).print(f"{e}")- )- PrintStyle(- background_color="#6734C3", font_color="white", padding=True- ).print("Parsed MCP config:")- (PrintStyle(- background_color="#334455", font_color="white", padding=False- ).print(mcp_config.model_dump_json())- )- if first_context:- first_context.log.log(- type="info", content="Finished updating MCP settings :)", temp=True+ background_color="#6734C3", font_color="white", padding=True+ ).print("Parsed MCP config:")+ (+ PrintStyle(+ background_color="#334455", font_color="white", padding=False+ ).print(mcp_config.model_dump_json()))+ 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- ) # TODO overkill, replace with background task+ task2 = defer.DeferredTask().start_task(+ update_mcp_settings, config.mcp_servers+ ) # TODO overkill, replace with background taskdef _env_to_dict(data: str):diff --git a/webui/components/settings/mcp/client/example.html b/webui/components/settings/mcp/client/example.htmlnew file mode 100644index 000000000..06d5d430b--- /dev/null+++ b/webui/components/settings/mcp/client/example.html@@ -0,0 +1,80 @@+<html>++<head>+ <title>Configuring MCP Servers</title>++</head>++<body>+ <div x-data>+ <p>Agent Zero uses standard JSON configuration known from other AI applications.<br>+ The configuration is a JSON object containing "mcpServers" object where each key is an individual MCP+ server.<br>+ Local servers are defined by a "command", "args", "env" variables.<br>+ Remote servers are defined by a "url", "headers".<br>+ "disabled" can be set to true to disable a server without removing config.<br>+ All servers can also define "init_timeout" and "tool_timeout" which override global settings.</p>+++ <h3>Example MCP Servers Configuration JSON</h3>+ <div id="mcp-servers-example"></div>++ <script>+ setTimeout(() => {+ const url = window.location.origin;+ const jsonExample = JSON.stringify({+ "mcpServers":+ {+ "sqlite": {+ "command": "uvx",+ "args": [+ "mcp-server-sqlite",+ "--db-path",+ "/root/db.sqlite"+ ],+ "init_timeout": 10,+ "tool_timeout": 200+ },+ "sequential-thinking": {+ "disabled": true,+ "command": "npx",+ "args": [+ "--yes",+ "--package",+ "@modelcontextprotocol/server-sequential-thinking",+ "mcp-server-sequential-thinking"+ ]+ },+ "agent-zero": {+ "type": "sse",+ "serverUrl": `${url}/mcp/sse`+ }+ }+ }, null, 2);++ const editor = ace.edit("mcp-servers-example");+ const dark = localStorage.getItem("darkMode");+ if (dark != "false") {+ editor.setTheme("ace/theme/github_dark");+ } else {+ editor.setTheme("ace/theme/tomorrow");+ }+ editor.session.setMode("ace/mode/json");+ editor.setValue(jsonExample);+ editor.clearSelection();+ editor.setReadOnly(true);+ }, 0);+ </script>+ <!-- </template> -->+ </div>++ <style>+ #mcp-servers-example {+ width: 100%;+ height: 40em;+ }+ </style>++</body>++</html>\ No newline at end of filediff --git a/webui/components/settings/mcp/client/mcp-servers-store.js b/webui/components/settings/mcp/client/mcp-servers-store.jsindex e87ae874e..11e1a4d1d 100644--- a/webui/components/settings/mcp/client/mcp-servers-store.js+++ b/webui/components/settings/mcp/client/mcp-servers-store.js@@ -83,6 +83,7 @@ const model = {const resp = await API.callJsonApi("mcp_servers_status", null);if (resp.success) {this.servers = resp.status;+ this.servers.sort((a, b) => a.name.localeCompare(b.name));}},@@ -98,7 +99,8 @@ const model = {await API.callJsonApi("mcp_servers_apply", {mcp_servers: this.getEditorValue(),});- scrollModal("mcp-servers-status");+ await sleep(5000); // just to prevent user from clicking apply multiple times+ // scrollModal("mcp-servers-status");} catch (error) {console.error("Failed to apply MCP servers:", error);alert("Failed to apply MCP servers: " + error.message);diff --git a/webui/components/settings/mcp/client/mcp-servers.html b/webui/components/settings/mcp/client/mcp-servers.htmlindex 81e67b5d6..1c6fbc36c 100644--- a/webui/components/settings/mcp/client/mcp-servers.html+++ b/webui/components/settings/mcp/client/mcp-servers.html@@ -14,6 +14,7 @@<div x-init="$store.mcpServersStore.initialize()" x-destroy="$store.mcpServersStore.onClose()"><h3>MCP Servers Configuration JSON+ <button class="btn slim" style="margin-left: 0.5em;" onclick="openModal('settings/mcp/client/example.html')">Examples</button><button class="btn slim" style="margin-left: 0.5em;"@click="$store.mcpServersStore.formatJson()">Reformat</button><button class="btn slim primary" :disabled="$store.mcpServersStore.loading"diff --git a/webui/components/settings/mcp/server/example.html b/webui/components/settings/mcp/server/example.htmlnew file mode 100644index 000000000..32d701084--- /dev/null+++ b/webui/components/settings/mcp/server/example.html@@ -0,0 +1,54 @@+<html>++<head>+ <title>Connection to A0 MCP Server</title>++</head>++<body>+ <div x-data>+ <p>Agent Zero MCP Server is an SSE MCP running on the same URL and port as the Web UI + /mcp/sse path.</p>+ <p>The same applies if you run A0 on a public URL using a tunnel.</p>++ <h3>Example MCP Server Configuration JSON</h3>+ <div id="mcp-server-example"></div>++ <script>+ setTimeout(() => {+ const url = window.location.origin;+ const jsonExample = JSON.stringify({+ "mcpServers":+ {+ "agent-zero": {+ "type": "sse",+ "serverUrl": `${url}/mcp/sse`+ }+ }+ }, null, 2);++ const editor = ace.edit("mcp-server-example");+ const dark = localStorage.getItem("darkMode");+ if (dark != "false") {+ editor.setTheme("ace/theme/github_dark");+ } else {+ editor.setTheme("ace/theme/tomorrow");+ }+ editor.session.setMode("ace/mode/json");+ editor.setValue(jsonExample);+ editor.clearSelection();+ editor.setReadOnly(true);+ }, 0);+ </script>+ <!-- </template> -->+ </div>++ <style>+ #mcp-server-example {+ width: 100%;+ height: 15em;+ }+ </style>++</body>++</html>\ No newline at end of file