How to connect AI agents to databases: 5 ways, step by step

Short answer: you can hand an AI agent a connection string, a read-only role, an MCP database server, a proxy that checks every statement, or a tool that checks SQL before it runs. For anything that touches production, give the agent no database credential of its own: let it reach the data through a read-only role behind a proxy or MCP server that evaluates each statement, and keep the direct credential out of its environment.

The five ways at a glance

The same five options apply to coding agents (Claude Code, Cursor, Codex) and to agents you build with LangChain or the OpenAI Agents SDK. They differ in who holds the credential and who checks the SQL.

WayWho holds the credentialWho checks the SQL
1. Direct connection stringThe agentNobody
2. Read-only roleThe agentThe database's privileges
3. An MCP database serverThe MCP serverWhatever that server implements
4. The Vericto proxy or vericto-proxy mcpThe proxyVericto's rules, on the AST of each statement, before the database sees it
5. Runtime MCP server and check_sqlYour own tool (Vericto never connects)Vericto returns a verdict; the agent or your tool acts on it

They combine: a read-only role is worth having under every other option.

1. A direct connection string

When to use it

A local or disposable database with nothing you would miss: a Docker container, a seeded dev database, a branch you can recreate.

Setup

The agent reads a URL from the environment, a .env file or its tool configuration, and runs SQL with psql, a driver, LangChain's SQL database wrapper or a function tool you register in the OpenAI Agents SDK.

What can go wrong

  • The agent has every privilege of that user. If the URL belongs to the owner role, a DELETE without WHERE, a DROP TABLE or a schema reset runs as written.
  • Anything in the environment is readable. A coding agent can read the .env and the shell variables, and use that credential from any tool, not only the one you meant.
  • Rows are text the model reads. A value stored in a table can carry instructions; with write access, an injected instruction can become a write.

Developers have reported agents that ran destructive statements against production: see an AI agent deleted the production database, Claude Code and Codex.

This is the statement the rule pages call VERICTO-001, and what the Vericto CLI reports for it:

-- cleanup.sql
DELETE FROM users;
$ npx @vericto/vericto-cli@2.3.0 check --offline cleanup.sql
note: offline mode: 42 standard rules at default severities, engine 5.1.0. Custom rules, overrides, sensitive columns, allowlists and the audit trail apply online only.
✖ cleanup.sql  BLOCKED  VERICTO-001 critical
    DeleteStmt > WhereClause = NULL
    fix: DELETE FROM users WHERE id = $1
1 blocked · 0 allowed · 0 flagged · 0 monitored   (ruleset standard@engine-5.1.0 · mode: offline (engine 5.1.0, 42 standard rules, no workspace policy))

✖ Vericto blocked 1 statement  (ruleset standard@engine-5.1.0 · mode: offline (engine 5.1.0, 42 standard rules, no workspace policy))
  ✖ cleanup.sql  BLOCKED  VERICTO-001 critical
      DeleteStmt > WhereClause = NULL
      fix: DELETE FROM users WHERE id = $1

This is Vericto enforcing a rule — the exit code is intentional, not a crash.
To allow a finding on purpose, add an inline comment on the statement:
    -- vericto:ignore[VERICTO-001] <reason>   (a reason is required)

Real output of @vericto/vericto-cli@2.3.0 (engine 5.1.0) on the example of the VERICTO-001 page.

2. A read-only role

When to use it

Always, as the base layer, whenever the agent only needs to read. A role with SELECT grants only makes the database itself refuse writes.

Setup

PostgreSQL (GRANT):

CREATE ROLE vericto_agent_ro LOGIN PASSWORD '…';
GRANT CONNECT ON DATABASE shop TO vericto_agent_ro;
GRANT USAGE ON SCHEMA public TO vericto_agent_ro;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO vericto_agent_ro;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO vericto_agent_ro;

From the docs, not tested here: vericto-proxy 5.0.1: docs/MCP.md (MCP proxy mode)

MySQL (GRANT):

CREATE USER 'agent_ro'@'%' IDENTIFIED BY '…';
GRANT SELECT ON shop.* TO 'agent_ro'@'%';

From the docs, not tested here: MySQL 8.4 Reference Manual: GRANT

