Skip to content

Agent Zero AI framework

Project native system instructions only for Responses requests

Alessandro9d9d6e1a8922
diff --git a/AGENTS.md b/AGENTS.md
index 142eca2be..75c431aac 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,6 +34,7 @@
- Embedding wrappers expose batch-shaped `embed(inputs)` for provider-ready inputs; keep `embed_documents` and `embed_query` as LangChain compatibility adapters.
- Embedding requests never forward the chat-only `a0_api_mode` control to providers.
- Prompt Markdown may retain fenced JSON examples for readability; final system-prompt rendering removes only their JSON fence markers before model calls and preserves non-JSON fences.
+- System section owners populate request-only `LoopData.responses_prompt_replacements`; prompt construction resets them each time. Responses applies them to copied input, preserving original Chat/fallback messages and stored history.
- Copy live core-plugin changes back into tracked source under `plugins/`.
- Develop new custom plugins under ignored `usr/plugins/`; tracked bundled plugins live under `plugins/`.
- Use the framework runtime for backend and plugin-hook verification, not the separate agent execution runtime.
diff --git a/agent.py b/agent.py
index dfa55f665..716beabc7 100644
--- a/agent.py
+++ b/agent.py
@@ -342,6 +342,7 @@ class LoopData:
def __init__(self, **kwargs):
self.iteration = -1
self.system = []
+ self.responses_prompt_replacements: dict[str, str] = {}
self.user_message: history.Message | None = None
self.history_output: list[history.OutputMessage] = []
self.protocol_temporary: OrderedDict[str, history.MessageContent] = OrderedDict()
@@ -570,6 +571,7 @@ class Agent:
)
# set system prompt and message history
+ loop_data.responses_prompt_replacements.clear()
loop_data.system = await self.get_system_prompt(self.loop_data)
loop_data.history_output = self.history.output()
@@ -947,6 +949,7 @@ class Agent:
"background": background,
"explicit_caching": explicit_caching,
"a0_responses_function_tools": response_tools,
+ "responses_prompt_replacements": dict(self.loop_data.responses_prompt_replacements),
}
previous_state = self._responses_state_for_model(model)
@@ -975,6 +978,7 @@ class Agent:
),
}
for key in (
+ "responses_prompt_replacements",
"responses_builtin_tools",
"responses_state",
"previous_response_id",
diff --git a/extensions/python/system_prompt/AGENTS.md b/extensions/python/system_prompt/AGENTS.md
index 71225b8b4..699ae3118 100644
--- a/extensions/python/system_prompt/AGENTS.md
+++ b/extensions/python/system_prompt/AGENTS.md
@@ -12,6 +12,7 @@
## Local Contracts
- Preserve ordering where sections depend on earlier context.
+- Main, local-tool and MCP section owners register `LoopData.responses_prompt_replacements` while retaining normal text prompts. Responses applies these request-only substitutions when native A0 definitions are present; Chat and fallback keep the text protocol. MCP native framing preserves allowed-server context.
- Keep secret-related prompt sections masked and scoped.
- Prompt additions must be bounded and compatible with tool-call contracts.
- Keep non-tool sections free of configurable capability guidance; tool-owned
diff --git a/extensions/python/system_prompt/_10_main_prompt.py b/extensions/python/system_prompt/_10_main_prompt.py
index 88193540c..87deaed89 100644
--- a/extensions/python/system_prompt/_10_main_prompt.py
+++ b/extensions/python/system_prompt/_10_main_prompt.py
@@ -16,6 +16,11 @@ class MainPrompt(Extension):
return
prompt = await build_prompt(self.agent)
system_prompt.append(prompt)
+ communication = self.agent.read_prompt("agent.system.main.communication.md")
+ if communication in prompt:
+ loop_data.responses_prompt_replacements[communication] = self.agent.read_prompt(
+ "agent.system.main.communication.native.md"
+ )
@extensible
diff --git a/extensions/python/system_prompt/_11_tools_prompt.py b/extensions/python/system_prompt/_11_tools_prompt.py
index 5501e22dd..71b65cfc8 100644
--- a/extensions/python/system_prompt/_11_tools_prompt.py
+++ b/extensions/python/system_prompt/_11_tools_prompt.py
@@ -22,6 +22,7 @@ class ToolsPrompt(Extension):
return
prompt = await build_prompt(self.agent)
system_prompt.append(prompt)
+ loop_data.responses_prompt_replacements[prompt] = ""
@extensible
diff --git a/extensions/python/system_prompt/_12_mcp_prompt.py b/extensions/python/system_prompt/_12_mcp_prompt.py
index c18c11fce..876d5749b 100644
--- a/extensions/python/system_prompt/_12_mcp_prompt.py
+++ b/extensions/python/system_prompt/_12_mcp_prompt.py
@@ -18,6 +18,9 @@ class MCPToolsPrompt(Extension):
prompt = await build_prompt(self.agent)
if prompt:
system_prompt.append(prompt)
+ loop_data.responses_prompt_replacements[prompt] = (
+ MCPConfig.get_for_agent(self.agent).get_tools_prompt(agent=self.agent, native=True)
+ )
@extensible
diff --git a/helpers/litellm_transport.py b/helpers/litellm_transport.py
index 3a88f574e..7f2cd0993 100644
--- a/helpers/litellm_transport.py
+++ b/helpers/litellm_transport.py
@@ -18,6 +18,7 @@ from litellm import (
from helpers import images
from helpers.llm_result import LLMResult
+from helpers.responses_tools import project_system_prompt
ChatChunk = dict[str, str]
@@ -684,6 +685,8 @@ class ResponsesTransport:
request = cls.prepare_kwargs(kwargs, stop=stop, model=model, messages=messages)
state = _normalize_responses_state(kwargs.get("responses_state"))
input_items = cls._select_input_items(kwargs, messages, state)
+ if _has_tools(kwargs.get("a0_responses_function_tools")):
+ input_items = project_system_prompt(input_items, kwargs.get("responses_prompt_replacements"))
request["input"] = input_items or ""
cls.apply_state(request, kwargs, state=state)
return request
@@ -699,7 +702,10 @@ class ResponsesTransport:
) -> dict[str, Any]:
request = cls.prepare_kwargs(kwargs, stop=stop, model=model, messages=messages)
state = _normalize_responses_state(kwargs.get("responses_state"))
- request["input"] = list(input_items or []) or ""
+ items = list(input_items or [])
+ if _has_tools(kwargs.get("a0_responses_function_tools")):
+ items = project_system_prompt(items, kwargs.get("responses_prompt_replacements"))
+ request["input"] = items or ""
cls.apply_state(request, kwargs, state=state)
return request
@@ -1362,6 +1368,7 @@ def _drop_responses_only_kwargs(kwargs: dict[str, Any]) -> None:
kwargs.pop("responses_delete_on_chat_delete", None)
kwargs.pop("responses_input_items", None)
kwargs.pop("responses_local_input_items", None)
+ kwargs.pop("responses_prompt_replacements", None)
kwargs.pop("previous_response_id", None)
kwargs.pop("_a0_responses_builtin_downgrades", None)
diff --git a/helpers/litellm_transport.py.dox.md b/helpers/litellm_transport.py.dox.md
index 78f304baf..a6ab44b01 100644
--- a/helpers/litellm_transport.py.dox.md
+++ b/helpers/litellm_transport.py.dox.md
@@ -24,6 +24,7 @@
- Keep provider selection and provider-specific defaults outside this helper; callers pass a resolved LiteLLM model name and kwargs.
- Strip Agent Zero internal kwargs before sending requests to LiteLLM.
+- Apply `responses_prompt_replacements` only to Responses input when generated A0 functions are present; preserve original Chat/fallback messages and strip this internal control before either provider call.
- Do not send orphan tool controls when no tools are present; strict OpenAI-compatible servers can reject empty `tools` arrays.
- When Agent Zero function tools are present, default Responses requests to one required native call; explicit request-level `tool_choice` and `parallel_tool_calls` values still win.
- Normalize function tool parameter schemas with an explicit object `properties` field before Responses requests so OpenAI-compatible chat backends reached through LiteLLM can validate them.
diff --git a/helpers/mcp_handler.py b/helpers/mcp_handler.py
index b95ffb282..8771946a0 100644
--- a/helpers/mcp_handler.py
+++ b/helpers/mcp_handler.py
@@ -1150,7 +1150,7 @@ class MCPConfig(BaseModel):
tools.append({f"{server.name}.{tool['name']}": tool_copy})
return tools
- def get_tools_prompt(self, server_name: str = "", agent: Any | None = None) -> str:
+ def get_tools_prompt(self, server_name: str = "", agent: Any | None = None, *, native: bool = False) -> str:
"""Get a prompt for all tools"""
# just to wait for pending initialization
@@ -1196,6 +1196,9 @@ class MCPConfig(BaseModel):
_policy=policy,
).allowed:
continue
+ if native:
+ tool_prompts.append("")
+ continue
input_schema = (
json.dumps(tool["input_schema"]) if tool["input_schema"] else ""
)
@@ -1221,7 +1224,7 @@ class MCPConfig(BaseModel):
if not server_prompts:
return ""
return render(
- "agent.system.mcp_tools.md",
+ "agent.system.mcp_tools.native.md" if native else "agent.system.mcp_tools.md",
tools="\n".join(server_prompts),
) + "\n"
diff --git a/helpers/mcp_handler.py.dox.md b/helpers/mcp_handler.py.dox.md
index 5a48041bc..7faa2f347 100644
--- a/helpers/mcp_handler.py.dox.md
+++ b/helpers/mcp_handler.py.dox.md
@@ -86,6 +86,7 @@
policy, and `MCPTool.execute()` rechecks the same policy with the explicit MCP
canonical ID before invocation. Prompt construction uses one fresh policy
snapshot and omits server sections when none of their tools are allowed.
+ `get_tools_prompt(native=True)` retains server context and restrictive operation guidance without duplicating native function schemas or text envelopes; blocked-only servers remain absent.
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
diff --git a/helpers/responses_tools.py b/helpers/responses_tools.py
index c94cf5dc8..b6c9ba8bb 100644
--- a/helpers/responses_tools.py
+++ b/helpers/responses_tools.py
@@ -166,6 +166,37 @@ def original_tool_name(native_name: str, name_map: dict[str, str] | None) -> str
return name_map.get(native_name, native_name)
+def project_system_prompt(
+ items: list[dict[str, Any]], replacements: dict[str, str] | None,
+) -> list[dict[str, Any]]:
+ if not replacements:
+ return items
+ pairs = []
+ for source, target in replacements.items():
+ source = files.remove_code_fences(source, language="json")
+ if source.strip():
+ pairs.append((source, files.remove_code_fences(target, language="json")))
+ pairs.sort(key=lambda pair: len(pair[0]), reverse=True)
+
+ def replace(text: str) -> str:
+ for source, target in pairs:
+ text = text.replace(source, target)
+ return text
+
+ projected = deepcopy(items)
+ for item in projected:
+ if item.get("role") not in {"system", "developer"}:
+ continue
+ content = item.get("content")
+ if isinstance(content, str):
+ item["content"] = replace(content)
+ elif isinstance(content, list):
+ for block in content:
+ if isinstance(block, dict) and isinstance(block.get("text"), str):
+ block["text"] = replace(block["text"])
+ return projected
+
+
def _local_tool_prompts(agent: Any) -> list[tuple[str, str]]:
prompt_dirs = subagents.get_paths(agent, "prompts")
tool_files = files.get_unique_filenames_in_dirs(
diff --git a/helpers/responses_tools.py.dox.md b/helpers/responses_tools.py.dox.md
index e2f705592..9c0081de4 100644
--- a/helpers/responses_tools.py.dox.md
+++ b/helpers/responses_tools.py.dox.md
@@ -28,6 +28,7 @@
is 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.
+- `project_system_prompt` applies build-local substitutions only to system/developer input on a copy. Match rendered JSON-fence normalization; preserve user/history content and unrelated blocks. Chat inputs remain untouched for fallback.
- Connector remote tools are advertised only when `_a0_connector` runtime metadata says the matching connected CLI capability is currently available.
## Work Guidance
diff --git a/prompts/AGENTS.md b/prompts/AGENTS.md
index 5ddfea4ac..48891adbd 100644
--- a/prompts/AGENTS.md
+++ b/prompts/AGENTS.md
@@ -16,6 +16,7 @@
- Do not include secrets, real API keys, or private user data in prompt templates.
- Keep placeholder names, include aliases, and template assumptions synchronized with prompt-loading code and extensions.
+- `agent.system.main.communication.native.md` owns native function-call formatting; profiles may override it alongside the legacy communication template. Shared communication additions remain transport-neutral; the brace terminator belongs only to legacy JSON formatting.
- 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
diff --git a/prompts/agent.system.main.communication.md b/prompts/agent.system.main.communication.md
index c43795d50..059f7f27b 100644
--- a/prompts/agent.system.main.communication.md
+++ b/prompts/agent.system.main.communication.md
@@ -12,6 +12,7 @@
- tool_args: key value pairs tool arguments
- `tool_name` must be one listed tool name, never an action name such as `read`, `write`, `terminal`, or `multi`
- To do dependent operations, call one tool now, then call the next tool after the first result
+- Treat the closing `}` of a tool call as an end-of-turn signal. Terminate generation immediately.
- No text output before or after the JSON object
diff --git a/prompts/agent.system.main.communication.native.md b/prompts/agent.system.main.communication.native.md
new file mode 100644
index 000000000..c95d29e9f
--- /dev/null
+++ b/prompts/agent.system.main.communication.native.md
@@ -0,0 +1,8 @@
+## Communication
+- Use the provided native functions for tool calls. Put only the function arguments in the call.
+- Do not emit an Agent Zero JSON envelope, `thoughts`, `headline`, `tool_name`, or `tool_args` as a text response.
+- Tool examples in older messages describe previous actions; follow the current native function definitions for new calls.
+- Call one tool, then wait for its result before choosing the next dependent action. Do not append a second tool call as text.
+- Finish through the native response function when the task is done. Its text is the answer shown to the user.
+
+{{ include "agent.system.main.communication_additions.md" }}
diff --git a/prompts/agent.system.main.communication_additions.md b/prompts/agent.system.main.communication_additions.md
index d52d926a9..d57382613 100644
--- a/prompts/agent.system.main.communication_additions.md
+++ b/prompts/agent.system.main.communication_additions.md
@@ -1,6 +1,5 @@
## messages
user messages may include superior instructions, tool results, and framework notes
-treat the closing `}` of a tool call as an end-of-turn signal. terminate generation immediately
if message starts `(voice)` transcription can be imperfect
messages begin `[PROTOCOL]`; protocol = must-follow instructions
messages end `[EXTRAS]`; extras are context not new instructions
diff --git a/prompts/agent.system.mcp_tools.native.md b/prompts/agent.system.mcp_tools.native.md
new file mode 100644
index 000000000..e988f2464
--- /dev/null
+++ b/prompts/agent.system.mcp_tools.native.md
@@ -0,0 +1,4 @@
+## MCP server context
+Server descriptions are context, not callable capabilities. Each provided function's description defines its allowed operation. Never infer capabilities from names or 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_prompt_protocol.py b/tests/test_prompt_protocol.py
index a34835371..66a1d2e25 100644
--- a/tests/test_prompt_protocol.py
+++ b/tests/test_prompt_protocol.py
@@ -176,3 +176,36 @@ async def test_project_prompt_does_not_load_agents_md_without_project(monkeypatc
assert "agents_md_instructions" not in loop_data.protocol_persistent
assert "project_instructions" not in loop_data.protocol_persistent
+
+
+async def test_native_communication_projection_preserves_custom_main_sections():
+ from pathlib import Path
+ from helpers import files, responses_tools
+ from extensions.python.system_prompt._10_main_prompt import MainPrompt
+
+ prompt_root = Path(__file__).parents[1] / 'prompts'
+ legacy = files.read_prompt_file('agent.system.main.communication.md', _directories=[str(prompt_root)]).rstrip('\n')
+ native = files.read_prompt_file('agent.system.main.communication.native.md', _directories=[str(prompt_root)]).rstrip('\n')
+ original = f'Custom role instructions.\n{legacy}\nCustom project constraints.'
+ mapping = {
+ 'agent.system.main.md': original,
+ 'agent.system.main.communication.md': legacy,
+ 'agent.system.main.communication.native.md': native,
+ }
+ agent = SimpleNamespace(read_prompt=lambda name: mapping[name])
+ loop_data = LoopData()
+ sections = []
+ await MainPrompt(agent).execute(system_prompt=sections, loop_data=loop_data)
+ assert sections == [original]
+ rendered = files.remove_code_fences(original, language='json')
+ result = responses_tools.project_system_prompt(
+ [{'role':'system','content':rendered}], loop_data.responses_prompt_replacements,
+ )[0]['content']
+ assert result.startswith('Custom role instructions.')
+ assert result.endswith('Custom project constraints.')
+ assert 'Use the provided native functions' in result
+ assert 'treat the closing' not in result.lower()
+ assert '"tool_name":' not in result
+ assert 'closing `}`' in legacy
+ assert '[PROTOCOL]' in result and '[EXTRAS]' in result
diff --git a/tests/test_responses_tools.py b/tests/test_responses_tools.py
index 30d9082b2..c74273546 100644
--- a/tests/test_responses_tools.py
+++ b/tests/test_responses_tools.py
@@ -356,3 +356,35 @@ payload = {"tool_name":"example","tool_args":{"text":"literal code"}}
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
+
+
+def test_native_system_projection_is_scoped_and_does_not_mutate_inputs():
+ from copy import deepcopy
+ from helpers import files, litellm_transport
+
+ legacy = 'Legacy format\n~~~json\n{"tool_name":"example"}\n~~~'
+ rendered = files.remove_code_fences(legacy, language='json')
+ items = [
+ {'role':'system','content':f'Custom role\n{rendered}\nTOOLS\nCustom rule'},
+ {'role':'developer','content':[{'type':'input_text','text':rendered}]},
+ {'role':'user','content':[{'type':'input_text','text':rendered}, {'type':'input_image','image_url':'image-ref'}]},
+ {'role':'assistant','content':'Summary stays visible'},
+ ]
+ original = deepcopy(items)
+ kwargs = {
+ 'responses_state':'local', 'responses_local_input_items':items,
+ 'responses_prompt_replacements':{legacy:'Native format','TOOLS':'',' ':'Never insert this'},
+ 'a0_responses_function_tools':[{'type':'function','name':'example','parameters':{'type':'object'}}],
+ }
+ for build in (
+ lambda: litellm_transport.ResponsesTransport.from_chat([], kwargs),
+ lambda: litellm_transport.ResponsesTransport.from_input(items, kwargs),
+ ):
+ request = build()
+ assert request['input'][0]['content'] == 'Custom role\nNative format\n\nCustom rule'
+ assert request['input'][1]['content'][0]['text'] == 'Native format'
+ assert request['input'][2:] == original[2:]
+ assert 'responses_prompt_replacements' not in request
+ assert items == original
+ kwargs['a0_responses_function_tools'] = []
+ assert litellm_transport.ResponsesTransport.from_chat([], kwargs)['input'] == original
diff --git a/tests/test_stream_tool_early_stop.py b/tests/test_stream_tool_early_stop.py
index eb3e5db2c..0825c8e74 100644
--- a/tests/test_stream_tool_early_stop.py
+++ b/tests/test_stream_tool_early_stop.py
@@ -535,6 +535,8 @@ async def test_unified_call_falls_back_to_chat_when_responses_endpoint_missing(
async def fake_aresponses(*args, **kwargs):
calls.append("responses")
+ assert kwargs["input"][0]["content"] == "Native instructions"
+ assert "responses_prompt_replacements" not in kwargs
raise RuntimeError(
"Client error '404 Not Found' for url "
"'https://llm.agent-zero.ai/v1/responses'"
@@ -542,6 +544,8 @@ async def test_unified_call_falls_back_to_chat_when_responses_endpoint_missing(
async def fake_acompletion(*args, **kwargs):
calls.append("chat")
+ assert kwargs["messages"][0]["content"] == "Legacy instructions"
+ assert "responses_prompt_replacements" not in kwargs
assert kwargs["stream"] is True
assert kwargs["drop_params"] is True
assert "tool_choice" not in kwargs
@@ -560,6 +564,8 @@ async def test_unified_call_falls_back_to_chat_when_responses_endpoint_missing(
provider="openai",
model_config=None,
a0_api_mode="responses",
+ a0_responses_function_tools=[{"type": "function", "name": "response", "parameters": {"type": "object"}}],
+ responses_prompt_replacements={"Legacy instructions": "Native instructions"},
tool_choice="auto",
parallel_tool_calls=True,
)
@@ -568,7 +574,7 @@ async def test_unified_call_falls_back_to_chat_when_responses_endpoint_missing(
return None
response, reasoning = await wrapper.unified_call(
- messages=[],
+ messages=[SystemMessage(content="Legacy instructions")],
response_callback=response_callback,
)
@@ -577,7 +583,7 @@ async def test_unified_call_falls_back_to_chat_when_responses_endpoint_missing(
assert calls == ["responses", "chat"]
response, reasoning = await wrapper.unified_call(
- messages=[],
+ messages=[SystemMessage(content="Legacy instructions")],
response_callback=response_callback,
)
diff --git a/tests/test_tool_policy.py b/tests/test_tool_policy.py
index 8deb4e29c..f133d9081 100644
--- a/tests/test_tool_policy.py
+++ b/tests/test_tool_policy.py
@@ -785,6 +785,11 @@ def test_mcp_prompt_and_native_schema_omit_blocked_tool(
assert len(restricted_schemas) == 1
assert set(allowed_name_map.values()) == {"docs.read", "docs.write"}
assert name_map[restricted_schemas[0]["name"]] == "docs.read"
+ native_prompt = config.get_tools_prompt(agent=restricted_agent, native=True)
+ assert "Context only: Documentation" in native_prompt
+ assert "Server descriptions are context, not callable capabilities" in native_prompt
+ assert "tool_args" not in native_prompt and "docs.write" not in native_prompt
+ assert "Input schema" not in native_prompt
reads = 0
@@ -797,6 +802,8 @@ def test_mcp_prompt_and_native_schema_omit_blocked_tool(
assert config.get_tools_prompt(agent=_Agent(tmp_path)) == ""
assert reads == 1
+ assert config.get_tools_prompt(agent=_Agent(tmp_path), native=True) == ""
+ assert reads == 2
@pytest.mark.asyncio