Chaitanya Bharath Gopu · IEEE Senior Member · ORCID 0009-0004-2511-3850

When an LLM agent can call query_db, the interesting security question is not "will the model behave?" It is "what is the last piece of code that can say no, and can I reason about it?"

That last piece of code should be boring. It should give the same answer for the same input every time, it should not call another model to decide, and when it is unsure it should refuse. This post walks through a small open-source implementation of that idea, mcp-guard-cli, and the three things I think are more useful than the tool itself: the design constraints, the measurements, and the bugs.

The problem

The Model Context Protocol standardises how an agent discovers and invokes tools. A tools/call request is just JSON-RPC:

{"jsonrpc":"2.0","id":1,"method":"tools/call", "params":{"name":"query_db","arguments":{"query":"SELECT * FROM v_customer_orders"}}} 

Whatever sits between the agent and the tool has three jobs: decide which tools may run at all, validate the arguments, and leave a record. Prompt-level guardrails ("never run destructive SQL") are advice to a probabilistic system. A gate that sits outside the model is a different kind of control, because you can test it.

Design constraints

I set four rules before writing code:

  1. Deterministic. The decision is a pure function of (policy, request bytes). No model call, no network, no clock.
  2. Default deny. Unknown tool, malformed JSON, missing tool name, missing SQL argument: all denied.
  3. Parse, don't pattern-match. SQL is judged on its syntax tree, not a regex. Regexes are how SELECT … ; DROP TABLE … and comment tricks get through.
  4. Auditable. Each decision carries the SHA-256 of the exact request bytes, so a log line can be tied to its input later.

The whole policy fits on one screen:

default_action: deny allowed_tools: [get_weather, query_db] blocked_tools: [exec_shell, drop_table] sql: query_db: argument: query allowed_relations: [v_customer_orders] 

And the core entry point is one function:

pub fn evaluate(policy: &Policy, raw: &[u8]) -> Decision 

How the SQL check works

The check uses sqlparser and its visitor API. The rules:

  • exactly one statement (stacked statements are rejected);
  • it must be a Query (SELECT, WITH, UNION…). INSERT, UPDATE, DELETE, DROP, COPY are rejected by statement kind;
  • a visitor walks every relation in the tree (subqueries, EXISTS, derived tables, joins, set-operation branches, CTE bodies) and each one must be on the allowlist, except names introduced by the query's own WITH clauses;
  • a visitor also inspects every function call and rejects a short list that touches files, shells, the clock or other hosts (pg_read_file, dblink, pg_sleep, xp_cmdshell, …), including schema-qualified forms like public.dblink(...).

Letting the library's visitor collect relations, instead of hand-walking the AST, matters. I started from a hand-written recursive walker and it was easy to miss a node type. Which brings me to the bugs.

Two bypasses I found by testing my own validator

After the first version passed 12 tests, including 17 adversarial SQL strings, I wrote a second round of probes aimed at valid read-only-looking statements that still have side effects:

SELECT * INTO newtab FROM v_customer_orders => allowed (!) SELECT * FROM v_customer_orders FOR UPDATE => allowed (!) 

Both parse as an ordinary Query. SELECT … INTO creates a table in PostgreSQL-family dialects. FOR UPDATE/FOR SHARE takes row locks, which is a denial-of-service lever on a busy table. Neither touches a non-allowlisted relation, so a validator that only answers "which tables does this read?" passes them.

The fix is to inspect those fields as part of "read-only":

fn side_effect_of(body: &SetExpr) -> Option<&'static str> { match body { SetExpr::Select(s) if s.into.is_some() => Some("SELECT ... INTO creates a table"), SetExpr::SetOperation { left, right, .. } => side_effect_of(left).or_else(|| side_effect_of(right)), SetExpr::Query(q) => side_effect_of(&q.body), _ => None, } } // and in the visitor: if !q.locks.is_empty() { /* reject */ } 

These are now regression tests, including an INTO hidden in the second branch of a UNION. I then ran the same two probes against a separate, hand-rolled validator I had written earlier for a different project, and it had exactly the same hole. The lesson I took: a read-only check needs a negative test suite for side effects, not just for access. "What can this read?" and "can this change anything?" are separate questions.

Measurements

All numbers are from cargo run --release --example bench on an Intel i9-13950HX (32 GB, Windows 11, rustc 1.97.1): 50,000 timed iterations after a 2,000-iteration warm-up, in-process.

case p50 p95 p99 tool allowlist only 1.0 µs 2.0 µs 2.6 µs allowed SELECT with filter + ORDER BY 12.6 µs 14.4 µs 21.4 µs blocked SQL (subquery escape) 7.1 µs 8.3 µs 15.0 µs 

As a separate process (spawn, load policy, evaluate, exit; 200 runs on the same machine) the median was 5.1 ms and p95 5.9 ms, almost all of it Windows process creation. The release binary is 4.1 MB.

So: microseconds if you embed it as a library, single-digit milliseconds if you shell out per request. I deliberately did not benchmark against a Python guard. A fair comparison needs the same policy semantics on both sides, and I have not built that yet. If you want one, the harness is a single file; run it on your hardware and publish your methodology.

What this does not do

  • It only protects what is routed through it. If a client can reach the tool server directly, the gate is decoration. Put it in the path (a proxy, or the client's tool-execution hook).
  • It checks syntax and referenced relations, not row-level security or query cost. A permitted SELECT can still be expensive. Keep database credentials least-privileged as well.
  • It parses PostgreSQL syntax. A statement that does not parse is denied, which is the right failure mode but will reject dialect-specific queries.
  • It does not detect prompt injection in natural language. It constrains what a tool call may do, whatever convinced the model to make it.

Try it

git clone https://github.com/gchaitanyabharath9/mcp-guard-cli && cd mcp-guard-cli cargo test echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"exec_shell","arguments":{}}}' \ | cargo run --release -- --policy policies/example.yaml # {"allow":false,"reason":"tool is on the blocklist", ...} exit code 2 

The repository has 13 integration tests, an Apache-2.0 license and a benchmark you can rerun. If you find a SQL string that gets through, please open an issue with the string; that is the most useful contribution.

Takeaways

  • Put the control that can say "no" outside the model, and make it a pure function so you can test it.
  • Judge SQL on its AST, and let the parser library's visitor enumerate relations and functions rather than hand-walking nodes.
  • Test side effects (INTO, locking clauses, dangerous functions) separately from access (which tables).
  • Report latency with percentiles, hardware and what was inside the timer. "Sub-millisecond" with no method is a claim, not a result.

Chaitanya Bharath Gopu is a Principal Enterprise Architect and AI systems researcher (19+ years in enterprise cloud modernization, FinOps and Rust/WASM systems) and an IEEE Senior Member. Code: github.com/gchaitanyabharath9 · Datasets: huggingface.co/CHAITANYABHARATHGOPU