What can go wrong

  • Reads still do harm. A read-only role can run an unbounded SELECT over a large table, and can read every column it was granted, including emails or card numbers that then land in the model's context.
  • Session settings are not a lock. Settings such as default_transaction_read_only and statement_timeout are client connection defaults a session can change; the grants are what holds.
  • Some catalogues are readable by any role. In PostgreSQL, pg_catalog describes the schema to everyone who can connect.

We tested this on PostgreSQL 17, statement by statement: what a read-only Postgres role does and doesn't stop when an AI agent connects.

3. An MCP database server

When to use it

When the agent speaks the Model Context Protocol (Claude Code, Cursor, Codex and many others do) and you want it to call a database tool instead of a shell. An MCP database server is a process that holds the credential and exposes tools such as "run this SQL" or "describe the schema" to the agent.

Setup

You register the server in the agent's MCP configuration (a command it starts, or a URL), and give the server the connection URL. The exact flags depend on the server you pick: follow its own documentation.

What can go wrong

  • The credential moves, the risk does not. The agent no longer sees the URL, but the server runs what the model asks for with that credential's privileges.
  • Many servers run any SQL the model writes. Check whether the one you use restricts statements, bounds results or runs inside a read-only transaction; if not, the read-only role is your only control.
  • Results are untrusted data. Rows go back into the model's context, where an injected instruction can steer the agent's other tools.
  • A second path defeats it. If the agent also has a DATABASE_URL in its environment, it can go around the server.

4. The Vericto proxy or vericto-proxy mcp

Both put Vericto between the agent and the database: each statement is evaluated on its AST against the rules before the database receives it.

When to use it

  • The TCP proxy (PostgreSQL and MySQL) for an agent or app that already speaks the database protocol, including SQL an ORM generates. No code change: the connection URL points at the proxy.
  • vericto-proxy mcp (PostgreSQL, read-only in 5.0.1) for a coding agent: it gets execute_sql, describe_schema, check_sql and whoami, and no database credential.

Setup: the TCP proxy

Run the proxy next to the database and point the client at it, with the same user and password (integration guide):

# docker-compose.yml
services:
  vericto-proxy:
    image: ghcr.io/vericto/vericto-proxy:latest
    ports:
      - "5433:5433"
    environment:
      VERICTO_API_URL: "https://api.vericto.com"
      VERICTO_API_KEY: "${VERICTO_API_KEY}"
      VERICTO_DATABASE_ID: "${VERICTO_DATABASE_ID}"
      VERICTO_WIRE_PROTOCOL: "postgres"   # or "mysql"
      UPSTREAM_HOST: "your-db-host.rds.amazonaws.com"
      UPSTREAM_PORT: "5432"
      PROXY_LISTEN_PORT: "5433"
      # Remote DB (RDS): encrypt the proxy → database hop.
      UPSTREAM_SSLMODE: "require"   # or "verify-full" + UPSTREAM_SSLROOTCERT

  app:
    environment:
      # Point your app to the proxy — same user:pass as before
      DATABASE_URL: "postgres://user:pass@vericto-proxy:5433/mydb"
    depends_on:
      - vericto-proxy

From the docs, not tested here: Vericto integration guide: the TCP proxy

Setup: vericto-proxy mcp, no account needed

Since 5.0.1 there are native binaries for Linux, macOS and Windows. Without VERICTO_API_KEY the server runs locally on the built-in ruleset and reports nothing anywhere.

  1. Create a role only this server uses, with the read-only SQL from step 2.
  2. Put the URL in a file, not in the agent's configuration:
mkdir -p ~/.config/vericto && chmod 700 ~/.config/vericto
printf '%s' 'postgres://vericto_agent_ro:…@db.example.com:5432/shop?sslmode=verify-full' \
  > ~/.config/vericto/shop.url
chmod 600 ~/.config/vericto/shop.url

From the docs, not tested here: vericto-proxy 5.0.1: docs/MCP.md (MCP proxy mode)

  1. Install the binary and register the server. Claude Code:
curl --proto '=https' --tlsv1.2 -LsSf \
  https://github.com/vericto/vericto-proxy/releases/download/v5.0.1/vericto-proxy-installer.sh | sh
claude mcp add vericto-db -- ~/.cargo/bin/vericto-proxy \
  mcp --database-url-file ~/.config/vericto/shop.url

From the docs, not tested here: vericto-proxy 5.0.1: docs/MCP.md (MCP proxy mode)

Cursor (.cursor/mcp.json):

