Skip to content

Agent Zero AI framework

Move MCP guidance into prompt templates

Alessandro87e39b300a51
diff --git a/helpers/mcp_handler.py b/helpers/mcp_handler.py
index 64565ed1e..b95ffb282 100644
--- a/helpers/mcp_handler.py
+++ b/helpers/mcp_handler.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+from pathlib import Path
import re
from typing import (
List,
@@ -41,7 +42,7 @@ from anyio.streams.memory import (
)
from pydantic import BaseModel, Field, Discriminator, Tag, PrivateAttr
-from helpers import dirty_json, media_artifacts
+from helpers import dirty_json, files, media_artifacts
from helpers.print_style import PrintStyle
from helpers.tool import Tool, Response
from helpers.defer import DeferredTask
@@ -1156,7 +1157,15 @@ class MCPConfig(BaseModel):
with self.__lock:
pass
- prompt = '## "Remote (MCP Server) Agent Tools" available:\n\n'
+ def render(file: str, **kwargs: Any) -> str:
+ if agent is not None:
+ return agent.read_prompt(file, **kwargs).strip()
+ return files.read_prompt_file(
+ file,
+ _directories=[str(Path(__file__).resolve().parents[1] / "prompts")],
+ **kwargs,
+ ).strip()
+
server_names = []
for server in self.servers:
if not server_name or server.name == server_name:
@@ -1165,53 +1174,56 @@ class MCPConfig(BaseModel):
if server_name and server_name not in server_names:
raise ValueError(f"Server {server_name} not found")
+ policy = None
+ if agent is not None:
+ from helpers import tool_policy
+
+ server_prompts: list[str] = []
for server in self.servers:
if server.name in server_names:
- server_name = server.name
- prompt += f"### {server_name}\n"
- prompt += f"{server.description}\n"
- tools = server.get_tools()
+ selected_server_name = server.name
+ tool_prompts: list[str] = []
- for tool in tools:
- qualified_name = f"{server_name}.{tool['name']}"
+ for tool in server.get_tools():
+ qualified_name = f"{selected_server_name}.{tool['name']}"
if agent is not None:
- from helpers.tool_policy import canonical_mcp_id, resolve_tool
-
- if not resolve_tool(
+ if policy is None:
+ policy = tool_policy.get_policy(agent)
+ if not tool_policy.resolve_tool(
agent,
qualified_name,
- canonical_id=canonical_mcp_id(qualified_name),
+ canonical_id=tool_policy.canonical_mcp_id(qualified_name),
+ _policy=policy,
).allowed:
continue
- prompt += (
- f"\n### {qualified_name}:\n"
- f"{tool['description']}\n\n"
- # f"#### Categories:\n"
- # f"* kind: MCP Server Tool\n"
- # f'* server: "{server_name}" ({server.description})\n\n'
- # f"#### Arguments:\n"
- )
-
input_schema = (
json.dumps(tool["input_schema"]) if tool["input_schema"] else ""
)
+ tool_prompts.append(
+ render(
+ "agent.system.mcp_tool.md",
+ qualified_name=qualified_name,
+ description=tool["description"],
+ input_schema=input_schema,
+ )
+ )
- prompt += f"#### Input schema for tool_args:\n{input_schema}\n"
-
- prompt += "\n"
-
- prompt += (
- f"#### Usage:\n"
- f"{{\n"
- # f' "observations": ["..."],\n' # TODO: this should be a prompt file with placeholders
- f' "thoughts": ["..."],\n'
- # f' "reflection": ["..."],\n' # TODO: this should be a prompt file with placeholders
- f" \"tool_name\": \"{qualified_name}\",\n"
- f' "tool_args": !follow schema above\n'
- f"}}\n"
+ if tool_prompts:
+ server_prompts.append(
+ render(
+ "agent.system.mcp_server.md",
+ server_name=selected_server_name,
+ server_description=server.description,
+ tools="\n\n".join(tool_prompts),
+ )
)
- return prompt
+ if not server_prompts:
+ return ""
+ return render(
+ "agent.system.mcp_tools.md",
+ tools="\n".join(server_prompts),
+ ) + "\n"
def has_tool(self, tool_name: str) -> bool:
"""Check if a tool is available"""
diff --git a/helpers/mcp_handler.py.dox.md b/helpers/mcp_handler.py.dox.md
index d5240fb25..5a48041bc 100644
--- a/helpers/mcp_handler.py.dox.md
+++ b/helpers/mcp_handler.py.dox.md
@@ -84,7 +84,16 @@
- MCP tool names are qualified as `server_name.tool_name`; server names are normalized without dots, and the tool portion may contain dots.
- Agent-facing MCP prompt descriptions filter through the central profile tool
policy, and `MCPTool.execute()` rechecks the same policy with the explicit MCP
- canonical ID before invocation.
+ canonical ID before invocation. Prompt construction uses one fresh policy
+ snapshot and omits server sections when none of their tools are allowed.
+ Server headings are explicitly non-callable groups; each tool heading exposes
+ the exact qualified name that Chat Completions must call. Prompt guidance
+ treats each allowed-operation description as exhaustive and rejects inferring
+ capabilities from names or schemas when no operation matches. Static MCP
+ framing is rendered from `prompts/agent.system.mcp_tools.md`,
+ `prompts/agent.system.mcp_server.md`, and
+ `prompts/agent.system.mcp_tool.md`; this helper supplies the policy-filtered
+ server names, exact qualified tool names, descriptions, and schemas.
- `MCPConfig.get_tool()` tries the supplied qualified name first, then restores an advertised Responses alias from the calling agent's name map; names that still do not identify an MCP tool return `None` unchanged for downstream local-tool resolution.
- Servers may define `disabled_tools` as a list of MCP tool names. Disabled tools are omitted from agent-facing prompts, status counts, `has_tool`, and calls, while detail views can still retrieve them through `get_all_tools()` with a `disabled` flag so users can re-enable them.
- Server-specific `init_timeout` and `tool_timeout` override global MCP client timeout settings for list-tools and call-tool operations.
diff --git a/prompts/AGENTS.md b/prompts/AGENTS.md
index 10917ba20..ee9503940 100644
--- a/prompts/AGENTS.md
+++ b/prompts/AGENTS.md
@@ -18,6 +18,12 @@
- Keep placeholder names, include aliases, and template assumptions synchronized with prompt-loading code and extensions.
- Prompt changes can alter agent behavior; keep edits narrow and intentional.
- Maintain clear separation between core behavior prompts and profile/plugin-specific customization.
+- Keep configurable capability names and usage guidance in their
+ `agent.system.tool.*.md` prompts so tool policy removes the guidance together
+ with the capability; non-tool system fragments stay capability-neutral.
+- MCP prompt templates own the static outer, server, and tool framing;
+ `helpers/mcp_handler.py` supplies policy-filtered names, descriptions, and
+ schemas.
- Summary prompts that compress history should preserve loaded skill names from `skill_instructions` metadata without copying full skill bodies.
## Work Guidance
diff --git a/prompts/agent.system.mcp_server.md b/prompts/agent.system.mcp_server.md
new file mode 100644
index 000000000..1ef7e04df
--- /dev/null
+++ b/prompts/agent.system.mcp_server.md
@@ -0,0 +1,4 @@
+### MCP server `{{server_name}}` (group only; not a tool)
+Context only: {{server_description}}
+
+{{tools}}
diff --git a/prompts/agent.system.mcp_tool.md b/prompts/agent.system.mcp_tool.md
new file mode 100644
index 000000000..4f41c7fdf
--- /dev/null
+++ b/prompts/agent.system.mcp_tool.md
@@ -0,0 +1,12 @@
+#### MCP tool `{{qualified_name}}`
+Allowed operation (exhaustive): {{description}}
+
+##### Input schema for tool_args:
+{{input_schema}}
+
+##### Usage:
+{
+ "thoughts": ["..."],
+ "tool_name": "{{qualified_name}}",
+ "tool_args": !follow schema above
+}
diff --git a/prompts/agent.system.mcp_tools.md b/prompts/agent.system.mcp_tools.md
index 67776e5b4..24260835e 100644
--- a/prompts/agent.system.mcp_tools.md
+++ b/prompts/agent.system.mcp_tools.md
@@ -1 +1,5 @@
+## "Remote (MCP Server) Agent Tools" available:
+
+Server descriptions are context, not callable capabilities. Each "Allowed operation" line is exhaustive. Never infer capabilities from tool names or input schemas, repurpose inputs, or substitute a different operation. If no allowed operation matches, report that the capability is unavailable.
+
{{tools}}
diff --git a/tests/test_tool_policy.py b/tests/test_tool_policy.py
index 4e2527caf..b0ce73b01 100644
--- a/tests/test_tool_policy.py
+++ b/tests/test_tool_policy.py
@@ -4,6 +4,7 @@ from pathlib import Path
import subprocess
import sys
from types import SimpleNamespace
+from unittest.mock import AsyncMock
import pytest
@@ -726,8 +727,9 @@ def test_mcp_prompt_and_native_schema_omit_blocked_tool(
config = mcp_handler.MCPConfig(servers_list=[])
config.servers = [Server()]
- allowed_agent = _Agent(tmp_path, profile="agent0")
- restricted_agent = _Agent(tmp_path, profile="researcher")
+ prompt_root = Path(__file__).parents[1] / "prompts"
+ allowed_agent = _Agent(prompt_root, profile="agent0")
+ restricted_agent = _Agent(prompt_root, profile="researcher")
monkeypatch.setattr(
tool_policy,
"get_policy",
@@ -753,17 +755,86 @@ def test_mcp_prompt_and_native_schema_omit_blocked_tool(
allowed_prompt = config.get_tools_prompt(agent=allowed_agent)
restricted_prompt = config.get_tools_prompt(agent=restricted_agent)
- allowed_schemas, _ = responses_tools.build_responses_function_tools(allowed_agent)
+ allowed_schemas, allowed_name_map = responses_tools.build_responses_function_tools(
+ allowed_agent
+ )
restricted_schemas, name_map = responses_tools.build_responses_function_tools(
restricted_agent
)
assert "docs.write" in allowed_prompt
assert "docs.write" not in restricted_prompt
+ assert "### MCP server `docs` (group only; not a tool)" in allowed_prompt
+ assert "#### MCP tool `docs.read`" in allowed_prompt
+ assert "Context only: Documentation" in allowed_prompt
+ assert "Allowed operation (exhaustive): Read docs" in allowed_prompt
+ assert "Server descriptions are context, not callable capabilities" in allowed_prompt
+ assert "Never infer capabilities from tool names or input schemas" in allowed_prompt
+ assert "\n### docs\n" not in allowed_prompt
+ assert "\n### docs.read:" not in allowed_prompt
+ assert allowed_prompt.count("docs.read") == 2
+ assert allowed_prompt.count("docs.write") == 2
+ assert restricted_prompt.count("docs.read") == 2
assert len(allowed_schemas) == 2
assert len(restricted_schemas) == 1
+ assert set(allowed_name_map.values()) == {"docs.read", "docs.write"}
assert name_map[restricted_schemas[0]["name"]] == "docs.read"
+ reads = 0
+
+ def get_policy(_agent):
+ nonlocal reads
+ reads += 1
+ return _custom_policy(default="allow", mcp_default="block")
+
+ monkeypatch.setattr(tool_policy, "get_policy", get_policy)
+
+ assert config.get_tools_prompt(agent=_Agent(tmp_path)) == ""
+ assert reads == 1
+
+
+async def test_browser_context_follows_profile_tool_policy(
+ monkeypatch, tmp_path: Path
+) -> None:
+ from plugins._browser.extensions.python.system_prompt import _20_browser_context
+
+ runtime = SimpleNamespace(
+ call=AsyncMock(
+ return_value={
+ "browsers": [
+ {
+ "id": "browser-1",
+ "currentUrl": "https://example.com",
+ "title": "Example",
+ }
+ ]
+ }
+ )
+ )
+ allowed = False
+ agent = _Agent(tmp_path)
+ agent.context.id = "ctx"
+ monkeypatch.setattr(
+ tool_policy,
+ "resolve_tool",
+ lambda *_args, **_kwargs: SimpleNamespace(allowed=allowed),
+ )
+ monkeypatch.setattr(
+ _20_browser_context, "get_runtime", AsyncMock(return_value=runtime)
+ )
+
+ system_prompt: list[str] = []
+ extension = _20_browser_context.BrowserContextPrompt(agent)
+ await extension.execute(system_prompt=system_prompt)
+ assert system_prompt == []
+ runtime.call.assert_not_awaited()
+
+ allowed = True
+ await extension.execute(system_prompt=system_prompt)
+ assert "currently open web browsers" in system_prompt[0]
+ runtime.call.assert_awaited_once_with("list")
+
@pytest.mark.asyncio
async def test_local_execution_gate_returns_stable_profile_error(