Wrapping Gemini tool calls in state machines, lifecycle callbacks, and byte-capped SQL sandboxes
Mayuk Jain · Forward Deployed AI Software Engineer · November 2026
Building a customer-support or billing agent with Gemini and the open-source Agent Development Kit (ADK) takes minutes, yet shipping that agent into regulated production requires hard runtime guarantees [1]. A single hallucinated tool argument or indirect prompt injection cannot be allowed to trigger an unverified refund, scan terabytes in BigQuery, or leak sensitive records. In this guide, you will learn how to wrap non-deterministic LLM reasoning inside deterministic Python controls using ADK lifecycle callbacks, BigQuery QueryJobConfig dry-run caps, Model Armor, and Vertex AI Agent Engine [1][2][3][4].
Note: The architectural patterns and reference code shared here reflect my personal field-engineering practices on Google Cloud.
Why prompt rules alone fail in production agent loops
When an agent misbehaves in staging, the tempting fix is adding another ALL-CAPS rule to the system prompt, setting temperature=0, and wrapping API calls in a retry decorator.
In production, all three shortcuts break down quickly:
- Prompts guide probabilities rather than enforcing contracts: Even a tiny per-step error rate compounds across a ten-step troubleshooting workflow. One bad intermediate tool call pollutes the session history for every turn that follows.
- Blind retries duplicate side effects: Retrying an ambiguous network timeout against a billing or ticketing API will double-execute the write unless your tool layer enforces deterministic idempotency keys.
- Text-only filters miss confused-deputy tool abuse: Suppose a customer-support agent reads an inbound ticket containing a planted instruction to query another tenant’s billing rows. The text looks harmless in isolation, so safety settings on the prompt alone won’t stop an over-privileged tool from running.
Mapping deterministic controls across the Google Cloud agent stack
Reliable agent design splits responsibility cleanly in two. Let Gemini handle unstructured judgment: parsing messy customer tickets, summarizing logs, and proposing candidate tool arguments. Let deterministic code outside the model own workflow state, authorization, query byte caps, and side effects [2][5][6].
Here is how a free-roaming prototype compares to a production Google Cloud guardrail stack [1][2][3][4][6].
| System Layer | Unconstrained Agent Prototype | Deterministic Google Cloud Stack |
|---|---|---|
| Workflow Routing | LLM decides step order and when to stop | ADK Workflow Agents + Session.state stage tracking |
| Prompt & MCP Screening | Raw user and tool strings hit the model | Model Armor floor settings on Gemini & MCP traffic |
| Tool Authorization | Prompt instruction (“check identity first”) | ADK before_tool_callback checking user:role & stage |
| BigQuery Cost & Safety | Unbounded client.query(sql) execution |
Read-only SQL check + dry_run + maximum_bytes_billed |
| Write Idempotency | Blind retries risk duplicate payouts | Canonical SHA-256 idempotency_key deduplication |
| Managed Runtime | DIY container scripts with manual logs | Vertex AI Agent Engine + Cloud Logging & SCC alerts |
Step-by-step: Implementing four deterministic guardrails in Python
Let’s walk through a concrete customer-support scenario: a Billing & Refund Support Agent that looks up customer ledger entries in BigQuery (lookup_ledger) and issues refunds (send_refund) only after caller identity is verified (VERIFY_ID \\rightarrow ISSUE_REFUND).
Step 1: Own workflow order with ADK workflow agents and session state
When a single unconstrained agent owns both reasoning and routing, a clever prompt can coax it into calling send_refund before identity verification completes. In ADK Python, Workflow Agents provide deterministic control flow without relying on the LLM to orchestrate step order, while Session.state stores transient workflow state in a key-value dictionary outside the prompt [6].
Keys prefixed with user: (such as user:role) persist across sessions for that user within the same application, giving your callbacks a tamper-resistant place to read caller permissions and workflow stage [5].
Step 2: Gate tool calls with ADK Before_Tool_Callback and idempotency keys
ADK hooks into agent execution through six lifecycle checkpoints across agent, model, and tool pairs (before_agent_callback, before_model_callback, before_tool_callback, and their after_* counterparts) [2][5]. Every callback follows one clean return-value contract:
- Return
None: ADK proceeds with normal tool execution (including any in-place edits you made to the mutableargsdictionary) [2][5]. - Return a
dict: ADK skips executing the actual tool function and hands your returneddictstraight back to the LLM as the tool response [2].
That single rule lets you turn before_tool_callback into an operating-system-style syscall gate [2][5]. Notice that ADK invokes callbacks by keyword, so parameter names (tool, args, tool_context) must match the expected signature [5][6].
Below is a self-contained Python 3.11+ guardrail module you can run locally to verify every branch before attaching before_tool_callback=enforce_tool_guardrail to an ADK LlmAgent:
# Prerequisites: Python 3.11+ (runs standalone for unit tests; `pip install google-adk` in your agent project)
from typing import Any, Optional, Protocol
import hashlib
import json
import re
ALLOWED_TOOLS_BY_STAGE: dict[str, set[str]] = {
"VERIFY_ID": {"lookup_ledger"},
"ISSUE_REFUND": {"lookup_ledger", "send_refund"},
}
FORBIDDEN_SQL = re.compile(
r"(;|--|\b(INSERT|UPDATE|DELETE|DROP|ALTER|TRUNCATE|GRANT|EXEC)\b)",
re.IGNORECASE,
)
class ToolLike(Protocol):
name: str
class ContextLike(Protocol):
state: dict[str, Any]
def make_idempotency_key(session_id: str, stage: str, tool_name: str, args: dict[str, Any]) -> str:
payload = json.dumps(
{"session": session_id, "stage": stage, "tool": tool_name, "args": args},
sort_keys=True,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
def enforce_tool_guardrail(
tool: ToolLike,
args: dict[str, Any],
tool_context: ContextLike,
) -> Optional[dict[str, Any]]:
"""ADK before_tool_callback: return None to allow execution, or a dict to block/skip."""
state = tool_context.state
stage = state.get("workflow_stage", "VERIFY_ID")
# 1. Per-stage capability allowlist (makes illegal state transitions unreachable)
if tool.name not in ALLOWED_TOOLS_BY_STAGE.get(stage, set()):
return {"status": "HALT", "reason": f"Tool '{tool.name}' is not permitted in stage '{stage}'."}
# 2. Role check + high-value human escalation for destructive/payout tools
if tool.name == "send_refund":
if state.get("user:role") != "billing_specialist":
return {"status": "HALT", "reason": "Caller lacks 'billing_specialist' permission."}
if float(args.get("amount", 0)) > 250.0 and not state.get("human_approved", False):
return {"status": "PAUSE", "reason": "Refunds above $250 require human supervisor sign-off."}
# 3. Read-only, single-statement SQL check before hitting BigQuery
sql = str(args.get("sql", "")).strip()
if sql and (not sql.upper().startswith("SELECT") or FORBIDDEN_SQL.search(sql)):
return {"status": "HALT", "reason": "Blocked non-SELECT or multi-statement SQL query."}
# 4. Call-budget circuit breaker across the current session trajectory
calls_used = int(state.get("tool_calls_used", 0))
if calls_used >= 10:
return {"status": "HALT", "reason": "Session tool-call circuit breaker tripped (limit: 10)."}
state["tool_calls_used"] = calls_used + 1
# 5. Deduplicate state-mutating calls with a deterministic SHA-256 idempotency key
if tool.name == "send_refund":
idem_key = make_idempotency_key(str(state.get("session_id", "s0")), stage, tool.name, args)
committed: set[str] = state.setdefault("committed_keys", set())
if idem_key in committed:
return {"status": "CACHED", "idempotency_key": idem_key, "note": "Duplicate retry skipped safely."}
args["idempotency_key"] = idem_key # Mutate args in-place for downstream substrate
committed.add(idem_key)
return None # Proceed with actual ADK tool execution
if __name__ == "__main__":
class _MockTool:
def __init__(self, name: str): self.name = name
class _MockCtx:
def __init__(self, state: dict[str, Any]): self.state = state
# Unverified session cannot call send_refund
ctx = _MockCtx({"workflow_stage": "VERIFY_ID", "user:role": "billing_specialist", "session_id": "s1"})
assert enforce_tool_guardrail(_MockTool("send_refund"), {"amount": 40}, ctx)["status"] == "HALT"
# Stacked SQL injection is blocked before reaching BigQuery
assert enforce_tool_guardrail(_MockTool("lookup_ledger"), {"sql": "SELECT 1; DROP TABLE t"}, ctx)["status"] == "HALT"
# Valid read-only SELECT returns None (allowing tool execution)
assert enforce_tool_guardrail(_MockTool("lookup_ledger"), {"sql": "SELECT bal FROM ledger WHERE id = 7"}, ctx) is None
# High-value refund pauses for human approval; approved <= $250 runs once and deduplicates retries
ctx.state["workflow_stage"] = "ISSUE_REFUND"
assert enforce_tool_guardrail(_MockTool("send_refund"), {"amount": 500}, ctx)["status"] == "PAUSE"
assert enforce_tool_guardrail(_MockTool("send_refund"), {"amount": 50, "acct": 7}, ctx) is None
assert enforce_tool_guardrail(_MockTool("send_refund"), {"acct": 7, "amount": 50}, ctx)["status"] == "CACHED"
Step 3: Cap warehouse blast radius with BigQuery dry runs and byte limits
Syntax checks stop DROP TABLE statements, yet a valid SELECT across an unpartitioned multi-terabyte dataset can still rack up unexpected query costs. When exposing BigQuery to an agent (either via a custom Python FunctionTool or managed MCP connectors), enforce two native QueryJobConfig guardrails from google-cloud-bigquery [3][7]:
- Pre-flight
dry_run=Trueestimation: Inspecttotal_bytes_processedwithout running the query [3][7]. - Hard
maximum_bytes_billedandjob_timeout_mscaps:maximum_bytes_billedfails the query before execution if estimated bytes exceed your budget, giving you cheap insurance on any agent-facing endpoint [3][7].
# Prerequisites: pip install google-cloud-bigquery>=3.47.0
from google.cloud import bigquery
ONE_GIB = 1024 ** 3
def run_guarded_bigquery_select(client: bigquery.Client, sql: str, max_bytes: int = ONE_GIB) -> list[dict]:
# Step A: Zero-execution dry run to inspect scan volume up front
dry_cfg = bigquery.QueryJobConfig(dry_run=True, use_query_cache=False)
estimate_job = client.query(sql, job_config=dry_cfg)
if estimate_job.total_bytes_processed > max_bytes:
raise ValueError(
f"Query blocked: estimated {estimate_job.total_bytes_processed} bytes exceeds {max_bytes} cap."
)
# Step B: Execute with hard server-side billing ceiling and 15-second timeout
exec_cfg = bigquery.QueryJobConfig(
maximum_bytes_billed=max_bytes,
job_timeout_ms=15_000,
)
return [dict(row) for row in client.query(sql, job_config=exec_cfg).result()]
Step 4: Screen prompts, responses, and MCP traffic with Model Armor
Deterministic Python callbacks guard what tools do; Model Armor complements them by screening what enters and leaves the model across trust boundaries [4][8]. Rather than writing brittle regexes for prompt injection or PII masking, you can deploy Model Armor inline in three practical places:
- Gemini API Templates & Floor Settings: Configure reusable Model Armor templates for application-specific thresholds alongside baseline floor settings to screen
generateContentprompts and responses against prompt injection, jailbreaks, malicious URLs, and sensitive data leaks (backed by Google Cloud Sensitive Data Protection), logging sanitization events to Cloud Logging [4][8]. - MCP Tool Server Sanitization: Configure Model Armor to sanitize Model Context Protocol (MCP) tool calls and responses using floor settings, stopping indirect prompt injections hidden inside external ticket bodies or documents before the model acts on them [4].
- Gateway & Centralized Security Ops: Enforce policies across multiple agents via Agent Gateway, Apigee, or load-balancer Service Extensions, routing violation findings straight into Security Command Center [4].
Choosing how much guardrail overhead your use case needs
Not every internal prototype needs human-approval queues and multi-stage state machines. Use the 2×2 matrix below to match your Google Cloud controls to input ambiguity and side-effect blast radius.
- Structured Input + Low Blast Radius (Bottom-Left): Skip the LLM and use deterministic Python on Cloud Run or scheduled SQL.
- Messy Input + Low Blast Radius (Bottom-Right): Pair a single bounded Gemini call with typed output schemas and Model Armor floor settings for read-only triage or summarization [4][8].
- Structured Input + High Blast Radius (Top-Left): Keep generative models out of the critical compliance path; use explicit state machines, least-privilege IAM, and audit logs.
- Messy Input + High Blast Radius (Top-Right): Deploy the full stack on Vertex AI Agent Engine: ADK Workflow Agents,
before_tool_callbackallowlists and SHA-256 idempotency, BigQuerymaximum_bytes_billedcaps, and Model Armor MCP screening [1][2][3][4].
Next steps and further reading
When you separate probabilistic Gemini reasoning from deterministic ADK, BigQuery, and Model Armor enforcement, bad model outputs become routine HALT dictionary responses in Cloud Logging rather than production incidents [1][2][4].
To try this architecture in your own Google Cloud project:
- Start locally with ADK: Wire
enforce_tool_guardrailinto anLlmAgent(before_tool_callback=...)and run offline unit tests against malformed SQL, unauthorized roles, and duplicate retries before connecting live credentials [2][6]. - Deploy to Vertex AI Agent Engine: Move from local CLI runs to a managed runtime with built-in session management, evaluation, and scaling controls [1].
- Turn on Model Armor & Cloud Logging: Enable floor settings on your agent and MCP endpoints so prompt-injection attempts and sensitive-data blocks surface automatically in Security Command Center [4][8].
How are you guarding tool-calling agents on Vertex AI today? Drop a question or share the trickiest edge case your before_tool_callback caught in the comments below, and I’ll be glad to compare implementations!
Sources
[1] Build and manage multi-system agents with Vertex AI | Google Cloud Blog
[2] Callbacks: Observe, Customize, and Control Agent Behavior - Agent Development Kit (ADK)
[3] Class QueryJobConfig (3.47.0) | Python client libraries - Google Cloud Documentation
[4] Overview | Model Armor - Google Cloud Documentation
[5] Google ADK - Callbacks | Ravikanth Chaganti
[6] adk-python.md - google/agents-cli - GitHub


