sqlguardllm
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
The SQL firewall for LLM apps.
Your model writes SQL. sqlguardllm makes sure it can only read what it's allowed to read: one read-only statement, allowlisted tables and columns, row-level filters per user, and a row limit, in any of the 32 dialects sqlglot speaks.
Status: alpha. 0.5.0a7 is on PyPI (pip install sqlguardllm, import sqlguardllm), with the rules of docs/DESIGN.md, optional complexity limits and a 148-case development corpus. The API may still change before 1.0; violation codes are stable. ⭐ Star the repo to follow along, and tell us what you think in Discussions.
Full documentation: https://jmmana.github.io/sqlguardllm/
Install
Python 3.10+: the engine itself, inside your process.
pip install --pre sqlguardllmNode.js / TypeScript 18+: runs the embedded engine (no Python, no server) or talks to sqlguardllm serve.
npm install sqlguardllm.NET 8 or 10: runs the embedded engine (no Python, no server) or talks to sqlguardllm serve.
dotnet add package SqlGuardLlm --prereleaseThe server is optional for Node.js and .NET: their packages carry the engine and run it locally (SqlGuard.local / SqlGuard.CreateLocalAsync). Run it, in another terminal (Python 3.10+), when several services share one policy or your platform has no embedded engine. No Docker image is published; the Dockerfile builds one if you need it.
uvx sqlguardllm serve --policy policy.json --port 8787 # or: pipx run sqlguardllm serve ...Step by step for each language, from install to a program and its exact output: Python · Node.js / TypeScript · .NET · which package to choose. The Node.js and .NET guides use the embedded engine: no Python and no server.
Related MCP server: Terminus
Try it: input, decision and returned SQL
Try it in your browser · Watch the 42-second video · Run the example · How the demos are made
The GIF above and the results below come from actual executions. check() returns a Python CheckResult; its main fields are shown here as JSON. The library validates and rewrites SQL; your application executes the returned SQL when ok is true.
pip install sqlguardllmfrom sqlguardllm import Guard, Policy
guard = Guard(Policy(
dialect="postgres",
tables={"invoices", "customers"},
hidden_columns={"customers.email"},
row_filters={"invoices": "tenant_id = {user.tenant_id}"},
max_rows=100,
), language="en")
context = {"user": {"tenant_id": 7}}
result = guard.check("SELECT id, total FROM invoices ORDER BY id", context)Allowed input: SELECT id, total FROM invoices ORDER BY id
{
"ok": true,
"sql": "SELECT id, total FROM (SELECT * FROM invoices WHERE tenant_id = 7) AS invoices ORDER BY id LIMIT 100",
"applied_filters": [
"invoices: tenant_id = 7"
],
"violations": []
}Rejected write hidden in a CTE:
WITH d AS (DELETE FROM invoices RETURNING *) SELECT * FROM d{
"ok": false,
"sql": null,
"violations": [
{
"code": "write_operation",
"message": "The query tries to change data or structure (DELETE)",
"detail": "DELETE"
}
]
}The accepted read runs on the synthetic demo fixture and returns [(1, 250), (3, 120)]. The other tenant's invoice (2, 999, 900) is absent. The denied statement never reaches the executor.
Another input | Actual outcome under the policy above |
|
|
| Rewritten with |
| Allowed: the text is a string literal |
A read of |
|
Execute result.sql, with a read-only database account, only after checking result.ok. The context must come from your authenticated session. Guard.enforce() provides the equivalent raise-on-rejection interface; Guard.explain() adds readable policy provenance.
For the complete captured outputs, run python examples/readme_demo.py. The checks use the PostgreSQL dialect; accepted portable reads execute on a fictional SQLite fixture. See the systems study and measured coverage for SQLite, DuckDB and PostgreSQL/WebAssembly execution results and its limitations.
Why
LLM apps that talk to databases (text-to-SQL, data agents, MCP database tools) all share the same risk: the model writes SQL, and someone will eventually make it write the wrong SQL. Through a prompt injection, a malicious row in your own data, or a plain hallucination.
The usual defense is a keyword blocklist. It fails in both directions:
SQL | Keyword blocklist ( | What it actually is |
| ❌ Blocks it | A harmless read with a string literal |
| ✅ Blocks it, by luck | A write hidden inside a CTE. A text match alone does not establish read-only semantics |
| ⚠️ Lets it through: it starts with | Creates a new table (SQL Server) |
| ⚠️ Lets it through | Reads personal data the model should never see |
sqlguardllm parses the statement into a syntax tree with sqlglot and decides on the tree, not on the text. Then it rewrites the query so it can only see the rows the current user is allowed to see.
What it guarantees
Rule | |
1️⃣ | One statement that is a query ( |
2️⃣ | Read-only across the whole tree: no |
3️⃣ | Allowlisted tables and hidden columns: CTE-aware; |
4️⃣ | Denied functions per dialect: file readers, sleeps, shells, network calls ( |
5️⃣ | Row-level filters: every occurrence of a table becomes a filtered derived table, with the user's values bound as escaped literals |
6️⃣ | Row limit applied or lowered, in the dialect's own syntax ( |
🔒 | Fails closed: if the SQL can't be parsed, or the user context is missing a value a filter needs, the answer is no |
Optional limits
Off by default; turn on what you need. They stop queries that are far more expensive than the question that produced them.
Policy option | What it does | Violation |
| Caps joins in the whole query, CTEs and subqueries included |
|
| Caps nesting of subqueries, derived tables and CTEs |
|
| Rejects |
|
| Every read of the table must filter on one of the columns, such as a date range on a big fact table |
|
| The model writes PostgreSQL; the rewritten SQL comes out for SQL Server, Oracle or any sqlglot dialect | — |
| The column can be selected but comes back masked: |
|
| The table can only be read through aggregates, and groups smaller than 5 rows never come back ( |
|
How it works
flowchart LR
LLM["LLM / agent<br/>writes SQL"] --> P{"Parse with<br/>sqlglot"}
P -- "can't parse" --> X["❌ Rejected<br/>with a reason"]
P --> S{"One read-only<br/>query?"}
S -- no --> X
S --> A{"Allowed tables,<br/>columns, functions?"}
A -- no --> X
A --> R["Inject row filters<br/>as derived tables"]
R --> L["Apply row limit"]
L --> G["Generate SQL<br/>in your dialect"]
G --> DB[("Your database<br/>read-only user")]What runs is the SQL regenerated from the validated tree, never the original string.
Row-level security, rewritten
Each occurrence of a filtered table is replaced by a derived table that keeps its alias, so the filter holds inside joins, subqueries and CTEs. Real sqlglot output for a user who can only see branches 1 and 2:
SELECT b.name, SUM(i.total)
FROM invoices i
JOIN branches b ON b.id = i.branch_id
GROUP BY b.nameSELECT b.name, SUM(i.total)
FROM (
SELECT * FROM invoices
WHERE branch_id IN (1, 2)
) AS i
JOIN branches AS b ON b.id = i.branch_id
GROUP BY b.name
LIMIT 1000Same idea on SQL Server, where the limit becomes TOP 500, or Oracle, where it becomes FETCH FIRST 100 ROWS ONLY. More examples in docs/DESIGN.md.
Attack gallery
What sqlglot 30.35 actually sees for each attempt, and what sqlguardllm does about it. Every row is a test case. The full list is in docs/ATTACK_GALLERY.md.
Dialect | Attempt | sqlglot sees | sqlguardllm |
postgres |
|
| ❌ |
tsql |
| 2 statements | ❌ |
tsql |
|
| ❌ |
postgres |
|
| ❌ |
mysql |
| parse error | ❌ |
sqlite |
|
| ❌ |
postgres |
| function | ❌ |
oracle |
| qualified function call | ❌ |
postgres |
| one | ✅ allowed |
postgres |
| one | ✅ allowed |
Found a way through? That's a vulnerability: please report it privately.
Where it fits
sqlguardllm is one layer, not the only one. Keep the others:
A read-only database user with access to only the tables the app needs. Non-negotiable.
sqlguardllm between the model and the database: shape, allowlists, row filters, limits.
Statement timeouts in the database, against expensive queries.
Audit logs of every SQL that ran and for whom.
What it does not do, and why, is in the threat model.
Works with your stack
sqlguardllm sits wherever your app executes the SQL the model wrote. Recipes with runnable, tested code: a generic execute() wrapper (DB-API and SQLAlchemy), LangChain, LlamaIndex, Vanna and MCP. See also docs/INTEGRATIONS.md.
For the policy.yaml examples, install pip install "sqlguardllm[yaml]".
The command-line tool is handy in CI and for trying policies. Exit code 0 means allowed (it prints the rewritten SQL), 1 rejected (it prints the violations) and 2 a usage or policy error:
sqlguardllm check --policy policy.yaml --context '{"user": {"branches": [1, 2]}}' \
"SELECT * FROM invoices"
echo "SELECT …" | sqlguardllm check --policy policy.yaml --format json -Policy files have a JSON Schema for autocompletion in VS Code and other editors. In CI, sqlguardllm test runs the queries your policy must allow or reject and sqlguardllm lint warns about policies that are valid but probably unsafe, such as a tenant_id column without a row filter.
MCP server: sqlguardllm mcp gives Claude Desktop, Cursor and VS Code a database tool that can't write, see hidden data or escape row filters; copy-paste setup in docs/MCP.md.
HTTP server: sqlguardllm serve exposes POST /v1/check and /v1/explain as a sidecar for any language; the Dockerfile builds an image (none is published yet). See docs/SERVER.md.
Other languages
One engine, many clients. The engine is Python because it is built on sqlglot, which only exists in Python, and three engines in three languages could disagree, which in a security library means a bypass. Other languages call the same engine through sqlguardllm serve, and every case of the attack corpus must get the same answer from Python, the server, the Node.js client and the .NET client (conformance).
Node.js / TypeScript:
npm install sqlguardllm(clients/node): zero dependencies, ESM and CJS, fails closed..NET:
dotnet add package SqlGuardLlm --prerelease(clients/dotnet), on NuGet from 0.5.0-alpha.2: net8.0 and net10.0, fails closed.Any other language: the HTTP API, the MCP server or the CLI.
Install steps for each language are in Install. The Node.js and .NET packages carry the engine for linux-x64, linux-arm64, macOS (x64, arm64) and win-x64, so they work with no Python and no server; elsewhere they use the remote mode.
Playground: try to break it
Open the playground: it runs sqlguardllm entirely in your browser with Pyodide and a demo SQLite database. Pick a role, type the nastiest SQL you can think of, and watch it get blocked or rewritten. No server, no sign-up; share any attempt with a link. Source in playground/.
Roadmap
Milestone | Scope |
Statement and read-only checks, allowlists, hidden columns, denied functions, row limit, adversarial corpus | |
Row filters as derived tables, policy files, CLI, dialect test matrix, docs site, PyPI release | |
Complexity limits, required filters, PII masking, aggregate-only tables (k-anonymity), exact schema from the database, policies per role, | |
A safe database tool for Claude Desktop, Cursor and any agent, with an optional cost guard | |
Integration recipes, browser playground, performance budget | |
One engine, many clients: server mode plus npm and NuGet clients |
Details in docs/ROADMAP.md.
Contributing
Contributions are very welcome, and some of the most valuable ones need no deep knowledge of the codebase:
Add attack cases to the adversarial corpus, especially for dialects you know well.
Extend the denied-function lists for your database.
Translate violation messages.
Challenge the design in Discussions before v0.1 freezes the API.
Start with CONTRIBUTING.md and the good first issues. This project follows a Code of Conduct.
Security
A bypass of sqlguardllm is a security vulnerability. Don't open a public issue: report it privately as described in SECURITY.md.
License
Apache-2.0 © 2026 Juan Castillo. sqlguardllm was born inside ChatIApp, an open-source chat that turns business questions into safe SQL.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Zero-trust SQL AST & MCP firewall enforcing tenant isolation, PII scrubbing, and schema allowlists.
Guard AI agents' PostgreSQL/MySQL access via MCP: SQL audit, auth, masking, write approval
AgentGuard — 20-tool AI safety MCP: policy preflight, risk scoring, audit logging, rate limits.
Real-time MCP & A2A prompt-injection, jailbreak, and tool-schema poisoning firewall for AI agents.
Related MCP Servers
- AlicenseAqualityCmaintenanceSecure MCP server for safe, read-only DB access by AI agents, with SQL guardrails, table allowlists, PII masking, and audit logs650 npm9MIT
- AlicenseNot gradedqualityDmaintenanceA default-deny SQL firewall sidecar for AI agents that enforces per-agent policies on database queries, provides safe rewrites, and maintains a tamper-evident audit chain.AGPL 3.0
- AlicenseNot gradedqualityCmaintenanceA multi-database MCP server that enables LLM agents to safely access MySQL, Oracle, DM, PostgreSQL, and SQLite databases with security features like whitelist, row count pre-check, and audit logging.3MIT
- AlicenseAqualityBmaintenanceA security-hardened Postgres MCP server that enables LLM agents to run safe, read-only SQL queries with enforcement via SQL-AST inspection and read-only transactions.1MIT