Skip to content
Blog

Database Querying Tools: Building Safe Read-Only SQL Agents

Layer a SQL tool so an ADK agent can explore data but never modify it: a read-only connection, a statement gate, an identifier allow-list, parameter binding, and a bounded result payload.

Published on • November 28, 2026

AI Assistant

A model that can write SQL is genuinely useful — and one prompt injection away from DROP TABLE. The system instruction is not the security boundary; the database credential your tool connects with is. If that connection can write, an attacker who controls any text reaching the model can write too.

This tutorial covers the defence layers that make a SQL tool safe in practice — connection privileges, statement gating, identifier allow-lists, parameter binding, and a bounded result shape — plus where ADK’s callbacks fit.

Threat model: four ways a SQL tool fails

  1. Destructive writes. DELETE, DROP, ALTER — caused by a hostile or hallucinated query.
  2. Privilege-broad reads. SELECT * FROM users returning password hashes the analyst never asked for.
  3. Syntax smuggling. Multi-statement payloads (;), PRAGMA, ATTACH, SELECT ... INTO — things that behave like reads but are not.
  4. Resource exhaustion. A cartesian join or a missing LIMIT that returns 400k rows into the model’s context and your bill.

Layer 1: the connection is read-only

Make writes impossible at the protocol level, not at the prompt level. With SQLite that means a read-only URI and the query_only pragma:

import sqlite3

def readonly_connection(path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
    conn.execute("PRAGMA query_only = ON")
    conn.row_factory = sqlite3.Row
    return conn

For server databases, use a dedicated role: a Postgres login granted SELECT on the specific schemas (or better, on views), plus SET default_transaction_read_only = on and a statement_timeout so a runaway query dies instead of pinning the connection pool. OWASP’s guidance is the same rule — accounts that only need read access get only read access, and views let you expose columns rather than whole tables.

Layer 2: gate the statement before the driver sees it

Parameter binding does not help if you never prepare the query. Validate the text first: single statement, read-only verb, no pragma/attach smuggling, and a forced row cap.

import re

WRITE_VERBS = {"insert", "update", "delete", "merge", "replace", "drop", "alter", "create",
               "truncate", "grant", "revoke", "attach", "detach", "pragma", "vacuum", "call"}

def gate_sql(sql: str, max_rows: int = 500) -> str:
    """Return a safe, bounded SELECT or raise ValueError."""
    cleaned = re.sub(r"--.*?$|/\*.*?\*/", " ", sql, flags=re.M | re.S).strip().rstrip(";")
    if ";" in cleaned:
        raise ValueError("Multiple statements are not allowed.")
    tokens = re.findall(r"[A-Za-z_][A-Za-z0-9_]*", cleaned.lower())
    if not tokens or tokens[0] not in {"select", "with"} or WRITE_VERBS.intersection(tokens):
        raise ValueError("Only read-only SELECT queries are allowed.")
    limit = re.search(r"\blimit\s+(\d+)", cleaned)
    if not limit:
        return f"{cleaned} LIMIT {max_rows}"
    return re.sub(r"\blimit\s+\d+", f"LIMIT {min(int(limit.group(1)), max_rows)}",
                  cleaned, count=1)

Token scanning is deliberately blunt: it blocks SELECT ... INTO, subquery tricks like WHERE id IN (SELECT ...) that carry writes, and comment-obfuscated keywords. It will occasionally reject a legitimate exotic query — that is the correct trade for an agent tool, and the error message tells the model to rephrase.

Layer 3: identifiers by allow-list, values by binding

Parameter markers bind data values, never table names, column names, or ASC/DESC — so dynamic structure has to come from fixed, application-owned mappings:

SORT_COLUMNS = {"created": "created_at", "total": "total_amount"}

def build_orders_query(sort_by: str, ascending: bool, limit: int) -> tuple[str, list]:
    column = SORT_COLUMNS[sort_by]            # KeyError -> rejected, not injected
    direction = "ASC" if ascending else "DESC"
    return (f"SELECT id, customer, state FROM orders ORDER BY {column} "
            f"{direction} LIMIT ?", [min(limit, 500)])

The ADK tool

With the layers in place the tool itself is thin, and the docstring tells the model exactly what it is allowed to ask for:

from google.adk.tools import ToolContext

def run_readonly_sql(sql: str, tool_context: ToolContext,
                     params: list[str] | None = None) -> dict:
    """Run a read-only SELECT against the analytics database.

    Args:
        sql (str): One SELECT or WITH ... SELECT. No semicolons, no DDL/DML;
            a LIMIT is added automatically (max 500 rows).
        params (list[str], optional): Values to bind to `?` placeholders.

    Returns:
        dict: status, columns, rows, row_count, truncated, summary — or
        {'status': 'error', 'error_message': str}.
    """
    try:
        query = gate_sql(sql)
    except ValueError as exc:
        return {"status": "error", "error_message": str(exc)}

    with readonly_connection("analytics.db") as conn:
        cursor = conn.execute(query, params or [])
        columns = [d[0] for d in cursor.description]
        rows = [dict(r) for r in cursor.fetchall()]

    tool_context.state["temp:last_sql"] = query
    return {"status": "success", "columns": columns, "rows": rows,
            "row_count": len(rows), "truncated": len(rows) >= 500,
            "summary": f"Read-only query returned {len(rows)} rows within the cap."}

Two details matter: the truncated flag lets the model say “there may be more” instead of pretending the set is complete, and the summary gives it a sentence to quote — the same contract described in function tool docstrings. Returning rows as a list of dicts also makes follow-up tools (aggregation, pagination) trivial; see tool output formatting.

Enforce policy outside the function too

The function is not the only place to check arguments. ADK’s before_tool_callback can reject a call before it runs — return a dict and the tool is skipped, with that dict used as the tool result instead. The after_tool_callback runs once the tool succeeds and can replace the payload, which is where column redaction belongs: iterate tool_response["rows"] and pop email, ssn, and anything else out of scope, then return the dict (returning None leaves the original untouched). Keep credentials, tenant IDs, and bindable values out of the model’s reach entirely — ADK’s MCP Toolbox integration, for instance, binds such parameters server-side and hides them from the model.

Defence in depth at a glance

LayerMechanismCatchesMisses
ConnectionRead-only role, mode=ro, query_only, statement_timeoutAny write, DDL, runaway queryReads of tables that should stay hidden
Statement gateSingle statement, verb allow-list, forced LIMITSmuggled writes, PRAGMA/ATTACH, row floodsLegitimate-but-expensive SELECTs
Identifier allow-listFixed table/column/sort mapsTable and column exfiltrationNothing about value inputs
Result shapingColumn caps, truncated, human-readable errorsContext flooding, confusion on failure—

Takeaways

  • Read-only is a privilege decision: connect with a role that physically cannot write, then add statement_timeout and views for column-level scope.
  • Gate SQL text before preparing it — single statement, read-only leading verb, blocked keyword set, and a clamped LIMIT on every query.
  • Parameters bind values only; table, column, and sort direction must come from an application-owned allow-list.
  • Return status, columns, rows, truncated, and a quotable summary; reject with a human-readable error_message the model can act on.
  • Use before_tool_callback for argument policy and after_tool_callback for output redaction — defence that survives a rewritten tool body.

Further reading