Skip to main content
Glama
supabase-secure

supabase-secure

Secure Supabase Model Context Protocol (MCP) Server

CI Security Check TypeScript License: MIT Node.js

An enterprise-grade Model Context Protocol (MCP) server that grants AI agents (Antigravity IDE/CLI, Cursor, Claude Desktop) safe access to Supabase database stored procedures without exposing raw SQL execution.


1. Problem Statement

Connecting LLMs directly to SQL databases introduces critical vulnerabilities:

  • SQL Injection & Data Loss: Unchecked LLM parameter generation can trigger unintended DROP TABLE or DELETE commands.

  • Schema Leakage: Exposing raw internal database tables increases the attack surface.

  • Zero Visibility: Lack of execution tracking makes auditing LLM query intents and latency impossible.


Related MCP server: MCP Postgres Guard

2. Architecture & Security Defenses

graph TD
    Client[LLM Client: Antigravity CLI / IDE] -->|JSON-RPC over STDIO| MCP[Secure MCP Server Layer]
    
    subgraph Execution Safeguards
        MCP -->|1. Type Guard| Zod[Zod v4 Native Schema Validator]
        MCP -->|2. Mode Guard| Scope[Scope Control Middleware]
        MCP -->|3. Error Sanitizer| ErrorHandler[Postgres Trace Sanitizer]
        MCP -->|4. Interceptor| Audit[Async Audit Interceptor]
    end
    
    Zod -->|Validated RPC Params| Supabase[(Supabase Stored Procedures)]
    Scope -->|Blocked Mutations| Client
    Audit -->|Execution Records| AuditTable[(mcp_audit_logs Table)]

Key Security Features

  1. Air-Gapped Tool Layer: AI agents execute pre-written database functions (RPCs). Dynamic SQL construction and raw queries are strictly prohibited.

  2. Native Zod v4 Schema Validation: Employs Zod v4's z.toJSONSchema(schema, { io: "input" }) for native OpenAPI tool registration, enforcing strict parameter boundaries (ISO dates, UUIDs, numeric bounds).

  3. Scope Control Middleware: Enforces READ_ONLY mode by default, trapping state-modifying operations unless an explicit admin token is provided.

  4. Immutable Audit Trail: Asynchronously writes caller role, tool parameters, execution duration, and status (SUCCESS, BLOCKED, ERROR) to mcp_audit_logs.

  5. Trace Sanitization: Strips internal PostgREST stack traces and database internal names before returning errors to the LLM client.


3. Quickstart

3.1 - Prerequisites

  • Node.js >= 20.0.0

  • Supabase project with Service Role key access

  • Antigravity CLI / IDE, Cursor, or Claude Desktop

3.2 - Installation & Build

git clone https://github.com/minhajadab3836/supabase-mcp-secure.git
cd supabase-mcp-secure
npm install
npm run build

3.3 - Database Setup (Supabase Migration)

Run the SQL migration located in supabase/migrations/20260101000000_init_security_schema.sql inside your Supabase SQL Editor. This initializes:

  • mcp_audit_logs (immutable audit trail table with indexes)

  • customers & orders (demo tables with sample seed records)

  • get_customer_metrics (read-only analytical stored procedure)

  • update_customer_status (audited mutation stored procedure)

3.4 - Environment Setup

Create a .env file in the root directory (refer to .env.example):

SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-supabase-service-role-key
MCP_MODE=READ_ONLY
ADMIN_TOKEN=secret-admin-token-123

3.5 - Security Test Suite

Run the automated assertion script to test SQL injection rejection, scope enforcement, parameter bounding, trace sanitization, and audit logging:

npm test

Expected Output:

šŸ”’ Starting Secure MCP Security Test Suite...

Test 1: SQL Injection in date parameter
āœ… PASSED: SQL Injection attempt caught by Zod schema validation.

Test 2: Unauthorized mutation execution in READ_ONLY mode
[AUDIT] 2026-11-07T13:42:34.721Z | Tool: update_customer_status | Status: BLOCKED | Duration: 0ms
āœ… PASSED: Scope Control guard blocked unauthorized mutation.

Test 3: Parameter overflow constraint check
āœ… PASSED: Parameter bound correctly enforced by Zod max limit.

Test 4: Error trace sanitization
āœ… PASSED: Sensitive database details stripped from error output.

Test 5: Scope authorization verification
āœ… PASSED: Scope guard correctly validates admin credentials.

šŸŽ‰ Security suite complete. All 5 defense boundaries verified.

4. Client Integration

Option 1: Antigravity IDE Workspace Auto-Discovery (.antigravity/mcp.json)

Place or update .antigravity/mcp.json in your workspace root:

{
  "mcpServers": {
    "supabase-secure": {
      "command": "node",
      "args": ["./dist/index.js"],
      "env": {
        "SUPABASE_URL": "https://your-project.supabase.co",
        "SUPABASE_SERVICE_ROLE_KEY": "your-service-role-key",
        "MCP_MODE": "READ_ONLY",
        "ADMIN_TOKEN": "secret-admin-token-123"
      }
    }
  }
}

Option 2: Antigravity CLI Manual Registration

Register the binary directly via CLI:

antigravity mcp add supabase-secure \
  --command node \
  --args "$(pwd)/dist/index.js" \
  --env SUPABASE_URL="https://your-project.supabase.co" \
  --env SUPABASE_SERVICE_ROLE_KEY="your-service-role-key" \
  --env MCP_MODE="READ_ONLY"

5. Security Threat & Defense Matrix

Threat Vector

Input Payload Attempt

Defense Mechanism

System Outcome

