Skip to content
Blog

Dynamic Tool Registration: Adding and Removing Tools Mid-Session

How ADK resolves an agent's tools per invocation, and the four ways to change the tool set at runtime: toolsets, list mutation, callback gating, and sub-agent routing.

Published on • November 28, 2026

AI Assistant

A static tools=[...] list assumes the agent’s abilities are fixed at import time. Real deployments disagree: a support agent should only expose issue_refund once the caller’s entitlement says so, a plugin system ships tools nobody has installed yet, and a disabled integration must disappear from the model’s view without a redeploy. So the question is not whether ADK can change the tool set — it is at which moment a change takes effect, and what happens to sessions sharing the same agent instance.

This tutorial covers how ADK resolves tools per invocation, the four practical mechanisms for changing the set at runtime, when each one takes effect, and the concurrency traps of mutating an agent that many sessions share.

How tools are actually resolved

Your tools=[...] list is not what the model receives verbatim. On each run the agent resolves its entries — plain callables, BaseTool instances, or whole BaseToolsets — through its canonical tool resolution, and the result is cached on the InvocationContext for that invocation. Three consequences follow:

  • Changes land between invocations, not inside one. The resolved list is cached per invocation, so mid-turn edits are invisible to the model request already in flight.
  • Toolsets are re-consulted with context. A toolset receives a read-only context (invocation, session state) every time it is asked for its tools, so the mechanism for per-session capabilities is a toolset that answers differently per caller.
  • A failing toolset degrades instead of crashing. If listing raises, the agent runs without that toolset’s tools — which is convenient for availability and dangerous if you assumed failure would be loud.

Toolsets: the supported dynamic path

BaseToolset is the abstraction built for this. You implement async def get_tools(self, readonly_context=None) and return whatever the current context allows:

from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.tools import FunctionTool
from google.adk.tools.base_toolset import BaseToolset

class EntitlementToolset(BaseToolset):
    """Exposes only the tools this tenant has paid for."""

    def __init__(self, registry: dict[str, list[str]]):
        super().__init__()
        self._registry = registry          # plan -> tool names

    async def get_tools(self, readonly_context: ReadonlyContext | None = None) -> list:
        state = readonly_context.state if readonly_context else {}
        plan = state.get('user:plan', 'free')
        names = self._registry.get(plan, [])
        return [make_tool(n) for n in names]      # fresh FunctionTool per call

agent = Agent(name='helper', model='gemini-3.8-flash', tools=[EntitlementToolset(REGISTRY)])

Two constructor options matter. tool_filter accepts a predicate f(tool, readonly_context) -> bool (or a list of names) to filter what the toolset yields, and tool_name_prefix namespaces the exposed names. disable_invocation_cache=True turns off the per-invocation cache and re-lists before every model request — that is the opt-in for tool sets that must change within a single invocation.

Mutating the agent’s list

The simplest hack — agent.tools.append(my_tool) between runs — works for the same reason toolsets do: resolution happens at run time. It is also the riskiest, because the agent object is typically shared across every session the Runner serves. Your “temporary” addition is global, unsynchronized, and affects in-flight behavior the next time any session resolves tools. If you go this route, treat it as a process-wide reconfiguration with a lock around it, not as a per-user toggle.

Gating instead of registering

Sometimes you do not need to hide a tool — you need it to refuse. A before_tool_callback runs after the model has emitted the call but before the tool executes, and returning a dictionary skips the tool entirely and feeds that dictionary back to the model as the result:

def enforce_entitlement(tool, args, tool_context) -> dict | None:
    if 'admin' in tool.name and not tool_context.state.get('user:is_admin'):
        return {'status': 'error',
                'error_message': f'{tool.name} requires an admin role; it is not available to this account.'}
    return None        # None lets the tool run — an empty dict would NOT

The trade-off is honest: the tool still appears in the declaration, so the model may try it, burn a call, and learn a boundary — while the schema itself never leaks a capability the tenant could have used. Prefer toolset-level filtering when availability is a secret; prefer callback gating when the tool exists for everyone but must not fire under certain conditions.

Routing as capability packs

Another axis: instead of swapping tools, swap who handles the request. Sub-agents reached through AgentTool or transfer_to_agent give each persona its own frozen tool list, and the root agent’s tool set never changes. This also sidesteps the one-tool-per-agent limitation for built-in tools, since each restriction is confined to its own agent.

ApproachGranularityEffectiveShared-agent riskBest for
Custom BaseToolsetper invocation (or per request with cache off)next model requestnone — context-awareentitlements, plugins, per-tenant tools
agent.tools mutationprocess-widenext invocationhigh — one agent, many sessionsfeature flags, admin toggles
before_tool_callback gateper callimmediately at executionnoneconditional refusal with feedback
Sub-agents / AgentToolper personawhen routing occursnonestable capability packs
Rebuild the Agentper app versionnext requestlow — new runner instancecold reconfiguration

Testing the declaration you advertise

Whatever mechanism you choose, assert the outcome: build the tool declaration for a given context and check the names the model would see. Schema regressions here are invisible until a tenant either loses a tool it needs or gains one it should not — the same discipline as asserting schemas in CI.

def test_paid_tools_are_hidden_for_free_plan():
    toolset = EntitlementToolset(REGISTRY)
    ctx = readonly_context_with({'user:plan': 'free'})
    names = [t.name for t in asyncio.run(toolset.get_tools(ctx))]
    assert 'lookup_order' in names
    assert 'issue_refund' not in names          # never reaches the model's declaration

Removing a tool is the same operation as adding one: the next invocation resolves the set again and the declaration no longer contains it. What you cannot do is retract it from a request already in flight — if a revoked tool is called in the turn that follows the revocation, the gate from the previous section is your second line of defense.

Takeaways

  • Tools are resolved from agent.tools at run time and cached per invocation — runtime changes apply from the next model request, not mid-turn.
  • BaseToolset.get_tools(readonly_context) with tool_filter, tool_name_prefix, and optional disable_invocation_cache is the supported way to vary tools by session, user, or tenant.
  • Mutating agent.tools is process-wide on a shared agent; treat it as reconfiguration, not personalization.
  • before_tool_callback returning a dict skips execution and returns that dict to the model; return None to let the tool run.
  • A toolset that raises is silently dropped — fail loudly where the capability is security-relevant.
  • Test the resolved declaration per context: a hidden tool must be absent from the schema, not merely refused at execution time.

Further reading