Skip to content
Blog

Tool Authorization and Permission Gates: Validating Caller Roles

Four places to enforce authorization in ADK — schema, in-tool policy, before_tool_callback, and plugins — plus identity choices and denial messages the model can act on.

Published on • November 28, 2026

AI Assistant

The model decides what to call; it must never decide whether the caller is allowed to. Any authorization check you phrase in an instruction is a suggestion a prompt injection can overwrite, while a check in Python executes regardless of what the model believes. That gap between “the model was told no” and “the code says no” is where agent authorization lives — and ADK gives you at least four distinct places to close it.

This tutorial covers the two identity models you must choose between, the four enforcement points with their trade-offs, a concrete before_tool_callback gate, why denial messages are a design surface, and where plugins fit.

Agent identity vs. user identity

Before any gate, decide whose credentials the tool acts with:

  • Agent-auth: the tool uses the agent’s own service identity. Simple, and you can scope it strictly — grant the service account read-only access to a bucket and no model decision can cause a write. But every user’s actions are attributed to the agent, so you must log who triggered what, and it only fits deployments where all users share one access level.
  • User-auth: the tool acts as the controlling human, typically through an OAuth token the frontend supplies. Actions are limited to what that user could do themselves, which caps the blast radius of a hijacked conversation — but delegated scopes are usually coarser than your app’s real permissions, so you still need in-app gates below.

Production systems usually combine both: a least-privilege agent identity for infrastructure, user tokens for user data, and in-tool policy for the fine grain.

Four enforcement points

GateWhereWhat it can seeCost of getting it wrong
Schema filteringtool registrationcontext at resolution timetool never advertised — safest, coarsest
In-tool guardrailinside the functionargs + ToolContextbug executes unauthorized action
before_tool_callbackaround every tool calltool, args, statedenial message confuses model
Runner-level pluginacross all agentsinputs, tool I/O, model outputlatency per call; policy drift

ADK’s own safety guidance ranks them as layers: design the tool so it can only express allowed actions, then validate arguments, then add screening — in-tool guardrails, callbacks, and plugins compose rather than compete.

The callback gate

A before_tool_callback receives the tool, the parsed arguments, and the tool context — everything needed to authorize the call before it happens. Returning a dictionary skips the tool and hands that dictionary to the model as the tool’s result:

from google.adk.tools import BaseTool, ToolContext

def authorize_tool(tool: BaseTool, args: dict, tool_context: ToolContext) -> dict | None:
    role = tool_context.state.get('user:role', 'viewer')
    required = TOOL_ROLES.get(tool.name)            # {'issue_refund': 'agent:finance', ...}

    if required and not allowed(role, required):
        return {
            'status': 'error',
            'error_message': f'{tool.name} requires {required}; current role is {role}.',
            'allowed_actions': actions_for(role),     # what the model may try instead
            'retryable': False,
        }
    user_arg = args.get('user_id')
    if user_arg and user_arg != tool_context.state.get('session_user_id'):
        return {'status': 'error',
                'error_message': 'user_id must match the signed-in user — do not supply it yourself.'}
    return None                                      # None lets the tool execute

agent = Agent(name='support', model='gemini-3.8-flash',
              instruction=..., tools=[issue_refund, lookup_order],
              before_tool_callback=authorize_tool)

Two footguns from ADK’s own docs: the framework compares the return value against None, so an empty {} counts as an override and blocks the tool; and with a list of callbacks only the final non-None value wins. Authorization checks are also the natural home for an on_tool_error_callback if a gate itself fails closed rather than open.

Policy belongs in context, not in the model

The security-relevant asymmetry: tool arguments come from the model (untrusted), while ToolContext is populated deterministically by your application (trusted). Read policy from the second place. The canonical shape is a query tool that only accepts SELECT statements against an allow-listed set of tables, with the table list pulled from session state rather than from anything the call supplied:

def run_query(sql: str, tool_context: ToolContext) -> dict:
    """Run a read-only analytics query.

    Args:
        sql (str): A single SELECT statement over the reporting schema.
    """
    policy = tool_context.state.get('query_tool_policy', {})
    tables = tables_referenced(sql)
    if not set(tables).issubset(set(policy.get('tables', []))):
        return {'status': 'error',
                'error_message': f'Query touches unauthorized tables. Allowed: {policy.get("tables", [])}'}
    if policy.get('select_only') and not sql.strip().upper().startswith('SELECT'):
        return {'status': 'error', 'error_message': 'Policy restricts queries to SELECT statements.'}
    ...

Because the policy arrives via state, the same tool object serves tenants with different permissions and the model has no way to widen the policy itself.

Denials are messages the model acts on

A blocked call is an error result, which lands in the model’s context and in the persisted session events. Write denials as repair instructions: which role is required, what the caller’s role is, and — crucially — the list of actions that are available, so the model pivots instead of retrying with a paraphrase. Set retryable: false when no amount of rewording helps. Log every denial with session, user, tool, and argument snapshot: an authorization denial is the one event your security review will ask for.

Plugins for policy across agents

Per-agent callbacks scale badly past a handful of agents — you end up pasting the same function everywhere. ADK’s plugin mechanism attaches once at the runner level and applies to every agent it serves, which is where cross-cutting policies belong: PII redaction before tool input leaves the process, prompt-injection screening via a cheap model as judge, or a hosted content inspection service. Keep agent-specific rules in callbacks; keep organizational rules in plugins.

Takeaways

  • Choose the identity first: agent-auth gives you infrastructure-level caps, user-auth caps blast radius to what the human could do anyway — layers work best together.
  • Enforce at four layers (schema, in-tool, callback, plugin); the earlier the tool is stopped, the less the model ever sees it.
  • before_tool_callback(tool, args, tool_context) returning a dict blocks execution and becomes the tool result; returning None proceeds, and {} accidentally blocks.
  • Read trusted policy from ToolContext/session state — never from model-supplied arguments.
  • Deny with a repairable message plus the allowed alternatives, set retryable, and log every denial for audit.
  • Callbacks scale per agent; move organization-wide policy into runner-level plugins so it cannot be forgotten in one agent.
  • Authorization gates fail closed: if the policy lookup itself errors, block the call rather than defaulting to allow.

Further reading