Extending the Runner Pipeline with Custom Middlewares and Hooks
Extend the ADK Runner pipeline with agent callbacks and BasePlugin hooks: return-value semantics, precedence rules, error hooks, and registering plugins on the App object.
Published on • November 24, 2026
AI Assistant

ADK has no class literally named Middleware, but it has something better: two layers of hooks that wrap every stage of the Runner pipeline — before and after agent execution, before and after every model call, before and after every tool, around each yielded event, and even on errors. These are callbacks and plugins, and they are where guardrails, caching, tracing, and output rewriting live.
Callbacks are local: you attach them to a single agent instance. Plugins are global: you register one module on the App (or the Runner) and its hooks apply to every agent, model, and tool that runner manages. This post covers both layers, the return-value semantics that make them act like real middleware, and the ordering rules that decide who wins.
The callback surface
Six standard callbacks wrap the main pipeline stages, available on any agent that inherits from BaseAgent:
| Callback | When it runs | Return value effect |
|---|---|---|
before_agent_callback | Immediately before _run_async_impl | Content → skip the agent, use it as the final output |
after_agent_callback | After the agent finishes | Content → append as an extra event (cannot replace) |
before_model_callback | Just before generate_content_async | LlmResponse → skip the LLM, use it as the response |
after_model_callback | Just after the LlmResponse arrives | LlmResponse → replace the model’s response |
before_tool_callback | Just before the tool’s run_async | dict → skip the tool, use it as the result |
after_tool_callback | After the tool succeeds | dict → replace the tool’s result |
LlmAgent additionally accepts on_model_error_callback and on_tool_error_callback: return an LlmResponse/dict to suppress the exception and substitute a fallback, or None to let it propagate. Returning None from any before_* callback simply means “proceed normally,” which is the observe-only mode.
def guard_model(callback_context, llm_request, llm_response=None):
user_text = callback_context.state.get("last_user_text", "")
if "ignore previous instructions" in user_text.lower():
return types.Content(role="model", parts=[types.Part.from_text("Blocked.")])
return None # let the call proceed / pass the response through
Watch two sharp edges: ADK compares returns against None, so returning {} from before_tool_callback skips the tool and uses {} as the result — return None, not {}, when you want the tool to run. And after_tool_callback receives the tool’s raw return value (a str for a function annotated -> str), because wrapping into {"result": ...} happens after the callback runs.
Building a plugin
A plugin extends BasePlugin and implements the same hook names, plus runner-level and error hooks:
from google.adk.agents.base_agent import BaseAgent
from google.adk.agents.callback_context import CallbackContext
from google.adk.models.llm_request import LlmRequest
from google.adk.plugins.base_plugin import BasePlugin
class CountInvocationPlugin(BasePlugin):
def __init__(self) -> None:
super().__init__(name="count_invocation")
self.agent_count = 0
self.llm_request_count = 0
async def before_agent_callback(
self, *, agent: BaseAgent, callback_context: CallbackContext
) -> None:
self.agent_count += 1
async def before_model_callback(
self, *, callback_context: CallbackContext, llm_request: LlmRequest
) -> None:
self.llm_request_count += 1
Registration goes on the App, which you then hand to the runner — in Python, Runner(plugins=...) is deprecated (it raises a DeprecationWarning, and passing both plugins and app raises a ValueError):
from google.adk.apps import App
from google.adk.runners import InMemoryRunner
app = App(name="test_app_with_plugin", root_agent=root_agent,
plugins=[CountInvocationPlugin()]) # multiple plugins allowed
runner = InMemoryRunner(app=app)
The full plugin hook surface
Plugins see more of the lifecycle than agent callbacks do:
on_user_message_callback— the very first hook, afterrunner.run(); returnContentto replace the user’s message.before_run_callback— global setup before any agent logic; returnContentto halt the run with that content as the result.before_agent/after_agent/on_agent_error_callback— agent execution; the error hook runs when the agent raises, and its return value is ignored (the exception still propagates).before_model/after_model/on_model_error— model calls; return anLlmResponseto short-circuit or suppress an error.before_tool/after_tool/on_tool_error— tool calls; return adictto skip, replace, or recover.on_event_callback— fires for each event after an agent yields it but before it streams to the client; return anEventto override it (in Python ADK merges your fields onto the original, whileid,invocation_id, andtimestampalways come from the original event).on_run_error_callback— run-level failure handling.
Each hook has exactly three modes: observe (return nothing, workflow proceeds), intervene (return a value, which short-circuits — the Runner halts the step and skips subsequent plugins), and amend (mutate the context object without interrupting).
Ordering, precedence, and failure rules
- Plugins run first. Plugin callbacks execute before any agent-level callback; if a plugin returns anything other than
None, the corresponding agent/model/tool-level callback is skipped. - List order wins. With multiple plugins, ADK runs hooks in the order they appear in
pluginsand stops at the first one that returns a non-Nonevalue. - Names must be unique. Two plugins with the same
nameraise aValueErrorwhen the runner is created. - Errors surface loudly. An exception in a plugin callback reaches your code as a
RuntimeErrorwith the original exception as__cause__; theon_agent_error_callbackandon_run_error_callbackhooks are the exceptions — ADK runs them on every plugin and logs anything they raise instead of raising.
Load plugins without touching agent code
Python ADK can inject plugins at launch time via --extra_plugins on adk web or adk api_server, added after any plugins your App registers (pass a class only if its constructor accepts name; otherwise pass a module-level instance, and repeat the flag for more):
adk web --extra_plugins=google.adk.plugins.LoggingPlugin /path/to/agents
The distribution already ships useful ones: LoggingPlugin, DebugLoggingPlugin, AutoTracingPlugin (wraps your functions in OpenTelemetry spans), GlobalInstructionPlugin, ContextFilterPlugin, SaveFilesAsArtifactsPlugin, plus reflect-and-retry and tool-call-integrity plugins. For observability callbacks wired into third-party tools, this is the same hook family used to build the traces discussed in explainable-actions-agent-reasoning-trust.md.
Takeaway: Think of ADK callbacks and plugins as the Runner’s middleware stack — six local before_*/after_* callbacks for a single agent’s stages, and a BasePlugin registered on the App for global, cross-cutting hooks that run before agent callbacks and win by returning a value — and you get real pipeline control (skip a model call with a cached LlmResponse, block a tool with a dict, rewrite every event in on_event_callback) as long as you return None (never {}) to let the default flow continue, give each plugin a unique name, and reserve error handling for on_*_error_callback.