Skip to content

Agent Zero AI framework

Preserve policy-filtered guidance in native tool descriptions

Alessandroecb96172b44d
diff --git a/helpers/responses_tools.py b/helpers/responses_tools.py
index 316db6533..c94cf5dc8 100644
--- a/helpers/responses_tools.py
+++ b/helpers/responses_tools.py
@@ -7,7 +7,7 @@ import re
from copy import deepcopy
from typing import Any
-from helpers import files, subagents, tool_policy
+from helpers import extract_tools, files, subagents, tool_policy
FUNCTION_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
@@ -25,8 +25,12 @@ SIMPLE_ARGS_PATTERN = re.compile(
)
TOOL_PROMPT_PREFIX = "agent.system.tool."
TOOL_PROMPT_SUFFIX = ".md"
-MAX_TOOL_DESCRIPTION_CHARS = 1024
TOOL_PROMPT_KWARGS_KEY = "_tool_prompt_kwargs"
+FENCED_EXAMPLE_PATTERN = re.compile(
+ r"^[ \t]*(?P<fence>`{3,}|~{3,})(?P<language>[^\r\n]*)\r?\n"
+ r"(?P<body>.*?)^[ \t]*(?P=fence)[ \t]*(?:\r?\n|$)",
+ re.IGNORECASE | re.MULTILINE | re.DOTALL,
+)
# Canonical arguments for the resolved bundled implementations, not tool-name aliases.
BUNDLED_TOOL_PARAMETERS: dict[str, dict[str, Any]] = {
@@ -112,7 +116,13 @@ def build_responses_function_tools(agent: Any) -> tuple[list[dict[str, Any]], di
name_map: dict[str, str] = {}
policy = tool_policy.get_policy(agent)
- for tool_name, prompt in _local_tool_prompts(agent):
+ local_prompts = _local_tool_prompts(agent)
+ descriptions = tool_policy.filter_tool_prompts(
+ agent,
+ [(f"{TOOL_PROMPT_PREFIX}{name}{TOOL_PROMPT_SUFFIX}", prompt) for name, prompt in local_prompts],
+ _policy=policy,
+ )
+ for (tool_name, prompt), description in zip(local_prompts, descriptions):
if not tool_policy.resolve_tool(agent, tool_name, _policy=policy).allowed:
continue
native_name = _native_tool_name(tool_name)
@@ -122,13 +132,7 @@ def build_responses_function_tools(agent: Any) -> tuple[list[dict[str, Any]], di
"type": "function",
"name": native_name,
"strict": False,
- "description": _truncate(
- tool_policy.tool_prompt_description(
- prompt,
- tool_name,
- fallback=tool_name,
- )
- ),
+ "description": _native_tool_description(description, tool_name),
"parameters": _schema_for_tool(agent, tool_name, prompt),
}
)
@@ -148,7 +152,7 @@ def build_responses_function_tools(agent: Any) -> tuple[list[dict[str, Any]], di
"type": "function",
"name": native_name,
"strict": False,
- "description": _truncate(str(tool.get("description") or tool_name)),
+ "description": str(tool.get("description") or tool_name),
"parameters": _schema_from_any(tool.get("input_schema")),
}
)
@@ -393,7 +397,28 @@ def _dedupe_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
return result
-def _truncate(text: str) -> str:
- if len(text) <= MAX_TOOL_DESCRIPTION_CHARS:
+def _native_tool_description(prompt: str, tool_name: str) -> str:
+ def arguments_examples(text: str) -> str:
+ for root in extract_tools.extract_json_root_strings(text):
+ request = extract_tools.extract_tool_request(root)
+ if request is None:
+ continue
+ name = request.get("tool_name") or request.get("tool")
+ args = request.get("tool_args", request.get("args"))
+ if not isinstance(name, str) or not isinstance(args, dict):
+ continue
+ label = "Arguments example" if name == tool_name else f"Call {name} with arguments"
+ example = f"{label}:\n```json\n{json.dumps(args, ensure_ascii=False)}\n```"
+ text = text.replace(root, example)
return text
- return text[: MAX_TOOL_DESCRIPTION_CHARS - 3].rstrip() + "..."
+
+ parts = []
+ end = 0
+ for match in FENCED_EXAMPLE_PATTERN.finditer(prompt):
+ parts.append(arguments_examples(prompt[end:match.start()]))
+ body = match.group("body")
+ projected = arguments_examples(body) if match.group("language").strip().lower() == "json" else body
+ parts.append(projected + "\n" if projected != body else match.group(0))
+ end = match.end()
+ parts.append(arguments_examples(prompt[end:]))
+ return "".join(parts).strip() or tool_name
diff --git a/helpers/responses_tools.py.dox.md b/helpers/responses_tools.py.dox.md
index b9b731dcc..e2f705592 100644
--- a/helpers/responses_tools.py.dox.md
+++ b/helpers/responses_tools.py.dox.md
@@ -20,9 +20,7 @@
- Emit generated definitions with `strict: false` so Responses does not normalize optional or extensible arguments into required strict fields. Provider-specific strictness (such as Codex's final response) belongs at the provider request boundary.
- Explicitly embedded JSON schemas take precedence. Otherwise use canonical argument properties only for a matching resolved bundled implementation in `BUNDLED_TOOL_PARAMETERS`; custom/profile overrides must not inherit a same-named bundled contract. Properties remain optional and extensible for action-dependent inputs and runtime aliases; runtime validation remains authoritative.
- For unlisted implementations, infer only an unambiguous single backticked argument on an otherwise empty `args:` line; otherwise retain a permissive object instead of prose-guessed types.
-- Native local-tool descriptions reuse the tool catalog's compact prompt
- description; Responses retains native-name mapping, schema derivation, and
- provider description limits.
+- Native local descriptions preserve full policy-filtered operational guidance. Convert unfenced and JSON-fenced A0 envelope examples to argument-only examples using the shared tool-request parser; preserve unrelated JSON and non-JSON code fences. Catalog summaries remain separate.
- Preserve original Agent Zero tool names through the native Responses name map.
- Keep MCP tool schemas merged after local prompt-derived tools.
- Apply `helpers.tool_policy` before emitting local or MCP schemas; a blocked
@@ -34,7 +32,7 @@
## Work Guidance
-- Keep prompt-derived descriptions bounded by `MAX_TOOL_DESCRIPTION_CHARS`.
+- Do not silently truncate local or MCP instructions; prompt owners control their guidance budget.
- Treat plugin-specific tool gates as optional imports so core helper loading does not require a plugin that is absent or disabled.
## Verification
diff --git a/helpers/tool_policy.py b/helpers/tool_policy.py
index 57c891fe3..51791ad32 100644
--- a/helpers/tool_policy.py
+++ b/helpers/tool_policy.py
@@ -214,9 +214,10 @@ def filter_tool_prompt(agent: Any, prompt_file: str, prompt: str) -> str:
def filter_tool_prompts(
- agent: Any, prompts: list[tuple[str, str]]
+ agent: Any, prompts: list[tuple[str, str]],
+ *, _policy: dict[str, Any] | None = None,
) -> list[str]:
- policy = get_policy(agent)
+ policy = _policy if _policy is not None else get_policy(agent)
if policy["mode"] != "custom":
return [prompt for _prompt_file, prompt in prompts]
diff --git a/helpers/tool_policy.py.dox.md b/helpers/tool_policy.py.dox.md
index 44a323c54..baa811e87 100644
--- a/helpers/tool_policy.py.dox.md
+++ b/helpers/tool_policy.py.dox.md
@@ -15,17 +15,14 @@
prompt/schema extensions remain responsible for live remote-tool exposure.
The editor applies the current draft policy instead of receiving duplicated
allowed/required flags from the backend.
-- `tool_prompt_description` owns the shared compact description extracted for
- the editor catalog and provider-native schemas; transport-specific names and
- schemas remain with their transports.
+- `tool_prompt_description` owns compact editor catalog summaries; Responses owns full native tool descriptions and schema projection.
- `resolve_tool` returns the effective decision and provenance.
- `ensure_tool_allowed` raises the stable repairable runtime policy error and
accepts an explicit canonical ID from transports that already resolved one.
- `filter_tool_prompt` removes denied local capabilities from the text protocol,
including complete fenced JSON examples that reference them, without taking
ownership 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.
+- `filter_tool_prompts` applies one fresh policy snapshot and one set of tool decisions to a complete prompt batch. Native schema construction may supply its current `_policy` snapshot; neither owner retains it across calls.
## Runtime Contracts
diff --git a/tests/test_responses_tools.py b/tests/test_responses_tools.py
index ffba38885..30d9082b2 100644
--- a/tests/test_responses_tools.py
+++ b/tests/test_responses_tools.py
@@ -264,7 +264,8 @@ def test_responses_function_tools_include_vision_prompt(monkeypatch, tmp_path):
tools, name_map = responses_tools.build_responses_function_tools(agent)
assert [tool["name"] for tool in tools] == ["vision_load"]
- assert tools[0]["description"] == "load images into the model for visual reasoning"
+ assert "load images into the model for visual reasoning" in tools[0]["description"]
+ assert "args: `paths` list of absolute image paths" in tools[0]["description"]
assert tools[0]["parameters"]["properties"] == {}
assert name_map == {"vision_load": "vision_load"}
@@ -330,3 +331,28 @@ def test_bundled_memory_prompt_exposes_every_memory_tool():
"memory_delete",
"memory_forget",
]
+
+
+def test_native_description_preserves_guidance_and_projects_only_tool_examples():
+ prompt = '''### example
+Keep every operational rule.
+~~~json
+{"thoughts":["think"],"headline":"execute","tool_name":"example","tool_args":{"text":"héllo","nested":{"value":true}},}
+~~~
+{"tool_name":"other","tool_args":{"query":"lookup"}}
+```python
+payload = {"tool_name":"example","tool_args":{"text":"literal code"}}
+```
+```json
+{"ordinary":"data"}
+```
+'''
+ description = responses_tools._native_tool_description(prompt, 'example')
+ assert 'Keep every operational rule.' in description
+ assert 'Arguments example:\n```json\n{"text": "héllo", "nested": {"value": true}}' in description
+ assert 'Call other with arguments:' in description
+ assert '"thoughts"' not in description and '"headline"' not in description
+ assert 'payload = {"tool_name":"example","tool_args":{"text":"literal code"}}' in description
+ assert '```json\n{"ordinary":"data"}\n```' in description
+ assert responses_tools._native_tool_description('rule\n' * 300, 'example').endswith('rule')
+ assert len(responses_tools._native_tool_description('rule\n' * 300, 'example')) > 1024
diff --git a/tests/test_tool_policy.py b/tests/test_tool_policy.py
index b0ce73b01..8deb4e29c 100644
--- a/tests/test_tool_policy.py
+++ b/tests/test_tool_policy.py
@@ -154,6 +154,11 @@ def test_provider_native_schemas_omit_blocked_local_tool(
)
assert [tool["name"] for tool in tools] == ["allowed"]
+ description = tools[0]["description"]
+ assert "Keyboard input remains documented." in description
+ assert "blocked" not in description.lower()
+ assert "Arguments example:" in description
+ assert '"tool_name"' not in description
@pytest.mark.asyncio
@@ -660,7 +665,8 @@ async def test_active_vision_model_uses_canonical_vision_prompt(
assert prompt.count("canonical vision") == 1
assert schemas[0]["name"] == "vision_load"
- assert schemas[0]["description"] == "canonical vision"
+ assert "canonical vision" in schemas[0]["description"]
+ assert "args: `paths`, `query`" in schemas[0]["description"]
def test_vision_prompt_stays_route_agnostic_and_batches_paths() -> None: