Securing MCP servers against SQL injection and table drops

Model Context Protocol servers execute database queries directly from agent prompts. When an agent receives malicious context or hallucinates syntax, conversational guardrails fail to stop destructive execution.

The Model Context Protocol threat landscape

The Model Context Protocol (MCP) has rapidly emerged as the standard protocol for connecting AI coding assistants and autonomous agents to local and remote developer tools. Whether developers are using Cursor, Claude Code, Windsurf, VS Code, or Goose, MCP provides an open standard for exposing tool execution endpoints. Through simple JSON-RPC over standard input/output or Server-Sent Events (SSE), an agent can invoke shell commands, fetch web resources, call third-party APIs, and execute SQL statements against live databases.

However, the architecture of MCP inherently places immense trust in the calling language model. When an MCP server registers a tool such as postgres_execute or run_sql, the server acts as an unmediated proxy between conversational text generation and the database engine. If the language model hallucinates an aggressive schema migration, misplaces a critical WHERE clause, or processes an untrusted prompt containing an indirect prompt injection payload, the MCP server receives and executes the command with the full privileges of its connection string.

Understanding this threat surface requires examining how MCP servers process inputs, why standard transaction boundaries fail under adversarial tool inputs, and how engineering teams must enforce deterministic pre-execution checks and physical storage verification.

Every MCP tool call goes through your rules first. Here a delete that doesn’t say which rows is stopped before it reaches the database. These are the rules deedglass init starts with; the call is made up.

Anatomy of an MCP SQL injection exploit

The most pervasive misconception in agent security is that executing SQL through a parameterized tool interface is inherently safe from injection. In practice, many database MCP implementations expose free-form SQL text execution to allow agents the full flexibility needed to write complex queries, analyze relational schemas, and debug performance bottlenecks.

In August 2025, security researchers exposed the systemic vulnerability of this pattern. Datadog Security Labs (Santiago Mola, 21 August 2025) showed that the reference Postgres MCP server @modelcontextprotocol/server-postgres 0.6.2 ran each query in a transaction opened with BEGIN TRANSACTION READ ONLY and rolled back in a finally block, and that a query beginning COMMIT; ends that transaction so the statements after it run outside it; their proof of concept dropped every table.1

Consider the mechanics of this flaw:

The MCP server assumed that prepending BEGIN TRANSACTION READ ONLY created an inviolable sandbox for the lifetime of the client invocation. However, relational engines evaluate multi-statement batches sequentially on the same connection. When an incoming agent query begins with COMMIT;, the read-only transaction terminates immediately. Subsequent statements within the exact same payload execute in standard autocommit mode with full read-write authority:

Code A database command in SQL. The text around it says what it does.

-- Incoming tool argument generated by an injected agent:
COMMIT; DROP TABLE customer_tenants CASCADE; DROP TABLE audit_ledger CASCADE;

Because the MCP server relied on programmatic wrappers rather than strict AST parsing and connection-level role isolation, the finally block attempted to roll back a transaction that had already closed, leaving the catastrophic table drops permanently committed on disk.

Credential exfiltration via tool arguments

Destructive table drops represent only half of the threat profile. The second critical vector is automated data and credential exfiltration through unconstrained tool parameters.

Autonomous agents frequently operate with read-write access to multiple MCP servers simultaneously: an agent might possess tools for querying a Postgres database alongside tools for filing issue tracker tickets, sending Slack notifications, or updating customer support portals. When an agent possesses cross-boundary capabilities, an injection payload in one data source can coerce the agent into exfiltrating sensitive credentials through another.

In a July 2025 demonstration by General Analysis (page dated 8 July 2025, dummy data only), a support ticket carrying instructions aimed at the developer’s assistant led an assistant using the Supabase MCP server under a service_role credential, which bypasses row-level security, to read the integration_tokens table and add its contents as a new message in the same ticket, where the attacker could see it.2

This demonstration highlighted two architectural failures:

  1. Over-privileged credentials: Assigning superuser or administrative roles (service_role) to an autonomous agent bypasses database security models like Row Level Security (RLS).
  2. Absence of tool parameter isolation: The agent had the authority to read private tokens and immediately pass those values as string arguments to a public-facing communication tool.

Without deterministic policies governing which tools can receive data extracted from specific database tables, prompt instructions alone cannot prevent an agent from inadvertently leaking keys, health records, or authentication secrets.

Why system prompt guardrails fail consistently

Faced with these vulnerabilities, many development teams attempt to mitigate risk through conversational instructions in system prompts:

Code What the screen or file shows, copied as is.

You are a responsible database assistant.
Never execute DROP TABLE, ALTER TABLE, or TRUNCATE.
Ensure all UPDATE queries include a valid WHERE clause.
Only read tables relevant to the user request.

Conversational guardrails fail because language models operate via probabilistic token prediction rather than formal invariant verification. When an agent processes complex multi-turn context, encounters error messages from previous queries, or digests untrusted user data, the attention mechanism distributes focus across all tokens. Attackers use jailbreaks, role-play framing, and nested linguistic obfuscation to bypass semantic restrictions.

Furthermore, language models cannot perform semantic static analysis on raw SQL strings. A query obfuscated using hex encoding, string concatenation, or dynamic function execution (EXECUTE format(...)) appears benign to a language model’s safety filter while executing destructively inside PostgreSQL.

