Leadership teams want to ask natural-language questions against live revenue, churn, and pipeline tables—without risking a dropped table, production lockup, or cross-tenant data leak. Building a guarded MCP server for PostgreSQL lets AI agents run accurate analytical queries safely via read replicas, Row-Level Security, and strict SQL guardrails.
Why Giving Agents Raw Database Credentials Fails in Production
Handing an AI assistant a standard read-write Postgres connection string is an incident waiting to happen. Even without malicious intent, an ambiguous natural-language question can generate an unindexed 5-table join that saturates CPU on your primary OLTP database or returns sensitive PII columns such as emails, tokens, and billing details.
When Webnext builds custom CRM and ERP AI integrations, we place an isolated read-only MCP service in front of a dedicated streaming read replica so analytical AI workloads can never impact transactional checkout or customer logins.
- Curated Analytical Views: Expose clean
analytics_*SQL views that pre-strip PII and pre-join common foreign keys so the LLM writes simpler, faster SQL. - PostgreSQL Row-Level Security (RLS): Bind the authenticated tenant or account manager ID into the Postgres transaction via
set_config()so the database engine enforces isolation even if generated SQL omits aWHEREfilter. - Statement & Row Caps: Reject multi-statement strings, block DDL/DML keywords, force
LIMIT 100, and enforcestatement_timeout = '3000ms'.
Preventing SQL Hallucinations With Curated MCP Resources
Production schemas frequently span hundreds of legacy tables with cryptic column abbreviations. Dumping raw pg_catalog metadata into every prompt bloats token costs and causes the model to guess join paths.
Instead, publish a concise MCP Resource documenting only your 10–20 approved reporting views, business metric formulas (for example, exact Net Revenue Retention logic), and common date filters. For unstructured notes or attachments stored alongside CRM rows, pair Postgres with hybrid vector retrieval and enforce RBAC permissions uniformly.
PostgreSQL MCP Guardrails Checklist
| Control Layer | Configuration | Protects Against |
|---|---|---|
| Replica & Role | Read-only role on Postgres read replica | Accidental INSERT / UPDATE / DELETE & OLTP locks |
| View Whitelist | Grant SELECT solely on analytics_* schema | Exposure of auth tokens, passwords & raw PII |
| Session Timeout | SET LOCAL statement_timeout = ‘3000ms’ | Cartesian joins & runaway CPU scans |
| Row-Level Security | SET LOCAL app.tenant_id = $1 | Cross-tenant or unauthorized data leaks |
| Result Cap | Hard row cap (max 100 rows) | Context window overflow & bulk scraping |
Safe Tenant-Scoped Read-Only PostgreSQL MCP Query Tool
import re
import asyncpg
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("postgres-readonly-analytics")
FORBIDDEN_SQL = re.compile(r"b(INSERT|UPDATE|DELETE|DROP|ALTER|GRANT|COPY|TRUNCATE)b", re.I)
@mcp.tool()
async def run_analytics_select(sql: str, tenant_id: str) -> dict:
"""Execute a read-only SELECT query on curated analytics_* views (max 100 rows)."""
cleaned = sql.strip().rstrip(";")
if not cleaned.upper().startswith("SELECT") or ";" in cleaned or FORBIDDEN_SQL.search(cleaned):
return {"error": "Only single read-only SELECT queries are permitted."}
if "LIMIT" not in cleaned.upper():
cleaned += " LIMIT 100"
conn = await asyncpg.connect(READ_REPLICA_DSN)
try:
async with conn.transaction(readonly=True):
await conn.execute("SET LOCAL statement_timeout = '3000ms'")
await conn.execute("SELECT set_config('app.tenant_id', $1, true)", tenant_id)
rows = await conn.fetch(cleaned)
return {"row_count": len(rows), "rows": [dict(r) for r in rows[:100]]}
finally:
await conn.close()
Related Webnext Engineering Resources
- Custom CRM & ERP Software Development Services
- Securing MCP Servers in Production with OAuth 2.1
- Role-Based Access Control (RBAC) in Enterprise RAG
- Database Design and Optimization Services
Frequently Asked Questions (FAQ)
Should an AI agent ever have raw SQL write access via MCP?
No. Expose read-only reporting views for analytical queries and wrap any state changes (like updating a CRM deal stage) in strict, parameter-validated API tools.
How do you prevent an LLM from running a slow full-table scan on PostgreSQL?
Enforce PostgreSQL statement_timeout (e.g., 3000ms), reject queries lacking LIMIT clauses, and use read-replica connections isolated from OLTP traffic.
Can PostgreSQL Row-Level Security (RLS) work with an MCP server?
Yes. Set SET LOCAL app.current_tenant_id inside each read transaction from the user’s verified OAuth token so Postgres itself enforces multi-tenant isolation.
How do you help LLMs write accurate SQL against complex schemas?
Expose curated schema definitions and sample rows as an MCP Resource containing only the 10–20 analytical views the agent actually needs.
Connect AI Safely to Your Postgres & CRM
Let Webnext engineer read-only analytics MCP servers and governed CRM automation workflows for your team.