SQL Injection

startDate: "2024-01-01'; DROP TABLE orders; --"

Zod Date Regex Constraint

Throws z.ZodError; execution halts before database contact

Unauthorized Write

Mutation tool call under MCP_MODE=READ_ONLY

Scope Control Guard

Intercepts call, returns SECURITY_VIOLATION, logs BLOCKED status

Parameter Overflow

limit: 99999

Zod Range Constraint (max(50))

Throws z.ZodError; prevents memory and query resource exhaustion

Schema Leakage

Database execution failure or missing relation

Error Sanitizer Middleware

Strips internal Postgres engine details (PGRST200, table names)

Audit Bypass

Any tool execution attempt

Async Audit Interceptor

Logs caller role, parameters, latency, and status to mcp_audit_logs


6. Architecture & Threat Model

For the in-depth isolation specifications and architectural boundary breakdown, see docs/architecture.md.


7. License

MIT License. See LICENSE for details.

Available Tools

2 tools
get_customer_metricsC

Retrieves aggregated customer metrics. Read-only execution.

NameRequiredDescriptionDefault
limitNo
startDateYes

TDQS

C2.6/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of disclosure, and 'Read-only execution' is its only behavioral claim. It says nothing about pagination, limits, permissions, time ranges, or what the aggregation returns. For a metrics tool with zero annotation coverage, that leaves nearly everything an agent needs to know undisclosed.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two short sentences with no waste, and the purpose comes first. The second sentence earns its place because no annotations exist to say otherwise, though the wording is slightly mechanical.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a two-parameter tool with no annotations and no output schema, the description is far too thin. It omits the date format, how the limit affects the result, the aggregation scope or grouping, and the shape of the return value, all of which must now be inferred.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the schema only supplies types, a pattern, and a range. The description never mentions startDate or limit, so it adds no meaning and leaves the date format, the default, and the limit's effect unexplained.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description names a specific verb and resource: 'Retrieves aggregated customer metrics'. That is clear enough to act on, and it distinguishes it from the only sibling, update_customer_status. However, it gives no clue which metrics are aggregated, so the scope of the resource stays vague.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is given on when to use this tool or when to prefer an alternative. It doesn't state prerequisites, such as whether a customer ID or date range is required to scope the query. Usage can only be inferred from the tool name.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

update_customer_statusB

Updates account status for a customer UUID. Mutation (Requires Admin Scope).

NameRequiredDescriptionDefault
statusYes
adminTokenNo
customerIdYes

TDQS

B3.1/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With zero annotations, the description must carry the full behavioral burden, and it does disclose the two most important traits: this is a mutation and it requires admin scope. It says nothing about reversibility (e.g., whether archived is terminal), side effects such as revoked access on suspension, idempotency, or error behavior, which are the remaining gaps for a write tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two short sentences with no filler, and the core operation is front-loaded ahead of the mutation/auth caveat. Efficient, though the parenthetical auth note is slightly compressed rather than fully stated.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a three-parameter mutation with no annotations, no output schema, and 0% schema description coverage, the definition is too thin: one required credential parameter is entirely undocument and status-transition consequences are unstated. What is present is accurate but does not cover enough for an agent to act confidently.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate for all three parameters. It covers customerId ("customer UUID") and status ("account status") at a bare level, but adds no meaning about the active/suspended/archived enum semantics or allowed transitions, and never mentions the adminToken credential at all.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description pairs a specific verb and resource ("Updates account status") with the identifier it acts on (a customer UUID), so the agent knows the exact operation without opening the schema. It does not explicitly name the sibling get_customer_metrics, but the read-versus-write distinction is obvious from "Mutation".

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

"Requires Admin Scope" gives an actionable prerequisite for calling the tool, which is real usage context. However, there is no guidance on when to choose this over the sibling tool, no mention of permitted status transitions, and no indication of when NOT to change a status.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 2 tool updatesv1.0.0
    • First observedget_customer_metrics
    • First observedupdate_customer_status

TDQS

B3.2/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have clearly distinct purposes: one read-only metrics retrieval and one admin-scoped customer status mutation. An agent can easily tell them apart by action and resource.

Naming Consistency5/5

Both tools follow a consistent snake_case verb_noun pattern: get_customer_metrics and update_customer_status. The naming is predictable and readable.

Tool Count3/5

Two tools is thin for a server named supabase-secure, even if each tool is meaningful. It feels like a narrow slice of a broader secure customer-management surface.

Completeness3/5

The surface covers customer metrics retrieval and status updates but lacks obvious related operations such as listing customers, getting a customer, reading current status, or creating/deleting customer records. These gaps could force agents into dead ends.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to safely interact with Supabase through read-only and gated-write tools, with bounded queries, allowlists, and explicit project targeting.
    -
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to safely query PostgreSQL by intercepting and auditing every generated SQL statement before it reaches the database, blocking destructive commands like DROP/TRUNCATE, unbounded DELETE/UPDATE statements, stacked queries, and SQL injection probes. It exposes tools for validating query safety and enforcing a strict read-only (SELECT/EXPLAIN) policy.
    MIT
  • A
    license
    A
    quality
    A
    maintenance
    Enables AI agents to query PostgreSQL databases securely with read-only defaults, PII masking, rate limiting, and human-approved, expiring mutation tokens.
    9
    1
    Apache 2.0
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to query Postgres, BigQuery and DuckDB read-only through policy-checked SQL, with AST-based guards that refuse writes and dangerous functions, column masking on the way out, and an audit log of every query. Also exposes schema browsing and query-planning tools so agents can see allowed tables, columns and costs before running anything.
    MIT