{
  "mcpServers": {
    "vericto-db": {
      "command": "/Users/me/.cargo/bin/vericto-proxy",
      "args": ["mcp", "--database-url-file", "/Users/me/.config/vericto/shop.url"]
    }
  }
}

From the docs, not tested here: vericto-proxy 5.0.1: docs/MCP.md (MCP proxy mode)

Codex (~/.codex/config.toml):

[mcp_servers.vericto-db]
command = "/Users/me/.cargo/bin/vericto-proxy"
args = ["mcp", "--database-url-file", "/Users/me/.config/vericto/shop.url"]

From the docs, not tested here: vericto-proxy 5.0.1: docs/MCP.md (MCP proxy mode)

  1. Ask the agent to call whoami. This is the real answer in local mode:
whoami {}
Proxy mode · local (no control plane) · database shop (postgres) · tiers: read enabled, write/delete/ddl off · ruleset standard@5.0.0 (built-in)
Limits: 200 rows (max 1000), 262144 bytes, 8192 bytes per value, 15000 ms timeout.
Warning (no_control_plane): no control plane (local mode): the built-in ruleset only, without the workspace's rules, masks, allowlists, kill switch or reporting

Real output: vericto-proxy 5.0.1 release binary, `vericto-proxy mcp` in local mode, 2026-11-14.

A statement the rules block never runs, and a write is refused because only the read tier exists in 5.0.1. Real answers:

execute_sql { "sql": "DROP TABLE users" }
BLOCKED (BLOCKED): Blocked by VERICTO-010 (DropStmt).
Suggested fix: Use a versioned migration tool (Flyway, Prisma Migrate, Alembic, Rails migrations)
Next: not run; apply the suggested fix and call execute_sql again with the corrected SQL.
Ruleset standard@5.0.0

Real output: vericto-proxy 5.0.1 release binary, `vericto-proxy mcp` in local mode, 2026-11-14.

execute_sql { "sql": "DELETE FROM users WHERE id = 1" }
BLOCKED (TIER_NOT_ENABLED): The delete tier is not enabled for this database.
Next: not run: this is a DELETE and only read is enabled for you on shop. Each tier (write, delete, DDL) needs a person to enable it, and each statement needs approval; ask the user. Rephrasing will not help.
Ruleset standard@5.0.0

Real output: vericto-proxy 5.0.1 release binary, `vericto-proxy mcp` in local mode, 2026-11-14.

Linked to a Vericto workspace (VERICTO_API_KEY and VERICTO_DATABASE_ID), the same server applies the workspace's custom rules, sensitive-column masks and agent-access allowlists, records every call in the audit trail and adds a kill switch. The proxy is open source under AGPL-3.0-only.

What can go wrong

  • Another credential goes around it. The docs are explicit: it holds only if the agent has no other database credential. The server warns, by name, about DATABASE_URL, PGPASSWORD, a ~/.pgpass and similar in its environment. In Claude Code you can also deny the agent's own tools access to the secret in settings.json:
"permissions": { "deny": ["Read(~/.config/vericto/**)", "Bash(psql:*)", "Bash(cat ~/.config/vericto/*)"] }

From the docs, not tested here: vericto-proxy 5.0.1: docs/MCP.md (MCP proxy mode)

  • MySQL and writes are not in vericto-proxy mcp 5.0.1. For MySQL, use the TCP proxy.
  • Masks have limits. A tagged column used only in WHERE is not a read; the docs recommend an agent-access allowlist for the agent's database user.

5. The Vericto runtime MCP server and check_sql

When to use it

When the agent writes SQL (migrations, queries in code, a text-to-SQL tool) and should get a verdict before anything runs, on any of the six dialects. Vericto only analyses the text: it never connects to your database.

Setup: a coding agent

Create an API key with only the ci_dryrun:execute scope, export it as VERICTO_API_KEY, and add the remote server (MCP docs):

claude mcp add --scope user --transport http vericto https://mcp.vericto.com/mcp \
  --header 'Authorization: Bearer ${VERICTO_API_KEY}'

From the docs, not tested here: Vericto docs: AI agents (MCP)

The agent calls check_sql and gets BLOCKED, FLAGGED, MONITORED or ALLOWED per statement, with the rule, the line and a suggested fix. The real output below comes from the local check_sql of vericto-proxy mcp, which evaluates "as the hosted check_sql answers", in the same format:

