Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 5 min read

Google Now Blocks an AI Agent's Tool Call Before It Runs. Here Is the Pattern in 44 Lines of Python

Help Net Security reported on November 23 that Google has put "semantic governance policies" into preview on its Gemini platform. The idea is simple and overdue: every tool call an agent proposes is checked before it run

Google Now Blocks an AI Agent's Tool Call Before It Runs. Here Is the Pattern in 44 Lines of Python

Cover

Help Net Security reported on November 23 that Google has put "semantic governance policies" into preview on its Gemini platform. The idea is simple and overdue: every tool call an agent proposes is checked before it runs. If it does not match what the user asked for, or it breaks a company rule written in plain language, the call is blocked and the agent gets a denial instead.

Google's own example is a finance agent with one rule: unreleased quarterly results may only be emailed to addresses at the company's domain before the earnings release. When the agent tried to email results to an outside investor, the call was denied. When hidden text in a document tried to make the agent delete drafts, the intent check denied that too, because deleting drafts had nothing to do with the user's request.

You do not need a specific cloud to adopt this pattern. Here is the core of it in 44 lines of Python, with both checks, an audit log and a dry-run mode.

Where the gate sits

user request --> agent (model) --> proposed tool call
                                        |
                                        v
                                   POLICY GATE  <-- company rules + user intent
                                        |
                        allow ----------+---------- deny
                          |                           |
                       run tool               denial message back to agent
                          |                           |
                          +-------- audit log --------+

The important word is before. Output filters catch bad text after the fact. A gate in front of the tool stops the email from being sent at all.

The code

import json, re

# Plain-language company rules, compiled to checks a reviewer can read.
POLICIES = [
    ("Unreleased results go only to our own domain",
     lambda call, req: call["tool"] != "send_email" or "q3 results" not in call["args"]["body"].lower()
                       or call["args"]["to"].endswith("@example.com")),
    ("Agents never delete data",
     lambda call, req: not call["tool"].startswith("delete_")),
]
# Which tools each kind of user request can justify (the "intent" check).
INTENT_TOOLS = {
    "email": {"send_email", "search_docs"},
    "report": {"search_docs", "read_sheet"},
}

def intent_of(request: str) -> str:
    return "email" if re.search(r"\b(email|send|reply)\b", request, re.I) else "report"

def gate(call: dict, request: str, dry_run: bool = False) -> dict:
    """Runs BEFORE the tool. Returns allow/deny plus every reason, and logs the verdict."""
    reasons = [name for name, ok in POLICIES if not ok(call, request)]
    if call["tool"] not in INTENT_TOOLS[intent_of(request)]:
        reasons.append(f"'{call['tool']}' does not serve the request")
    verdict = {"allow": dry_run or not reasons, "reasons": reasons, "dry_run": dry_run}
    print(json.dumps({"tool": call["tool"], **verdict}))         # audit log line
    return verdict

def run_tool(call, request, dry_run=False):
    v = gate(call, request, dry_run)
    return f"ran {call['tool']}" if v["allow"] else "DENIED: " + "; ".join(v["reasons"])

if __name__ == "__main__":
    req = "Email the Q3 results summary to the finance team"
    cases = [
        {"tool": "send_email", "args": {"to": "[email protected]", "body": "Q3 results attached"}},
        {"tool": "send_email", "args": {"to": "[email protected]", "body": "Q3 results attached"}},
        {"tool": "delete_drafts", "args": {}},          # injected by hidden text in a document
        {"tool": "search_docs", "args": {"q": "Q3"}},
    ]
    for c in cases:
        print("   ->", run_tool(c, req))
    print("\ndry run (log only, nothing blocked):")
    print("   ->", run_tool(cases[1], req, dry_run=True))

Running it

$ python gate.py
{"tool": "send_email", "allow": true, "reasons": [], "dry_run": false}
   -> ran send_email
{"tool": "send_email", "allow": false, "reasons": ["Unreleased results go only to our own domain"], "dry_run": false}
   -> DENIED: Unreleased results go only to our own domain
{"tool": "delete_drafts", "allow": false, "reasons": ["Agents never delete data", "'delete_drafts' does not serve the request"], "dry_run": false}
   -> DENIED: Agents never delete data; 'delete_drafts' does not serve the request
{"tool": "search_docs", "allow": true, "reasons": [], "dry_run": false}
   -> ran search_docs

dry run (log only, nothing blocked):
{"tool": "send_email", "allow": true, "reasons": ["Unreleased results go only to our own domain"], "dry_run": true}
   -> ran send_email

Four proposed calls for one request ("Email the Q3 results summary to the finance team"):

  • Email to the CFO at the company domain: allowed.
  • Email to an outside investor: denied by the company rule.
  • Delete drafts, injected by hidden text: denied twice, by the "never delete" rule and by the intent check.
  • Search docs: allowed, because searching serves an email request.

In dry-run mode the risky email is allowed but the log still records the rule it broke. That is how you roll a gate out without breaking a working agent: watch what it would have blocked for a week, fix false positives, then enforce.

Two checks, two jobs

Company rules encode things that are always true, whatever the user says: no unreleased results outside the company, no deletes, no refunds above a limit. Google lets compliance teams write these in plain language and has a model judge them. Mine are code. Both have a place.

The intent check asks a different question: does this call serve what the user actually asked? It is the main defence against prompt injection, because injected instructions almost always ask for something unrelated to the user's request (delete, forward, export). My version maps request types to allowed tools. Google uses a model to judge intent, which is more flexible.

Rules in code or judged by a model?

Google's documentation is candid that an LLM judge is probabilistic and its verdicts may vary, which is why it recommends dry-run mode before enforcing. My recommendation:

  1. Hard rules in code for anything that must never happen: money limits, deletes, external recipients, data that cannot leave.
  2. A model judge for fuzzy rules that are hard to write as code ("don't commit to delivery dates on behalf of sales").
  3. Deny by default when the judge is unsure or times out.
  4. Log every verdict with the reason. The log is how you find false positives and how you prove to an auditor that the rule was enforced.

Production checklist

  • Put the gate outside the agent process, at a gateway or proxy, so a confused agent cannot skip it.
  • Give the agent the denial reason so it can recover ("I can't send this externally, should I send it to the finance team instead?").
  • Version your policies and test them like code, with allowed and denied examples for every rule.
  • Track deny rates per rule. A rule that never fires may be wrong, and one that fires constantly is probably too strict.

The model deciding what to do is the exciting part of an agent. The gate deciding what it is allowed to do is the part that lets you put it in front of real customers and real data.

If you are building agents that touch email, money or customer data, that is what we do at Axionry, an AI product development studio. We ship in weeks, with guardrails like this built in.

Source

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.