Agent Zero AI framework
Optimize scoped tool policy resolution
Alessandro1432bde85e23
diff --git a/extensions/python/system_prompt/_11_tools_prompt.py b/extensions/python/system_prompt/_11_tools_prompt.pyindex bb6de55e6..5501e22dd 100644--- a/extensions/python/system_prompt/_11_tools_prompt.py+++ b/extensions/python/system_prompt/_11_tools_prompt.py@@ -35,18 +35,21 @@ async def build_prompt(agent: Agent) -> str:# per-file kwargs registered by plugin config extensions (e.g. _09_text_editor_config)all_tool_kwargs: dict[str, dict[str, Any]] = agent.get_data(TOOL_KWARGS_KEY) or {}- tools: list[str] = []+ tool_prompts: list[tuple[str, str]] = []for tool_file in tool_files:try:basename = os.path.basename(tool_file)extra = all_tool_kwargs.get(basename, {})tool = agent.read_prompt(basename, **extra)- tool = tool_policy.filter_tool_prompt(agent, basename, tool)- if tool:- tools.append(tool)+ tool_prompts.append((basename, tool))except Exception as e:PrintStyle().error(f"Error loading tool '{tool_file}': {e}")+ tools = [+ tool+ for tool in tool_policy.filter_tool_prompts(agent, tool_prompts)+ if tool+ ]tools_str = "\n\n".join(tools)prompt = agent.read_prompt("agent.system.tools.md", tools=tools_str)diff --git a/helpers/responses_tools.py b/helpers/responses_tools.pyindex ffe570773..17ebb48b5 100644--- a/helpers/responses_tools.py+++ b/helpers/responses_tools.py@@ -33,9 +33,10 @@ def build_responses_function_tools(agent: Any) -> tuple[list[dict[str, Any]], ditools: list[dict[str, Any]] = []name_map: dict[str, str] = {}+ policy = tool_policy.get_policy(agent)for tool_name, prompt in _local_tool_prompts(agent):- if not tool_policy.resolve_tool(agent, tool_name).allowed:+ if not tool_policy.resolve_tool(agent, tool_name, _policy=policy).allowed:continuenative_name = _native_tool_name(tool_name)name_map[native_name] = tool_name@@ -59,6 +60,7 @@ def build_responses_function_tools(agent: Any) -> tuple[list[dict[str, Any]], diagent,tool_name,canonical_id=tool_policy.canonical_mcp_id(tool_name),+ _policy=policy,).allowed:continuenative_name = _native_tool_name(tool_name)diff --git a/helpers/responses_tools.py.dox.md b/helpers/responses_tools.py.dox.mdindex 3a7edc4aa..c1a96e654 100644--- a/helpers/responses_tools.py.dox.md+++ b/helpers/responses_tools.py.dox.md@@ -27,6 +27,8 @@- Apply `helpers.tool_policy` before emitting local or MCP schemas; a blockedcapability is absent from provider-native tool definitions. Vision routingis controlled by the effective model preset rather than Agent Editor.+- Resolve a fresh policy once per schema build and reuse it only within that+ build; runtime execution remains independently policy-gated.- Connector remote tools are advertised only when `_a0_connector` runtime metadata says the matching connected CLI capability is currently available.## Work Guidancediff --git a/helpers/tool_policy.py b/helpers/tool_policy.pyindex 3e14b78be..57c891fe3 100644--- a/helpers/tool_policy.py+++ b/helpers/tool_policy.py@@ -163,6 +163,7 @@ def resolve_tool(tool_name: str,*,canonical_id: str = "",+ _policy: dict[str, Any] | None = None,) -> ToolPolicyDecision:tool_id = canonical_id or _canonical_tool_id(agent, tool_name)requested = str(tool_name or "").strip()@@ -171,7 +172,7 @@ def resolve_tool(source = "framework-required" if name == "response" else "runtime-config"return ToolPolicyDecision(True, tool_id, source, "invariant")- policy = get_policy(agent)+ policy = _policy if _policy is not None else get_policy(agent)if policy["mode"] != "custom":return ToolPolicyDecision(True, tool_id, "inherited", "inherit")@@ -209,19 +210,44 @@ def ensure_tool_allowed(def filter_tool_prompt(agent: Any, prompt_file: str, prompt: str) -> str:- if get_policy(agent)["mode"] != "custom":- return prompt+ return filter_tool_prompts(agent, [(prompt_file, prompt)])[0]- known_names = _policy_tool_names(agent)- names = _prompt_tool_names(prompt_file, prompt, known_names)- if names and not any(resolve_tool(agent, name).allowed for name in names):- return ""- blocked_names = {+def filter_tool_prompts(+ agent: Any, prompts: list[tuple[str, str]]+) -> list[str]:+ policy = get_policy(agent)+ if policy["mode"] != "custom":+ return [prompt for _prompt_file, prompt in prompts]++ known_names = _policy_tool_names(agent, policy)+ prompt_names = {+ name+ for prompt_file, prompt in prompts+ for name in _prompt_tool_names(prompt_file, prompt, known_names)+ }+ allowed_names = {name- for name in known_names- if not resolve_tool(agent, name).allowed+ for name in known_names | prompt_names+ if resolve_tool(agent, name, _policy=policy).allowed}+ return [+ _filter_tool_prompt(prompt_file, prompt, known_names, allowed_names)+ for prompt_file, prompt in prompts+ ]+++def _filter_tool_prompt(+ prompt_file: str,+ prompt: str,+ known_names: set[str],+ allowed_names: set[str],+) -> str:+ names = _prompt_tool_names(prompt_file, prompt, known_names)+ if names and not any(name in allowed_names for name in names):+ return ""++ blocked_names = known_names - allowed_namesif not blocked_names:return promptpatterns = [@@ -261,9 +287,8 @@ def _local_tool_paths(agent: Any) -> dict[str, str]:return result-def _policy_tool_names(agent: Any) -> set[str]:+def _policy_tool_names(agent: Any, policy: dict[str, Any]) -> set[str]:names = set(_local_tool_paths(agent))- policy = get_policy(agent)names.update(_tool_name_from_id(tool_id)for tool_id in [*policy["allowed"], *policy["blocked"]]diff --git a/helpers/tool_policy.py.dox.md b/helpers/tool_policy.py.dox.mdindex 2fe6094eb..44a323c54 100644--- a/helpers/tool_policy.py.dox.md+++ b/helpers/tool_policy.py.dox.md@@ -24,6 +24,8 @@- `filter_tool_prompt` removes denied local capabilities from the text protocol,including complete fenced JSON examples that reference them, without takingownership of provider-native naming rules.+- `filter_tool_prompts` applies one fresh policy snapshot and one set of tool+ decisions to a complete prompt batch; it does not retain policy across calls.## Runtime Contracts@@ -55,6 +57,8 @@canonical IDs retain the exact transport-qualified spelling.- Unknown policy IDs remain in the catalog as unavailable entries.- Resolution performs no model calls and logs no secrets.+- Prompt and native-schema batches reuse their freshly loaded policy while+ runtime execution gates continue to resolve current policy independently.## Verificationdiff --git a/tests/test_tool_policy.py b/tests/test_tool_policy.pyindex 6dbf9da0e..4e2527caf 100644--- a/tests/test_tool_policy.py+++ b/tests/test_tool_policy.py@@ -116,6 +116,29 @@ async def test_text_tool_prompt_omits_blocked_tool_and_description(assert "Blocked description" not in prompt+async def test_policy_is_loaded_once_per_tool_surface(+ monkeypatch, local_prompt_agent: _Agent+) -> None:+ reads = 0++ def get_policy(_agent):+ nonlocal reads+ reads += 1+ return _custom_policy(default="allow", blocked=["local:blocked"])++ monkeypatch.setattr(tool_policy, "get_policy", get_policy)++ await _11_tools_prompt.build_prompt(local_prompt_agent)+ assert reads == 1++ await _11_tools_prompt.build_prompt(local_prompt_agent)+ assert reads == 2++ responses_tools.build_responses_function_tools(local_prompt_agent)+ assert reads == 3++def test_provider_native_schemas_omit_blocked_local_tool(monkeypatch, local_prompt_agent: _Agent) -> None:@@ -132,6 +155,65 @@ def test_provider_native_schemas_omit_blocked_local_tool(assert [tool["name"] for tool in tools] == ["allowed"]+async def test_profile_policy_isolated_across_prompt_schema_and_execution(+ monkeypatch, local_prompt_agent: _Agent+) -> None:+ restricted = _Agent(local_prompt_agent.prompt_root, profile="restricted")++ monkeypatch.setattr(+ tool_policy,+ "get_policy",+ lambda agent: _custom_policy(+ default="allow",+ blocked=(+ ["local:allowed"]+ if agent.config.profile == "restricted"+ else []+ ),+ ),+ )++ allowed_prompt = await _11_tools_prompt.build_prompt(local_prompt_agent)+ restricted_prompt = await _11_tools_prompt.build_prompt(restricted)+ allowed_tools, _ = responses_tools.build_responses_function_tools(+ local_prompt_agent+ )+ restricted_tools, _ = responses_tools.build_responses_function_tools(restricted)++ assert "Allowed description" in allowed_prompt+ assert "Allowed description" not in restricted_prompt+ assert "allowed" in {tool["name"] for tool in allowed_tools}+ assert "allowed" not in {tool["name"] for tool in restricted_tools}+ await EnforceToolPolicy(local_prompt_agent).execute(tool_name="allowed")+ with pytest.raises(+ RepairableException,+ match='Tool "allowed" is blocked for agent profile "restricted"',+ ):+ await EnforceToolPolicy(restricted).execute(tool_name="allowed")+++async def test_execution_rechecks_policy_after_tool_was_advertised(+ monkeypatch, local_prompt_agent: _Agent+) -> None:+ disabled = False++ def get_policy(_agent):+ return _custom_policy(default="block" if disabled else "allow")++ monkeypatch.setattr(tool_policy, "get_policy", get_policy)++ prompt = await _11_tools_prompt.build_prompt(local_prompt_agent)+ tools, _ = responses_tools.build_responses_function_tools(local_prompt_agent)+ assert "Allowed description" in prompt+ assert "allowed" in {tool["name"] for tool in tools}++ disabled = True+ with pytest.raises(RepairableException, match='Tool "allowed" is blocked'):+ await EnforceToolPolicy(local_prompt_agent).execute(tool_name="allowed")++def test_inherited_prompt_filter_skips_tool_inventory(monkeypatch, tmp_path: Path):agent = _Agent(tmp_path)prompt = "### shell\nRun a command."@@ -377,7 +459,7 @@ def test_prompt_filter_removes_complete_blocked_json_example(monkeypatch.setattr(tool_policy,"_policy_tool_names",- lambda agent: {"memory_load", "memory_save"},+ lambda agent, policy: {"memory_load", "memory_save"},)monkeypatch.setattr(tool_policy.subagents, "get_paths", lambda *args, **kwargs: [])monkeypatch.setattr(@@ -644,12 +726,18 @@ def test_mcp_prompt_and_native_schema_omit_blocked_tool(config = mcp_handler.MCPConfig(servers_list=[])config.servers = [Server()]- agent = _Agent(tmp_path)+ allowed_agent = _Agent(tmp_path, profile="agent0")+ restricted_agent = _Agent(tmp_path, profile="researcher")monkeypatch.setattr(tool_policy,"get_policy",lambda agent: _custom_policy(- default="allow", blocked=["mcp:docs:write"]+ default="allow",+ blocked=(+ ["mcp:docs:write"]+ if agent.config.profile == "researcher"+ else []+ ),),)monkeypatch.setattr(@@ -663,13 +751,18 @@ def test_mcp_prompt_and_native_schema_omit_blocked_tool(monkeypatch.setattr(tool_policy.subagents, "get_paths", lambda *args: [])monkeypatch.setattr(responses_tools, "_vision_tool_prompt", lambda agent: "")- prompt = config.get_tools_prompt(agent=agent)- schemas, name_map = responses_tools.build_responses_function_tools(agent)+ 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)+ restricted_schemas, name_map = responses_tools.build_responses_function_tools(+ restricted_agent+ )- assert "docs.read" in prompt- assert "docs.write" not in prompt- assert len(schemas) == 1- assert name_map[schemas[0]["name"]] == "docs.read"+ assert "docs.write" in allowed_prompt+ assert "docs.write" not in restricted_prompt+ assert len(allowed_schemas) == 2+ assert len(restricted_schemas) == 1+ assert name_map[restricted_schemas[0]["name"]] == "docs.read"@pytest.mark.asyncio