Relying on system prompts to guard production data is equivalent to implementing firewall rules with natural language suggestions. Security boundaries must exist out-of-band at the execution protocol layer.

Deterministic tool gating with Deedglass

To eliminate these vulnerabilities without sacrificing agent velocity, Deedglass deploys as a local loopback gateway between your AI client and downstream MCP servers.

Instead of your agent connecting directly to @modelcontextprotocol/server-postgres or external API endpoints, your client connects to Deedglass. Deedglass evaluates every incoming JSON-RPC tool invocation against strict, deterministic policies compiled in the Common Expression Language (CEL).

Before any tool call reaches the database driver, Deedglass evaluates the request against your security rules:

  1. AST-Level SQL Inspection: Deedglass parses the SQL statement using native database grammar. It does not use fragile regular expressions. It identifies the statement type (SELECT, UPDATE, DELETE, DROP), inspects the target tables, and extracts the WHERE clauses.
  2. Deterministic Block Rules: Any statement containing forbidden DDL (DROP, ALTER, TRUNCATE) is blocked instantly at the gateway. The tool call never reaches the database socket, and the agent receives a structured, unforgeable error message.
  3. Threshold-Based Approval Gates: Queries that modify more rows than a configured threshold (such as an UPDATE affecting more than 5 rows) are paused. Deedglass holds the tool call open until an authorized human engineer reviews the diff and approves the action via a local notification or CLI prompt.

Because Deedglass runs locally on loopback (127.0.0.1) on your workstation or internal infrastructure, evaluation adds less than 1 millisecond of latency, requiring zero external cloud round-trips.

Developers can explore how these gates behave in real time in our interactive browser playground, where real PostgreSQL queries are evaluated against deterministic security policies.

Verifying physical state after execution

Blocking obvious attacks at the gateway is necessary, but production reliability demands verifying what the database actually changed after the query completes.

In traditional setups, the agent executes an update and reads the returned response: “UPDATE 1”. However, triggers, cascading foreign keys, and stored procedures can cause a single update to modify dozens or hundreds of hidden rows. If your agent is operating on medical charts, billing accounts, or multi-tenant customer tables, unrecorded side effects corrupt business state without triggering an error.

If your app keeps its data in your own Postgres, with logical decoding on, Deedglass checks each agent write it runs against Postgres’s change log (Proven) and can undo the rows after a person countersigns.34

Deedglass connects to PostgreSQL’s native logical replication stream. When an agent executes a write, Deedglass reads the exact row-level changes recorded in the Write-Ahead Log (WAL). It compares the physical rows modified on disk against what the agent reported. If the agent reported updating one account record, but the WAL reveals 301 rows were updated, Deedglass flags the discrepancy immediately:

  • Claimed: What the agent stated in its conversational tool output.
  • Checked: What Deedglass confirmed by querying the database state.
  • Proven: Physical, ground-truth change verification derived directly from PostgreSQL logical decoding.

Deedglass seals a signed record of each action that the client can check offline, generating tamper-evident Merkle records that confirm provenance under healthcare and financial frameworks.3

To benchmark your current local agent configuration and evaluate your exposure to unmonitored MCP tool calls, you can calculate your security score or run npx deedglass scan directly in your terminal to identify open ports, plaintext tokens, and unguarded database connections across your repositories.

Configuring your agent safely today

Securing your agent workflow takes less than two minutes. To configure hardened MCP policies without manual JSON editing, use our interactive MCP Security Policy & Config Generator.

To secure an existing Cursor, Claude Code, or VS Code installation immediately:

  1. Audit your repository: Run npx deedglass scan in your project root. The scanner parses .cursor/mcp.json, .claude/settings.json, and environment files to identify unshielded database tools.
  2. Launch the Deedglass gateway: Run npx deedglass mcp serve to start the local loopback proxy.
  3. Connect your database: Configure your database connection string under a dedicated, least-privilege PostgreSQL user role.
  4. Enforce deterministic write gates: Enable human-in-the-loop approvals for table modifications and bulk operations.

By placing a deterministic policy gate and physical WAL verification between your agent and your database, you allow your engineering team to move fast with autonomous coding agents while ensuring production data remains completely secure.

Written with AI assistance and checked against our claims register.

The takeaway

LLM conversational guardrails cannot protect relational storage. Securing MCP requires deterministic tool gating and physical write verification.

Read nextWhy AI agent retry loops compound database corruption Try it: install in 7 s

Related on this site

More posts

Sources

  1. 1Datadog Security Labs: MCP PostgreSQL Vulnerability Case Study · securitylabs.datadoghq.com · checked 4 November 2026
  2. 2General Analysis: Supabase MCP Server Demonstration · generalanalysis.com · checked 4 November 2026
  3. 3Deedglass Verification Levels (Claimed and Checked) · docs.deedglass.com · checked 4 November 2026
  4. 4PostgreSQL Documentation: Logical Decoding · postgresql.org · checked 4 November 2026

Published 4 November 2026, sources last checked 4 November 2026. If something here is out of date, write to hello@deedglass.com.

Try it on your own setup

npx deedglass scan

Grades only your own setup. Nothing is uploaded.

Pricing