RFC: `ToolEnvelope` — a standard tool result schema that drives `ReflectAndRetryToolPlugin` (retryable errors, `no_match`, circuit-breaker cooldown)
🔴 Required Information
Is your feature request related to a specific problem?
Yes. ReflectAndRetryToolPlugin (src/google/adk/plugins/reflect_retry_tool_plugin.py) decides whether a tool call failed from a binary signal — a raised exception, or a non-None return from extract_error_from_result — and it only sees that signal after the tool has run. Four problems follow, and they share one root cause: ADK has no standard way for a tool to say what its result means.
1. As shipped, the plugin is a no-op for the dominant ADK tool style.
extract_error_from_result is a no-op by default, and at least 13 files under src/google/adk/tools/ catch their exceptions and return a status dict instead of raising (e.g. discovery_engine_search_tool.py catches GoogleAPICallError → {'status': 'error', 'error_message': ...}; spanner/search_tool.py returns {"status": "ERROR", "error_details": ...}). For every one of them, the default plugin treats the failure as a success and resets the counter. The only remedy is to subclass the plugin (the docstring's CustomRetryPlugin), and each project invents its own notion of what counts as an error.
ADK already answers "did this tool result represent an error?" in four places, four ways:
| Site | Reads | Can a plain Python tool participate? |
|---|---|---|
ReflectAndRetryToolPlugin.extract_error_from_result |
nothing (no-op) | only by subclassing |
plugins/_callback_helpers.py built-in rules for the analytics/logging plugins (#7112 → ToolResultClassification) |
MCP isError/is_error, the retry plugin's response_type |
no (or an app-side classifier per plugin) |
McpTool._detect_error_in_response (telemetry) |
isError/is_error |
no |
AnthropicLlm → tool_result.is_error (#7664) |
isError/is_error |
no — a tool returning {"status": "error"} is sent to Claude as a success |
Only MCP's isError is understood by three of the four; a quickstart-style Python tool is understood by none.
2. "Is this an error?" cannot express retryable.
Even with the override in place, the plugin has no notion of whether an error is worth retrying:
- A permanent error (authorization denied, resource does not exist) still gets "This is retry attempt 1 of 3 … try a corrected or different approach", burning up to
max_retriesmodel turns on a call that can never succeed. - A write that times out (
create_order,send_email,charge_card) is ambiguous — it may have committed server-side before the client gave up — and the plugin actively instructs the model to call it again. That is a duplicate-write risk, not a latency problem.
3. "Is this an error?" conflates no_match with call_failed.
Tools return an error-shaped dict for "0 results found" because a plain empty list is easy for the model to gloss over — and that error dict trips the retry loop and the failure counter. Only a genuine dependency failure (429/503/timeout) should count toward retries or a circuit breaker; an empty but successful lookup is a healthy execution.
4. Nothing enforces "stop calling this tool" once retries are exhausted.
After exhaustion the plugin either re-raises or returns prose ("Do not attempt to use the {tool} tool again for this task."). The tool's FunctionDeclaration is still in every subsequent LlmRequest, and if the model calls it again the tool still runs. The guide documents this (docs/guides/plugins/reflect_retry_tool_plugin/index.md → Limitations → "Relies on the model acting on guidance"). With TrackingScope.GLOBAL there is also no cooldown, no probe call, and no automatic return to healthy once the dependency recovers.
Describe the Solution You'd Like
Three coupled, opt-in pieces, deliverable as three PRs (see Delivery plan). A plain def get_weather(city: str) -> dict quickstart tool is unaffected by all of them; defaults preserve today's behavior exactly.
Part 1 — ToolEnvelope: an opt-in standard result schema (google.adk.tools)
A small Pydantic model a tool may return instead of a bare dict. One three-state discriminator plus a retryable flag encodes everything the plugin needs:
from google.adk.tools import ToolEnvelope
ToolEnvelope(
status="data_returned" | "no_match" | "call_failed",
retryable=..., # bool; required when status == "call_failed", ignored otherwise
error_code=..., # optional short code, e.g. "PERMISSION_DENIED", "WRITE_TIMEOUT_UNCONFIRMED"
error_message=..., # optional human-readable detail, shown to the model
data=..., # the payload the model should see
provenance=[...], # optional, reserved (see Non-goals)
)
| Tool outcome | Envelope |
|---|---|
| Lookup found data / write confirmed | status="data_returned", data=... |
| Lookup ran fine but matched nothing | status="no_match" |
| Dependency failure worth retrying (429, 503, read timeout) | status="call_failed", retryable=True |
| Invalid arguments the model can correct | status="call_failed", retryable=True (see definition below) |
| Permanent error, or an unconfirmed write (timeout on a non-idempotent call) | status="call_failed", retryable=False |
Definition of retryable. This is the agent sense, not the gRPC "same request may succeed" sense:
retryable=True— re-invoking this tool for this task, with the same or corrected arguments, is safe and may succeed. AnINVALID_ARGUMENTis thereforeretryable=True: the plugin's reflection guidance ("Invalid Parameters: review the tool's schema and your arguments") exists precisely for it.retryable=False— do not re-invoke this tool for this task: the error is permanent (authorization, non-existent resource) or repeating the call is unsafe (unconfirmed write).
retryable is required on call_failed so that a tool author must make the idempotency call explicitly rather than inherit a default in either direction. Adapters that cannot know (an MCP toolset mapping isError, an OpenAPI toolset mapping 5xx) pass retryable=True explicitly — that is today's behavior — and applications override per tool with non_retryable_tools (Part 3).
On no_match. The retry behavior below does not depend on it — it is handled exactly like data_returned. It exists so that tools have a sanctioned way to make an empty result visible to the model without misusing error to do so, which is how problem 3 arises. Write tools never use it. It is the state I hold most loosely (open question 1).
Part 2 — ReflectAndRetryToolPlugin reads the envelope natively
| Tool return value | Behavior in ReflectAndRetryToolPlugin |
|---|---|
| Plain dict / primitive (every existing tool) | Unchanged. extract_error_from_result override still applies. |
ToolEnvelope with data_returned or no_match |
Healthy execution: resets the tool's failure counter (_reset_failures_for_tool). |
ToolEnvelope with call_failed, retryable=True |
Takes the existing reflection path (_handle_tool_error) — increments the counter, returns the "attempt N of M" ToolFailureResponse with error_code/error_message rendered into the guidance. No subclass required. |
ToolEnvelope with call_failed, retryable=False |
Goes straight to the give-up path: raises if throw_exception_if_retry_exceeded, otherwise returns the "do not use this tool again" ToolFailureResponse. The model is never told to try again. If the breaker (Part 3) is enabled, it opens. |
Part 3 — Circuit breaker with cooldown, and non_retryable_tools
The envelope tells the plugin what happened; this part lets the plugin enforce the consequence instead of relying on prose.
CLOSED --(consecutive failures exceed max_retries, or a non-retryable failure)--> OPEN
OPEN --(cooldown_seconds elapsed)-----------------------------------------> HALF_OPEN
HALF_OPEN --(the single probe call succeeds)---------------------------------> CLOSED (counter reset)
HALF_OPEN --(the probe fails)------------------------------------------------> OPEN (cooldown restarts)
Wired into the two BasePlugin hooks the plugin does not use today:
before_tool_callback— short-circuit (the essential half). If the breaker is OPEN, or HALF_OPEN with a probe already in flight, return aToolFailureResponsewitherror_type="CircuitOpen"without executing the tool. The response carriesresponse_type=REFLECT_AND_RETRY_RESPONSE_TYPE, so the marker check at the top ofafter_tool_callbackalready keeps it from being counted as a new failure (abefore_tool_callbackresult still flows throughafter_tool_callback; seeworkflow/_tool_node.py). This composes with the current code path unchanged and on its own delivers the safety property.before_model_callback— tool stripping (optional,hide_open_tools_from_model, deferrable). For every tool inllm_request.tools_dictwhose breaker is OPEN, remove itsFunctionDeclarationfromllm_request.config.tools(mutate in place, returnNone) so the model cannot select it, andappend_instructionsa one-line note ("ToolXis temporarily unavailable (available again in ~Ns)") so the model tells the user instead of hallucinating a call. Once the cooldown elapses the breaker moves to HALF_OPEN and the declaration is left in place — that is how the probe gets to happen. Stripping is best-effort by design (history, shared plugin instances), which is why the short-circuit exists regardless; if reviewers prefer, it can land as a separate follow-up PR.after_tool_callback/on_tool_error_callback— detection as above;_handle_tool_erroradditionally drives the transitions, and the existing success path closes the breaker.
non_retryable_tools — a collection of tool names whose first failure of any kind takes the give-up path (and opens the breaker if enabled). This is the escape hatch for tools you cannot change to return an envelope: third-party toolsets, MCP servers, AgentTools. Envelope for the tools you write; non_retryable_tools for the ones you don't. (Same producer-flag + consumer-list pair as Temporal's ApplicationError(non_retryable=True) and RetryPolicy(non_retryable_error_types=...).)
Delivery plan
- PR 1 —
ToolEnvelopeingoogle.adk.tools+ unit tests. No behavior change anywhere. - PR 2 —
ReflectAndRetryToolPluginreads the envelope (Part 2) + tests intests/unittests/plugins/test_reflect_retry_tool_plugin.py+ guide update. Fixes problems 1–3. - PR 3 — breaker +
non_retryable_tools(Part 3):before_tool_callbackshort-circuit first;before_model_callbackstripping in the same PR or a follow-up, per review. Fixes problem 4.
Follow-ups that fall out naturally once the schema exists (not part of this RFC): the _callback_helpers built-in rule classifies call_failed as a tool error for analytics/logging; AnthropicLlm sets is_error=True for call_failed; built-in tools migrate from ad-hoc status dicts.
Impact on your work
Any deployment that points this plugin at slow or flaky backends pays for problem 4 twice per ignored instruction (a full tool timeout plus a model round-trip); problem 2 is a correctness risk rather than a latency one (a retried write timeout can duplicate a side effect); and problems 1 and 3 mean every team re-implements the same CustomRetryPlugin with slightly different ideas of what counts as an error. The retryable=False / non_retryable_tools half is a safety property that today cannot be expressed without overriding private methods. Not timeline-critical.
Willingness to contribute
Yes — happy to put up the PRs in the order above once the shape is agreed, including tests, the doc update to docs/guides/plugins/reflect_retry_tool_plugin/index.md, and a sample under contributing/samples/plugins/plugin_reflect_tool_retry/.
🟡 Recommended Information
Describe Alternatives You've Considered
- Keep subclassing
extract_error_from_result(status quo). Solves problem 1 per project, cannot solve 2 or 3 (the override returns "an error" orNone; there is nowhere to say retryable or no match), and does nothing for 4. - Extend
ToolResultClassification(google.adk.plugins) with aretryablefield. That type is a consumer-side verdict for the analytics/logging plugins ("OK" | "ERROR"), configured per plugin by the application, and its docstring explicitly excludes retry-plugin answers. Putting "is this retryable" in app-level plugin config means the one party that actually knows — the tool — cannot say it. The two are complementary: the built-in rule's read-set already includesresponse_type, so it can learn the envelope's marker in one line. - Typed exceptions (
RetryableToolError/NonRetryableToolError). Only works for tools that raise; losesno_matchentirely; and remote tools (MCP, A2A, OpenAPI) cannot raise a typed Python exception across the wire, whereas they can return a dict. MCP'sisErrorand Anthropic'stool_result.is_errorexist for exactly this reason. - A separate
CircuitBreakerPlugin. Feasible, but it would need its own failure counter kept in lock-step with this plugin'sScopedFailureTracker(same scope key, same reset-on-success semantics). Two sources of truth for "how many times has this tool failed" is worse than one. - Idempotency keys inside write tools. The right long-term answer for writes, but a framework plugin cannot assume it of every tool, and it does nothing for problems 1, 3 or 4.
Proposed API / Implementation
Schema (src/google/adk/tools/tool_envelope.py, exported from google.adk.tools):
TOOL_ENVELOPE_MARKER = "ADK_TOOL_ENVELOPE_V1"
class ToolEnvelope(BaseModel):
"""Opt-in structured result for tools that want ADK plugins to understand the outcome."""
# Survives model_dump(); same marker idea the retry plugin already uses for
# its own responses, and a key the _callback_helpers rules already read
# (they compare by exact value, so a new value is not misclassified).
response_type: Literal["ADK_TOOL_ENVELOPE_V1"] = TOOL_ENVELOPE_MARKER
status: Literal["data_returned", "no_match", "call_failed"]
retryable: Optional[bool] = None
error_code: Optional[str] = None
error_message: Optional[str] = None
data: Any = None
provenance: list[dict[str, Any]] = Field(default_factory=list) # reserved
@model_validator(mode="after")
def _require_retryable_on_failure(self) -> "ToolEnvelope":
if self.status == "call_failed" and self.retryable is None:
raise ValueError("retryable must be set when status is 'call_failed'")
return self
@classmethod
def from_result(cls, result: Any) -> Optional["ToolEnvelope"]:
"""Returns the envelope a tool result carries, or None for any other result."""
if isinstance(result, ToolEnvelope):
return result
if isinstance(result, dict) and result.get("response_type") == TOOL_ENVELOPE_MARKER:
return cls.model_validate(result)
return None
Tool author's view:
async def search_orders(customer_id: str) -> ToolEnvelope:
try:
rows = await orders_api.search(customer_id, timeout=10)
except TimeoutError:
return ToolEnvelope(status="call_failed", retryable=True, error_code="UPSTREAM_TIMEOUT")
except PermissionError as e:
return ToolEnvelope(status="call_failed", retryable=False,
error_code="PERMISSION_DENIED", error_message=str(e))
if not rows:
return ToolEnvelope(status="no_match", data={"customer_id": customer_id})
return ToolEnvelope(status="data_returned", data={"orders": rows})
async def create_order(customer_id: str, sku: str) -> ToolEnvelope:
try:
order = await orders_api.create(customer_id, sku, timeout=30)
except TimeoutError:
# The write may have committed; a retry could duplicate it.
return ToolEnvelope(status="call_failed", retryable=False,
error_code="WRITE_TIMEOUT_UNCONFIRMED")
return ToolEnvelope(status="data_returned", data=order)
Plugin configuration:
plugin = ReflectAndRetryToolPlugin(
max_retries=3,
throw_exception_if_retry_exceeded=False,
tracking_scope=TrackingScope.GLOBAL,
# --- new, all optional ---
cooldown_seconds=30.0, # None (default) = no breaker, today's behavior
hide_open_tools_from_model=True, # strip the FunctionDeclaration while OPEN
non_retryable_tools={"legacy_payment_mcp_tool"},
)
Plugin sketch (names tentative):
async def after_tool_callback(self, *, tool, tool_args, tool_context, result):
if _is_reflect_retry_response(result): # existing marker check, unchanged
return None
envelope = ToolEnvelope.from_result(result)
if envelope is None: # plain dict: today's path, unchanged
error = await self.extract_error_from_result(tool=tool, tool_args=tool_args,
tool_context=tool_context, result=result)
if error:
return await self._handle_tool_error(tool, tool_args, tool_context, error)
await self._reset_failures_for_tool(tool_context, tool.name)
return None
if envelope.status in ("data_returned", "no_match"):
await self._reset_failures_for_tool(tool_context, tool.name)
return None
error = ToolEnvelopeError(envelope) # Exception carrying code/message, so the
if not envelope.retryable: # raise path stays informative
return await self._give_up(tool, tool_args, tool_context, error) # opens breaker
return await self._handle_tool_error(tool, tool_args, tool_context, error)
async def before_tool_callback(self, *, tool, tool_args, tool_context):
if self._breaker is None:
return None
scope_key = self._get_scope_key(tool_context)
state = await self._breaker.state(scope_key, tool.name) # OPEN -> HALF_OPEN on expiry
if state is _CircuitState.OPEN or (
state is _CircuitState.HALF_OPEN
and not await self._breaker.try_acquire_probe(scope_key, tool.name)):
return self._create_circuit_open_response(tool, tool_args) # tool is NOT run
return None
async def before_model_callback(self, *, callback_context, llm_request):
if self._breaker is None or not self.hide_open_tools_from_model:
return None
scope_key = self._get_scope_key(callback_context)
open_tools = [name for name in llm_request.tools_dict
if await self._breaker.state(scope_key, name) is _CircuitState.OPEN]
if open_tools:
_strip_function_declarations(llm_request, open_tools) # config.tools only; tools_dict
llm_request.append_instructions([...]) # untouched so a stray call still
return None # hits the short-circuit above
Design notes:
- Where the envelope is seen.
after_tool_callbackreceives the tool's raw return value (workflow/_tool_node.py), sofrom_resultcan match the instance or itsmodel_dump(). Today a Pydantic return is not serialized for the model (flows/llm_flows/tools/_caller.pywraps non-dicts as{'result': value}); tools can returnenvelope.model_dump()as-is, and a one-lineBaseModel → model_dump(mode="json")in_caller.pywould let them return the instance directly. Either way the model sees a plain dict. - Plugin ordering.
PluginManagerstops at the first plugin that returns a value (as #7112 describes), so the retry plugin's response replaces the tool result for plugins after it. Unchanged by this RFC; the marker-based detection already copes with it. - Scope key.
_get_scope_keyreadsinvocation_idoff the context. In 2.0ToolContextandCallbackContextare both aliases ofContext, so the same method servesbefore_model_callbackwith no signature change. - Shared state.
ScopedFailureTrackeris shared with_reflect_retry_model_plugin.py; the breaker would live beside it in_reflect_retry_utils.pyunder the same asyncio-lock discipline (coroutine-safe, not thread-safe — the caveat the tracker already documents), so the model plugin could adopt it later. - HALF_OPEN under parallel function calls. Exactly one concurrent call may probe; the rest get the short-circuit response.
try_acquire_probeis the atomic check-and-set that guarantees it. - Clock injection (
time.monotonicby default) so tests advance time without sleeping. - Memory and lifecycle. CLOSED pops the entry, mirroring
ScopedFailureTracker.reset. Per-invocation breaker and counter state is also dropped in bothafter_run_callbackandon_run_error_callback— the runner calls only one of them per run, and neither on cancellation — and kept in a bounded map. Note that today'sScopedFailureTrackernever drops an invocation's scope dict (only per-item counters are popped) and the retry plugins implement no run-end hook, soINVOCATION-scope state already leaks on every run that ends in an error; PR 3 fixes that in passing. (Added after review on #7770.) - Visibility.
ToolEnvelopeis public (tool authors return it)._CircuitState, the breaker helper and the stripping helper stay private; the plugin's public surface grows by three constructor kwargs. - Relation to #7564 (customizable reflection guidance): the
CircuitOpenand give-up messages would be built through whichever guidance hook lands there, so the two changes compose rather than both reaching into_create_tool_reflection_response/_get_tool_retry_exceed_msg.
Additional Context
- Non-goals for this RFC.
provenanceis reserved on the schema (source ids a tool can attach for later citation checking) but no plugin reads it here; a retry plugin should not be writing session state, and that behavior deserves its own issue. Multimodal results (parts extracted by_caller.pyfrom the raw result) are out of scope for v1 — an envelope'sdatais plain JSON. Migrating built-in tools from ad-hoc status dicts to the envelope is a follow-up, not a prerequisite. - Related: #7564 (open) customizes this plugin's guidance text; #7112 and #7664 are the two most recent cases of a consumer needing "is this result an error?" and solving it locally; #4087 (closed) asked for resilience on
AgentToolspecifically — this proposal applies to anyBaseTool. max_retries=0already bypasses the counter inside_handle_tool_error;retryable=Falseandnon_retryable_toolsreuse that give-up path rather than adding a new one.
Open questions for maintainers
no_match. Keep it as a third state (model-facing signal that removes the incentive to misuseerrorfor empty results), or fold it intodata_returnedwith emptydataand keep the schema two-state +retryable? Retry behavior is identical either way.- Naming.
statuswithdata_returned | no_match | call_failed, oroutcometo avoid colliding with the existing ad-hoc"status": "error"dicts? The marker key makes the two unambiguous to code, but not to readers. - Marker. Reuse
response_type(consistent with the retry plugin's own responses and already read by_callback_helpers), or a dedicated key? - Should a non-retryable
call_failedopen the breaker? Proposed: yes, for consistency with today's exhaustion semantics (the plugin already treats N consecutive failures of any kind as "stop using this tool"). The alternative is to open only on retryable failures and treatretryable=Falseas per-call advice. non_retryable_toolsasCollection[str]only, or also a predicateCallable[[BaseTool, Any], bool]so only timeouts on a third-party write tool are non-retryable while its validation errors still retry?- Land
before_model_callbackstripping with PR 3, or defer it to a follow-up once the short-circuit has shipped? - Fixed
cooldown_secondsfor v1, or exponential backoff on repeated OPENs?
+1 on this proposal. Looking at the current ReflectAndRetryToolPlugin, the default extract_error_from_result returns None, so tools that report failure via an {"error": ...} dict instead of raising are counted as successes unless you subclass and override it. A standard envelope with an explicit retryable flag seems like a cleaner fix than every user writing their own extractor.
A couple of thoughts on the open questions:
- I'd keep
no_matchas a distinct status. Treating an empty result as a failure nudges the model into pointless retries, and treating it as plain success loses useful signal. - For cooldown, starting with a fixed duration and leaving exponential backoff as a follow-up seems reasonable to keep the first version simple.
@juliays happy to help if useful. I could take the circuit-breaker PR (3), or write tests for the envelope + plugin integration. I'll wait until maintainers are aligned on the design before starting so we don't duplicate work.
+1 on this proposal. Looking at the current
ReflectAndRetryToolPlugin, the defaultextract_error_from_resultreturnsNone, so tools that report failure via an{"error": ...}dict instead of raising are counted as successes unless you subclass and override it. A standard envelope with an explicitretryableflag seems like a cleaner fix than every user writing their own extractor.A couple of thoughts on the open questions:
- I'd keep
no_matchas a distinct status. Treating an empty result as a failure nudges the model into pointless retries, and treating it as plain success loses useful signal.- For cooldown, starting with a fixed duration and leaving exponential backoff as a follow-up seems reasonable to keep the first version simple.
@juliays happy to help if useful. I could take the circuit-breaker PR (3), or write tests for the envelope + plugin integration. I'll wait until maintainers are aligned on the design before starting so we don't duplicate work.
@Dhirajreddy2001 Thanks for the +1 and your votes on the questions. Look forward to the maintaner's responses.
Follow-up for the reserved provenance field: #7770 proposes ProvenanceGatePlugin, a deterministic runtime check that citation IDs in a model response were actually returned by a tool during the current invocation.
It does not depend on this RFC — it works on plain dict results via a configurable extractor — but ToolEnvelope.provenance would be its zero-config source, which makes it the concrete consumer behind open question 1 above (whether the reserved field earns its place).
The table maps an unconfirmed write to call_failed with retryable=False, which gets the no-retry part right but sends it down the same give-up path as PERMISSION_DENIED: the breaker opens on a dependency that may be perfectly healthy, and the model tells the user the order failed when it may well exist. I'd give it a status of its own, something like outcome_unknown, that never retries and never counts toward the breaker, and whose next step is a read-back by idempotency key or a human check before the run moves on.
Would you put that reconcile step in the plugin, or leave it to the tool author as a separate lookup tool?
Hello @juliays,
Thank you for raising this request, we will review it and reach out to you for further details if required. We appreciate your patience in the meantime.
Strong RFC—separating retryable vs. non-retryable tool outcomes at the envelope level is much cleaner than letting the LLM guess from raw error strings.
One edge case worth explicitly modeling in ToolEnvelope is the unknown_outcome / post-commit ambiguity state (e.g., ReadTimeout, dropped connection, or 502 on a mutating HTTP call). Treating that as blindly retryable=True without a persisted (operation_id, tool_name, tool_call_id) idempotency key or a sink-reconciliation lookup (GET by key) will silently double-write on ReflectAndRetryToolPlugin retries—whereas blocking retries unconditionally drops legitimate pre-commit 503s. Distinguishing retryable_pre_commit vs. reconcile_required in the envelope would save ADK users from both failure modes.
(Disclosure: I maintain agent-fault-check, an Apache-2.0 fault-injection proxy for CI; we recently benchmarked these exact 502-after-commit vs. 503 failure modes across 4 Python agent frameworks here: https://afc.evhu.net/benchmarks.html)