SQL Access for AI Agents — Flexibility with Guardrails
Source: Dev.to
Operational AI Agents Need Boundaries
AI agents are increasingly used for operational tasks like customer support:
“What’s the status of my subscription?”
To answer, an agent must:
- Look up the customer by email or phone
- Check active subscriptions
- Review recent interactions
The challenge: allowing AI to query databases safely without giving unrestricted access.
Why Common Solutions Fall Short
| Approach | Challenge for AI Agents |
|---|---|
| Raw SQL | Risky, prone to injection and errors |
| Hardcoded APIs | Inflexible, needs code changes for every query |
| GraphQL / OData | Powerful but generic; lacks safeguards and declarative interfaces for reliable agentic queries |
Key insight: AI agents don’t need full database flexibility — they need predictable, bounded access.
Our Two-Part Solution
We combined two patterns:
1. Model Context Protocol (MCP)
- Standardized interface for AI → tool communication
- Enables tool discovery, structured parameters, predictable responses
2. Schema‑Driven Query Builder
- Converts JSON‑defined entity schemas into safe SQL
- Handles relationships, field allowlists, and multiple backends
- Supports multiple SQL backends — SQLite for demos, SQL Server or PostgreSQL for production — with the same query logic
Outcome: minimal boilerplate, safe boundaries, LLM‑friendly query syntax.
Security: explicit field allowlists (allowedFilterFields) prevent AI from accessing unauthorized data.
Why It Matters
- AI‑ready APIs: enable operational queries safely
- Dual interface: same engine serves AI (via MCP) and REST clients
- Extensible: add new tools with minimal code
- Secure: explicit allowlists prevent unauthorized access
Key Takeaways
- Operational AI queries ≠ ad‑hoc analytics
- Bounded interfaces improve reliability and predictability
- Separation of transport (MCP) and query logic (query builder) maximizes flexibility
- MongoDB‑style JSON filters align with LLM training
What’s Next
In the next post, we’ll dive into MCP in detail: how AI discovers and calls tools, with real examples.
Check out the GitHub repo for the full implementation, diagrams, and code: