AgentGate: Guardrail & MCP server built with Antigravity + Gemini

Hi everyone,

I built an open-source project called AgentGate using Antigravity and Gemini.

I don’t write code directly myself, so I used Gemini to put together the code and test suite around a specific idea: keeping autonomous agents from running dangerous operations (like unconstrained SQL queries, accidental Git pushes, or direct file changes) by requiring manual approval first.

What it does:

  • Validates tool arguments strictly with Pydantic schemas.
  • Stops direct execution and keeps actions in a pending approval state until confirmed.
  • Includes basic SQL parsing to catch accidental multi-statement queries.
  • Prevents background subprocesses from hanging.
  • Plugs into Google ADK via before_tool_callback and supports MCP.
  • Covered by 230 automated tests.

Repository: https://github.com/kmlyz/agentgate

I’d really appreciate your thoughts and feedback, especially from those building with Google ADK:
How do you usually handle human approval when agents need to perform sensitive tasks?

@kml The overall premise is solid–intercepting destructive mutations at the before_tool_callback layer is significantly more reliable than relying solely on system-prompt instructions.

Having engineered comparable deterministic gates across our open-source MCP toolchains, there are three practical failure modes you will likely encounter in production:

1. The Synthetic Self-Approval Vulnerability

In your runtime_callback_guardrail.py, returning {"status": "pending_approval", "proposal_id": "<uuid>"} back into the agent’s trajectory introduces a subtle loop: autonomous models in multi-turn execution will notice the returned proposal_id in their context window and attempt to call gate_approve or gate_execute to bypass the block.

To harden this, approval tokens must be cryptographically signed or delivered strictly out-of-band. The agent runtime itself should be physically stripped of approval tools:

# The model manifest must never contain approval primitives
if tool_name in {"gate_approve", "gate_execute"}:
    raise PermissionError("E_PERM: Approval endpoints are isolated out-of-band.")

2. Synchronous MCP Stdio Timeouts

If you hold a tool execution open over an active MCP stdio transport while waiting for human Slack confirmation, standard client RPC timeouts (often defaulting to 30-60s) will drop the pipe and sever the session.

A resilient pattern is asynchronous staging with state rehydration:

  • The intercepted tool returns immediately with a STAGED receipt and terminates the active tool turn.
  • The agent process suspends or transitions to an idle state until an out-of-band webhook resumes the session with an approved execution token, rather than blocking the transport event loop.

3. Granular Blast-Radius Tiering (Preventing Approval Fatigue)

Gating every single file write or mutation creates rapid approval fatigue, which leads operators to auto-approve without inspecting diffs. Differentiating your schema into three risk tiers helps maintain developer focus:

  • Tier 0 (Unconstrained): Idempotent reads, schema inspections, test runs, localised non-destructive edits within designated scratch/build paths.
  • Tier 1 (Light Gate / Reversible): Atomic file mutations with automatic pre-flight rollback checkpoints.
  • Tier 2 (Hard Gate / Mandatory Human Sign-Off): Destructive git operations (push -f, branch deletions), external network dispatches, and irreversible SQL schema alterations (DROP, ALTER, unconstrained DELETE).

We documented a formal reference architecture covering these deterministic states and synthetic approval immunity in our open-source RFC-003 specification; happy to share the Gist link and schema definitions if of interest to your pipeline and permitted by forum guidelines.

If you are looking to benchmark multi-statement SQL parsing, AST tokenisation (e.g. via sqlglot) is also worth considering over lexical scans to prevent comment-injection bypasses (SELECT 1; --\nDROP TABLE):

import sqlglot
from sqlglot.expressions import Drop, AlterTable

ast = sqlglot.parse_one(query)
if any(isinstance(node, (Drop, AlterTable)) for node, *_ in ast.walk()):
    raise SecurityError("Schema mutation requires manual operator sign-off.")

@dllhell Thank you for the detailed feedback, this is incredibly helpful.

The points about synthetic self-approval, stdio timeouts, and AST parsing make complete sense. I am reworking the architecture around these failure modes.

I would really appreciate it if you could share the RFC-003 specification and schema definitions! The Gist link would be a huge help as I refine the implementation.

Thanks again for your time and guidance.

@kml Glad the analysis was helpful.

Here is the complete reference blueprint and implementation suite for RFC-003:

Gist Blueprint: RFC-003: Deterministic Two-Stage Planning Gate & Adversarial Execution Guard (planning-guard v1.3.0) - Google Antigravity & MCP Ecosystem · GitHub

Key Components Relevant to Your Architecture:

  1. server.js (Asynchronous Tool Staging & MCP stdio Transport):

    • Illustrates how an MCP server stages destructive actions into an in-memory or file ledger and returns an immediate staged receipt.
    • Decouples the tool-call completion from the human review cycle so that stdio pipes never drop or trigger client RPC timeouts while awaiting operator sign-off.
  2. Antigravity_RFC_Two_Stage_Planning_and_Alignment.md (Synthetic Approval Immunity):

    • Details the architectural invariant treating any model-synthesised approval statements as void.
    • Enforces that execution tokens must originate strictly from external, out-of-band operator commands rather than strings injected into the LLM context window.
  3. Multi-Stage Lifecycle State Machine:

    • Implements the formal transition matrix: PHASE_1_EXPLORATION (read-only, zero disk/db writes) → PHASE_2_BLUEPRINT (atomic artefact creation) → PHASE_3_EXECUTION (gated mutations with rollback checkpoints).