check_sql { "dialect": "postgres", "sql":
  "SELECT id, email FROM users WHERE id = 42 LIMIT 1;
   DELETE FROM users;
   UPDATE orders SET status = 'cancelled';
   SELECT id, email FROM users WHERE name = 'x' OR 1 = 1;
   SELECT id, email FROM users WHERE active;" }
BLOCKED: 3 of 5 statements must not ship as written.
- line 2 BLOCKED VERICTO-001 (critical): DELETE FROM users Fix: DELETE FROM users WHERE id = $1
- line 3 BLOCKED VERICTO-030 (critical): UPDATE orders SET status = 'cancelled' Fix: UPDATE orders SET {col} = $1 WHERE id = $2
- line 4 BLOCKED VERICTO-090 (critical): SELECT id, email FROM users WHERE name = 'x' OR 1 = 1 Fix: SELECT ... WHERE id = $1  -- use parameterized queries
- line 5 FLAGGED VERICTO-050 (medium): SELECT id, email FROM users WHERE active
Next:
- lines 2, 3, 4 (VERICTO-001): do not run it as written; apply the suggested fix, then call check_sql again with the corrected SQL.
- line 5 (VERICTO-050): allowed; mention VERICTO-050 (medium) to the user when you run it.
- line 1: call execute_sql with the same sql.
Ruleset standard@5.0.0 · checked locally, no CI checks spent

Real output: vericto-proxy 5.0.1 release binary, `vericto-proxy mcp` in local mode, 2026-11-14.

Setup: a custom agent (LangChain, OpenAI Agents SDK)

The Python and Node SDKs (Apache-2.0) evaluate each statement through the runtime API before your driver runs it. LangChain has an official integration, vericto.langchain (VerictoSQLDatabase for SQLDatabaseToolkit and create_sql_agent). For the OpenAI Agents SDK and other frameworks, the documented pattern is a tool function that calls guard.prepare() before executing:

import psycopg
from vericto import Vericto, VerictoBlocked

guard = Vericto()  # one per process
conn = psycopg.connect("dbname=app")  # a plain connection: the tool does the check

def run_sql(query: str) -> str:
    """The function you register as the agent's SQL tool."""
    try:
        sql = guard.prepare(query, "postgres")  # the masked rewrite when there is one
    except VerictoBlocked as exc:
        return f"Vericto blocked this query ({exc.verdict.rule_code}); it was not run. Suggested fix: {exc.suggested_fix}"
    with conn.cursor() as cur:  # VerictoUnavailable and VerictoConfigError propagate
        cur.execute(sql)
        return repr(cur.fetchall())

From the docs, not tested here: Vericto docs: Python and Node SDKs

What can go wrong

  • check_sql advises; it does not execute. An agent that ignores the verdict can still run the original through another tool. Pair it with a read-only role, or with the proxy when it must hold.
  • The SDK protects the SQL that goes through it. Not another connection, the raw driver object or another process with the same credentials.
  • Do not turn errors into text for the model. Let VerictoUnavailable and VerictoConfigError propagate, so a misconfiguration fails closed.

Which way to choose

WaySetupWhat stops a DELETE or DROPSensitive columnsAuditMySQL
Direct connection stringA URLNothingNoOnly what the database logsYes
Read-only roleA few SQL statementsThe database refuses writesOnly what you leave out of the grants or viewsOnly what the database logsYes
An MCP database serverOne entry in the agent's configDepends on the server and the role behind itDepends on the serverDepends on the serverDepends on the server
Vericto TCP proxyA container and a Vericto accountThe proxy blocks it before the databaseBlock, flag or mask per columnEvery statement in the audit trailYes
vericto-proxy mcpOne binary; no account for local modeRead tier only, plus the rulesMasks when linked to a workspaceEvery call, when linkedNo (PostgreSQL in 5.0.1)
Runtime MCP and check_sqlOne command and an API keyA BLOCKED verdict the agent must followThe masked query as the only approved oneCheck history in the dashboardYes (dialect: mysql)

A rule of thumb: local data, a direct URL is fine; shared or production data, a read-only role plus the proxy or vericto-proxy mcp, and check_sql for the SQL the agent writes into code.

Frequently asked questions

Sources

The official documentation this guide cites, checked on 2026-11-14: