after_tool_callback not triggering for VertexAiSearchTool in Google ADK
** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.
Describe the bug The after_tool_callback function configured for an LlmAgent does not trigger when the agent utilizes a VertexAiSearchTool. This prevents custom logic from being executed post-tool usage.
To Reproduce Steps to reproduce the behavior:
- Install the Google ADK and necessary dependencies.
- Configure a VertexAiSearchTool with a valid data_store_id.
- Initialize an LlmAgent and pass the VertexAiSearchTool in its tools list.
- Define a callback function (e.g., capture_after_tool_callback) and assign it to the after_tool_callback parameter of the LlmAgent.
- Run a query through the LlmAgent that would typically trigger the VertexAiSearchTool.
- Observe that the capture_after_tool_callback function is not executed.
Expected behavior The after_tool_callback function (e.g., capture_after_tool_callback) should be triggered immediately after the VertexAiSearchTool successfully executes and returns its results. This allows for post-processing, logging, or state updates related to the tool's usage.
Screenshots N/A (This is a functional bug, not a UI/visual bug)
Desktop (please complete the following information):
- OS: Windows
- Python version(python -V): 3.11
- ADK version(pip show google-adk): Github Current Main version
Additional context sample tool def capture_after_tool_callback( tool: BaseTool, args: Dict[str, Any], tool_context: ToolContext, tool_response: Dict ) -> Optional[Dict]: print(f"[Callback] After tool call for tool") agent_name = tool_context.agent_name tool_name = tool.name print(f"[Callback] After tool call for tool '{tool_name}' in agent '{agent_name}'") print(f"[Callback] Args used: {args}") print(f"[Callback] Original tool_response: {tool_response}") return None
Following up on this bug report, while investigating the after_tool_callback not triggering, I've also found that the before_tool_callback function is not being called at all either.
It appears that neither callback function (pre- or post-tool usage) is firing when an LlmAgent uses the VertexAiSearchTool. This completely prevents any custom logic from running before or after the tool's execution, making it difficult to track or control the agent's behavior.
The reproduction steps remain the same; you can easily confirm this by testing the before_tool_callback alongside. It might be good to add an example for before_tool_callback to the sample code too.
Hoping for a quick resolution on this! Thanks.
Experiencing the same issue when using the google_search built-in tool. Could this be affecting all built-in tools?
FYI after_model_callback seems to work as expected.
Also running into this with the vertex search
I'm trying to add after_tool_callback for my agent to format the response from the mcp tool. But the function is not triggering. It worked for few tests but after that the function is not evoked at all. I can't seem to pinpoint why it is happening. Does this happen only for local run ?
@raghul-velt
Having the same exact issue. I send back the result from the mcp server as stringified json and would like to format it before passing it on to the llm but the after tool callback never triggers. It works fine for other custom non-mcp tools, but mcp tools for whatever reason don't work....
Having same issue neither before_tool_callback or after_tool_callback is triggerd when VertexAiSearchTool is used as a tools for Agent. However before_agent_callback, after_agent_callback, before_model_callback & after_model_callback are working as expected.
Quick Update, using Gemini, I made these wrapper classes that you wrap around the original MCP Toolkit, and it works like a charm:
# in a file like 'utils/adk_wrappers.py'
from __future__ import annotations
from typing import Any, Callable, Coroutine, Optional, Dict
from google.adk.tools.base_tool import BaseTool, types
from google.adk.tools.tool_context import ToolContext
from google.adk.tools.mcp_tool.mcp_tool import MCPTool
# Define the signature for your callback for type hinting
AfterToolCallback = Callable[
[BaseTool, Dict[str, Any], ToolContext, Dict],
Coroutine[Any, Any, Optional[Dict]],
]
class MCPCallbackWrapperTool(BaseTool):
"""
A wrapper for an MCPTool that guarantees the after_tool_callback is executed.
"""
def __init__(
self,
mcp_tool: MCPTool,
after_tool_callback: Optional[AfterToolCallback] = None,
):
"""
Initializes the wrapper.
Args:
mcp_tool: The original MCPTool instance to wrap.
after_tool_callback: The async callback function to execute after the tool runs.
"""
# Copy essential properties from the original tool so the agent sees it as the same tool
super().__init__(
name=mcp_tool.name,
description=mcp_tool.description,
is_long_running=mcp_tool.is_long_running,
)
self._wrapped_tool = mcp_tool
self._after_tool_callback = after_tool_callback
def _get_declaration(self) -> Optional[types.FunctionDeclaration]:
"""Pass through to the original tool's declaration."""
return self._wrapped_tool._get_declaration()
async def run_async(
self, *, args: dict[str, Any], tool_context: ToolContext
) -> Any:
"""
Executes the wrapped tool and then triggers the after_tool_callback.
"""
# 1. Execute the actual wrapped MCP tool
tool_response = await self._wrapped_tool.run_async(
args=args, tool_context=tool_context
)
# 2. If an after_tool_callback is provided, execute it now
if self._after_tool_callback:
modified_response = await self._after_tool_callback(
tool=self, # Pass self, which has the correct name/description
args=args,
tool_context=tool_context,
tool_response=tool_response,
)
# If the callback returned a modified response, use it. Otherwise, use the original.
if modified_response is not None:
return modified_response
return tool_response
from typing import List, Union
from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.tools.mcp_tool.mcp_toolset import (
MCPToolset,
MCPTool,
StdioServerParameters,
)
from google.adk.tools.mcp_tool.mcp_session_manager import (
StdioConnectionParams,
SseConnectionParams,
StreamableHTTPConnectionParams,
)
class CallbackAwareMCPToolset(MCPToolset):
"""
An MCPToolset that automatically wraps its tools to ensure
after_tool_callbacks are fired.
"""
def __init__(
self,
*,
after_tool_callback: Optional[AfterToolCallback] = None,
connection_params: Union[
StdioServerParameters,
StdioConnectionParams,
SseConnectionParams,
StreamableHTTPConnectionParams,
],
**kwargs,
):
"""
Initializes the toolset and stores the callback.
Args:
after_tool_callback: The async callback to apply to all tools from this toolset.
connection_params: Connection parameters for the MCP server.
**kwargs: Other arguments to pass to the parent MCPToolset.
"""
super().__init__(connection_params=connection_params, **kwargs)
self._after_tool_callback = after_tool_callback
async def get_tools(
self,
readonly_context: Optional[ReadonlyContext] = None,
) -> List[BaseTool]:
"""
Retrieves tools from the parent class and wraps them with MCPCallbackWrapperTool.
"""
# 1. Get the original MCPTool instances from the base class
original_mcp_tools: List[MCPTool] = await super().get_tools(
readonly_context=readonly_context
)
if not self._after_tool_callback:
return original_mcp_tools
# 2. Wrap each tool with our custom wrapper
wrapped_tools: List[BaseTool] = [
MCPCallbackWrapperTool(
mcp_tool=tool, after_tool_callback=self._after_tool_callback
)
for tool in original_mcp_tools
]
return wrapped_tools
Can confirm that neither of the tool callbacks are triggered when using VertexAiRagRetrieval either.
@Pipasgonzalez thanks for your workaround! I can't seem to make it work though. Could you provide an example the actual mcptoolset and how you initialize it? I tried to use your wrapper class and added a custom after tool callback but it's never invoked
@vitalii-within-co ADK has since fixed the bug. I use the standard MCP Toolset from "from google.adk.tools.mcp_tool import MCPToolset" with the StreamableHTTP Parameters. During Agent instantiation, I pass on my after tool callback and it works well thus far, except for the annoying Google ADK Warnings in the terimnal. My after tool callback starts like this.
async def after_tool_callback( tool: BaseTool, args: Dict[str, Any], tool_context: ToolContext, tool_response: Dict ):
Root Cause
The after_tool_callback and before_tool_callback functions do not trigger for VertexAiSearchTool (and other built-in model tools like GoogleSearchTool and VertexAiRagRetrieval) because these tools execute server-side within the LLM model rather than client-side.
How Built-in Model Tools Work
- These tools inject themselves into the LLM request config via
process_llm_request()(vertex_ai_search_tool.py:91-117) - The LLM model executes them internally and incorporates results directly into its response
- They do not implement
run_async()for client-side execution (it raisesNotImplementedError)
As documented in google_search_tool.py:32-35:
"This tool operates internally within the model and does not require or perform local code execution."
Why Callbacks Don't Fire
Tool callbacks are invoked in functions.py:311-380 during the execution of _execute_single_function_call_async(). This function calls:
before_tool_callbackbefore executing the tooltool.run_async()to execute the toolafter_tool_callbackafter execution completes
Since built-in model tools execute server-side and never call run_async(), the callback code path is never reached.
Affected Tools
- VertexAiSearchTool - always server-side execution
- GoogleSearchTool - always server-side execution
- VertexAiRagRetrieval - always server-side execution
Note: after_model_callback and before_model_callback work correctly because they're invoked at different points in the flow and don't depend on client-side tool execution.
Regarding MCP Tools
@Pipasgonzalez @raghul-velt @vitalii-within-co - MCP tools should trigger callbacks correctly as they implement proper client-side execution via run_async() (mcp_tool.py:152-183).
If you're still experiencing issues with MCP tool callbacks not triggering, please open a separate issue with:
- A minimal reproducible example
- Your ADK version (
pip show google-adk) - Details about your MCP server setup
This will help isolate whether there's a different underlying issue specific to MCP tools.
Closing this issue as the root cause has been identified and documented. The behavior is by design: built-in model tools (VertexAiSearchTool, GoogleSearchTool, VertexAiRagRetrieval) execute server-side within the LLM and do not trigger client-side tool callbacks.