// RFC-003 Execution Interception Invariant
if (session.state !== "PHASE_2_BLUEPRINT" || !userApproved) {
  throw new Error("E_GATE_LOCKED: Destructive mutation requires explicit out-of-band approval.");
}

As you refine the Pydantic schemas in AgentGate, let me know if you encounter any edge cases around transport rehydration or AST traversal. Happy to compare benchmark notes as the implementation evolves.

@dllhell Thank you for the RFC-003 reference and Gist blueprint.

Following your recommendations, I have updated the architecture to version 0.5.0:

RFC-003 Implementation:

  • Decoupled Tool Staging & Stdio Resilience: The runtime callback immediately returns a staged receipt (rcpt_<proposal_id>). The stdio transport completes deterministically without client RPC timeouts while execution is locked pending operator review.
  • Synthetic Approval Immunity: Agent tools and human operator approval endpoints are physically isolated across distinct transport boundaries.

Additional Hardening We Implemented:

  • AST Traversal (sqlglot): Replaced lexical regex checks with semantic AST parsing to block tautologies (1=1, OR true) and comment-based injection attacks.
  • TOCTOU Environmental Fingerprinting: Captures Git and filesystem state at staging time to ensure the environment hasn’t drifted before execution.
  • Replay Protection: Enforces single-use cryptographic tokens during approval to prevent re-execution of historical proposals.
  • 3-Tier Blast Radius Classification: Implemented operational risk tiering (Tier 0 read-only, Tier 1 reversible, Tier 2 hard gate) to prevent operator approval fatigue.
  • Verification: Test suite expanded from 230 to 281 passing tests.

Local Benchmark Observations:

  • In-Memory Proposal Staging & Digest: ~0.44 ms
  • Safe SQL AST Traversal (sqlglot): ~0.24 ms
  • Tautology AST Catch Latency (1=1): ~0.009 ms
  • Blast-Radius Tier Classification: ~0.0003 ms

Happy to compare these with your planning-guard benchmarks, especially around memory overhead across multi-turn sessions.

@kml

Passing tests while keeping AST traversal under 0.25 ms is impressive.

Regarding latency: in planning-guard, our in-memory status reads average ~0.22 ms round-trip, so your ~0.44 ms in AgentGate is right in line with expectations for synchronous stdio interception.

Memory Overhead in Multi-Turn Sessions: What We Actually Do

Our MCP server (planning-guard) avoids database engines entirely. Here is our actual setup:

1. In-Memory Map Cache + Local JSON File

In our server, we maintain an in-memory Map (workspaceCache = new Map()) that holds the active session state.

When state changes, we write it synchronously to a local JSON file partitioned by an SHA-256 hash of the workspace directory:
~/.gemini/antigravity/planning-guard/workspaces/workspace-<hash>.json

The state file is tiny (typically under 5 KB), and process RAM is essentially just the baseline Node.js runtime (~25 MB).

2. Compact Tool Responses

The real memory hazard in multi-turn sessions isn’t host RAM–it is the LLM context window.

If an MCP tool returns full state dumps, diffs, or execution histories on every turn, the conversation context balloons rapidly. In planning-guard, tools like planning_get_status default to a compact format (returning just ~300 characters showing the current stage and active step), keeping historical turn bloat to a minimum.

3. What We Observed with Gemini 4 Argon

In our own development sessions, we found this context discipline to be essential for model stability.

With Gemini 4 Argon having just launched to GA this week (13 October 2026), its deep reasoning capabilities mean it can spend several minutes in extended thinking on complex prompts before outputting tokens. In practice, when multi-turn sessions accumulate large tool outputs and context approaches 50k–80k+ tokens, this extended thinking frequently trips cloud proxy SSE streaming timeouts (EOF / interrupted stream) where proxies expect byte traffic within 60–120 seconds.

It is also worth noting an important boundary: while RFC-003 decoupled staging completely eliminates local MCP client stdio timeouts, it cannot prevent cloud-side proxy timeouts (EOF) if the conversation context is already bloated. Once Argon enters 2–4 minutes of deep reasoning on a heavy prompt, the cloud proxy drops the socket before any MCP tool is even evaluated. Compact MCP returns help delay context bloat, but they cannot cure upstream proxy timeouts until Google’s transport patches land.

This is primarily an infrastructure teething issue for the launch rollout. Google’s updated documentation recommends bumping client read timeouts to 15–20 minutes, and connection keep-alive patches for the desktop IDE and CLI are rolling out during this introductory launch window (which runs through 30 November 2026).

Until those transport-layer keep-alive updates fully land, keeping MCP tool returns lean and holding detailed logs on disk rather than in the chat history remains the most practical workbench mitigation to keep long multi-turn sessions rock-solid.

It is a simple flat-file approach, but it has kept our memory footprint flat across hundreds of turns without needing external services.

Addendum (Argon & RFC-003 Roadmap):
We are holding off on any RFC-003 protocol revisions until Google’s transport-layer keep-alives stabilise. In the meantime, we are actively testing session longevity workarounds locally and will share our findings here once the introductory rollout patches land.

@dllhell Thanks a lot for the detailed breakdown. What you shared was super helpful and I honestly learned a bunch from it, especially the context bloat and proxy timeout parts.

By the way, on the AST latency, I probably should’ve mentioned that my benchmark was just running on tiny demo test queries with simple statements, so that definitely kept the numbers unrealistically low.

Thanks again for the tips, I’ll definitely keep an eye out for your updates.