Dev.to Security 🔐 Cybersecurity 👁 2 📖 3 min read

Why You Shouldn't Give AI Agents Direct Database Access (And How 4 Scoped MCP Tools Fix It)

Why You Shouldn't Give AI Agents Direct Database Access (And How 4 Scoped MCP Tools Fix It) Giving an AI coding agent like Claude or Codex direct access to your production database sounds magical—until it hallucinates a

Why You Shouldn't Give AI Agents Direct Database Access (And How 4 Scoped MCP Tools Fix It)

Giving an AI coding agent like Claude or Codex direct access to your production database sounds magical—until it hallucinates a column name, triggers a full-table scan across tenants, or runs a write query you didn't anticipate.

With Model Context Protocol (MCP) gaining traction, a lot of teams are wiring up generic Text-to-SQL MCP servers directly to Postgres or ClickHouse. For a local sandbox, that's fine. For multi-tenant event data in production, it's an accident waiting to happen.

While building an event reporting and retrieval system designed to be queried natively by AI agents, we ended up throwing away the "generic SQL over raw tables" idea and constraining the architecture around three strict boundaries. Here is the pattern that actually held up in practice.

1. Validate Against a Schema Before Anything Enters Storage

Most Text-to-SQL failures aren't actually LLM reasoning failures—they are data ambiguity failures.

If your ingestion pipeline accepts arbitrary schemaless JSON blobs, different services inevitably log userId, user_id, and uid as strings, ints, or nulls. When an agent tries to query "payment failures for user X in the last 24 hours," it has to guess the field structure and silently misses half the records.

A schema-first ingestion boundary fixes this upstream:

  • Every event—whether sent as a single HTTP JSON request or uploaded in batch files (CSV, TSV, NDJSON, Parquet, XLSX)—is validated against an authorized, versioned schema before ingestion.
  • Be honest about async state: Returning HTTP 202 Accepted on an event report or queueing a batch file job does not mean the record is immediately queryable. Separating ingestion acceptance from query readiness avoids race conditions when an agent checks a workflow right after triggering it.

2. Physically Separate Write and Read Credentials

Never hand an AI agent an API key that can also mutate data or manage account settings.

Even if your MCP server code claims to be "read-only," prompt injection or a single misconfigured endpoint turns a shared credential into a write vulnerability. We enforce strict credential isolation at the gateway level:

  • Write credentials (wk_proj_...): Scoped to a single tenant and project. Allowed to discover writable schemas and report events/files. Rejected (401) if used against MCP retrieval endpoints.
  • Read credentials (rk_proj_...): Strictly read-only, scoped to the same tenant/project boundary. Rejected (401) if used to ingest data.

If a Read token leaks inside a developer's local IDE config, it still cannot pollute production event streams or cross into another project's data.

3. Replace Freeform SQL with 4 Narrow MCP Tools

Instead of exposing a run_sql(query) tool that forces the model to guess table joins and tenant filters, constrain the MCP surface to four deterministic, read-only tools:

  1. list_schemas() — Returns only the active schemas authorized for the caller's Read token.
  2. describe_schema(schema_id) — Exposes exact field names, primitive types, and allowed filter fields so the agent never guesses column names.
  3. validate_schema(schema_id, sample) — Lets developers or agents dry-run a payload against the contract without writing a single record.
  4. query_schema(...) — Structured retrieval bounded by declared filters, record limits, and an explicit UTC time window.

Here is what a scoped query payload looks like when an agent investigates a payment error:

{
  "schema_id": "default_behavior_events",
  "schema_version": 1,
  "start_time": "2026-12-02T15:13:13Z",
  "end_time": "2026-12-03T15:13:13Z",
  "limit": 20,
  "filters": {
    "data_desc": "payment_failed"
  }
}

Notice what is not in the payload: no tenant_id parameter for the LLM to spoof or forget. Tenant and project isolation is derived strictly from the Read credential on the server side.

The Tradeoff

You do give up ad-hoc multi-table JOINs and arbitrary aggregations compared to a raw SQL console. But for operational debugging—finding a specific event_id, tracing a user_id across a time window, or inspecting failed batch imports directly inside Codex, Claude, or Cursor—constraining the contract makes agent retrieval predictable, auditable, and safe enough to actually hand to engineers.

Disclosure: I'm building EventInsight, a schema-first event data platform with separate Read/Write credentials and native MCP retrieval based on the architecture above. You can inspect the API/MCP contract or walk through a simulated query on the site. How are you currently isolating permissions when connecting AI agents to operational data?

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.