Learn how to safely expose SQL data to AI agents using a two-part pattern: MCP for AI communication and a schema-driven query builder for secure queries."
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 is built in: 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 (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: https://github.com/sanchar10/mcp-sql-query-dotnet
Follow me for more AI architecture deep-dives, and drop a comment if you have questions!
Top comments (0)