logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

supabase-mcp-handler

A specialized Model Context Protocol (MCP) server designed to facilitate secure interaction with Supabase environments. It enables IDEs to execute PostgreSQL statements, manage database schema evolution, interface with the Supabase Management API, and leverage the Auth Admin SDK, all underpinned by a multi-layered safety framework.

Author

supabase-mcp-handler logo

alexander-zuev

Apache License 2.0

Quick Info

GitHub GitHub Stars 802
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

supabasedatabasescloudsupabase managementmanage supabasesupabase databases

PostgreSQL Query Handler for Supabase | MCP Server

🎉 Significant adoption demonstrated by over 17k PyPI installations and nearly 30k downloads via Smithery.ai. This project has been a rewarding endeavor! My sincere gratitude to all users over the preceding months. I trust it has served your workflow well. Given the release of the official Supabase MCP server implementation by the community (link to official repo), I am formally ceasing active maintenance on this repository. The community-backed version matches and extends features, with ongoing development planned. Please transition to that solution!

The Query Handler is an open-source MCP backend facilitating safe execution of SQL, schema modifications, calls to the Supabase Management API, and utilization of the Auth Admin SDK, enforced by integrated security protocols.

PyPI version CI Status Code Coverage Python 3.12+ uv package manager PyPI Downloads Smithery.ai Downloads MCP Server License


Contents

SetupCapabilitiesSupportRevisions

Core Functionality

  • 🖥️ Protocol compliant with Cursor, Windsurf, Cline, and other MCP clients supporting the stdio communication standard.
  • 🔒 Granular control over SQL execution authorization: read-only versus read/write permissions.
  • 🧐 Runtime validation of SQL text, including severity scoring for potential risks.
  • 🛡️ Implementation of a three-tiered security enforcement mechanism for database modifications: safe, write-enabled, and high-impact/destructive.
  • 🔁 Reliable management of database transactions across both direct and connection-pooled links.
  • 💾 Automatic tracking and cataloging of database schema modifications.
  • ⚙️ Provisioning of tools to interact with the Supabase Project Management API.
  • 🧑‍🔧 Tools enabling interaction with Supabase Auth functions via the Admin SDK methods.
  • 🛠️ Pre-packaged utilities designed to enhance client interoperability (Cursor & Windsurf).
  • 📦 Effortless initial deployment and environment setup using Python ecosystem tools (uv, pipx, etc.).

Setup Guide

Prerequisites

Your operating system must satisfy the following minimum requirement: - Python version 3.12 or newer.

If leveraging the uv toolchain for installation, verify its presence via the official installation documentation.

PostgreSQL Dependencies

This MCP handler no longer requires a local PostgreSQL installation, as asyncpg dependency avoids reliance on PostgreSQL development headers.

However, if running a local Supabase stack, PostgreSQL remains necessary:

macOS bash brew install postgresql@16

Windows - Obtain and install PostgreSQL 16+ from https://www.postgresql.org/download/windows/ - During setup, confirm selection of both "PostgreSQL Server" and "Command Line Tools"

Phase 1. Installation

Package installation capability was introduced in version v0.2.0. Deploy the server using your preferred Python package manager:

bash

If pipx is available (recommended approach)

pipx install supabase-mcp-server

If uv is installed

uv pip install supabase-mcp-server

pipx is favored due to its isolation of package environments.

Alternatively, manual deployment involves cloning the repository and executing pipx install -e . from the root directory.

Installing from Source

For modification or local testing: bash uv venv

On Mac/Linux

source .venv/bin/activate

On Windows

.venv\Scripts\activate

Install package in editable mode

uv pip install -e .

Installation via Smithery.ai

Detailed instructions for integrating this handler with Smithery.ai clients can be found here.

Phase 2. Configuration Parameters

To establish connectivity to your Supabase instance and enable API/SDK features, the handler requires specific setup details.

🔑 Mandatory Requirement: As of version v0.4, a QUERY_API_KEY, obtainable free of charge from thequery.dev, is required to authorize any operation.

Environmental Variables

The server references the following environment settings:

Variable Essential? Default Value Purpose
SUPABASE_PROJECT_REF Yes 127.0.0.1:54322 Your Supabase project identifier (or local host:port)
SUPABASE_DB_PASSWORD Yes postgres Database access credential
SUPABASE_REGION Yes* us-east-1 The AWS region hosting your Supabase deployment
SUPABASE_ACCESS_TOKEN No None Token for Supabase Management API authorization
SUPABASE_SERVICE_ROLE_KEY No None Service key for Auth Admin SDK access
QUERY_API_KEY Yes None Authorization key from thequery.dev (globally required)

Regional Note: Local deployments default to host/port settings. Remote connections must specify SUPABASE_REGION. Region mismatch is the primary cause of "Tenant or user not found" errors.

Connection Modalities

Database Linkage
  • Connects via the transaction pooler endpoint to your Supabase PostgreSQL instance.
  • Local development targets 127.0.0.1:54322 directly.
  • Remote projects utilize the pooled format: postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres

⚠️ Pooling Restriction: Session-level pooling is unsupported; only transaction pooling is utilized for architectural alignment with the MCP server design.

Management API Linkage
  • Needs SUPABASE_ACCESS_TOKEN.
  • Targets https://api.supabase.com. Operational exclusively with cloud-hosted Supabase projects.
Auth Admin SDK Linkage
  • Needs SUPABASE_SERVICE_ROLE_KEY.
  • Local target: http://127.0.0.1:54321. Remote target: https://[project_ref].supabase.co

Configuration Loading Hierarchy

Configuration is prioritized as follows (top being highest precedence):

  1. Environment Variables: Directly exported variables.
  2. Local Project .env File: (Active only when running directly from source code)
  3. Global Configuration File:
  4. Windows: %APPDATA%\supabase-mcp\.env
  5. macOS/Linux: ~/.config/supabase-mcp/.env
  6. Built-in Defaults: Used only for local development simulation.

⚠️ Package Install Warning: When deployed via pipx or uv, local project .env files are ignored. Rely on environment variables or the global configuration file.

Configuration Deployment Methods

Method 1: Client-Specific Environment Setup (Preferred)

Inject the necessary variables directly into your MCP client's settings (Refer to Step 3 documentation for client-specific integration).

Method 2: Centralized Global Configuration

Establish a global .env file accessible by all server instances:

bash

Create configuration directory

On macOS/Linux

mkdir -p ~/.config/supabase-mcp

On Windows (PowerShell)

mkdir -Force "$env:APPDATA\supabase-mcp"

Initialize and edit the .env file

On macOS/Linux

nano ~/.config/supabase-mcp/.env

On Windows (PowerShell)

notepad "$env:APPDATA\supabase-mcp.env"

Populate the file with your secrets:

QUERY_API_KEY=your-api-key SUPABASE_PROJECT_REF=your-project-ref SUPABASE_DB_PASSWORD=your-db-password SUPABASE_REGION=us-east-1 SUPABASE_ACCESS_TOKEN=your-access-token SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

Method 3: Per-Project Configuration (Source Install Only)

If executing from source, place a .env file matching the format above directly within your project root.

Locating Supabase Credentials

  • Project Reference: Extracted from the dashboard URL: https://supabase.com/dashboard/project/<project-ref>
  • Database Password: Set during initial project creation or found under Project Settings → Database.
  • Access Token: Generated at https://supabase.com/dashboard/account/tokens.
  • Service Role Key: Available in Project Settings → API → Project API keys.

Supported Deployment Regions

The handler is compatible with all standard Supabase cloud regions:

  • us-west-1 - US West (N. California)
  • us-east-1 - US East (N. Virginia) - Default
  • us-east-2 - US East (Ohio)
  • ca-central-1 - Canada (Central)
  • eu-west-1 - Western Europe (Ireland)
  • eu-west-2 - Western Europe (London)
  • eu-west-3 - Western Europe (Paris)
  • eu-central-1 - Central Europe (Frankfurt)
  • eu-central-2 - Central Europe (Zurich)
  • eu-north-1 - Northern Europe (Stockholm)
  • ap-south-1 - South Asia (Mumbai)
  • ap-southeast-1 - Southeast Asia (Singapore)
  • ap-northeast-1 - Northeast Asia (Tokyo)
  • ap-northeast-2 - Northeast Asia (Seoul)
  • ap-southeast-2 - Oceania (Sydney)
  • sa-east-1 - South America (São Paulo)

Restrictions

  • Self-Hosted Incompatibility: Exclusively designed for official Supabase.com deployments; local development is supported.
  • Connection Strings: Custom PostgreSQL connection strings are not processed.
  • Pooling: Only transaction-based pooling is supported.
  • API/SDK Features: Management API and Auth Admin SDK functionalities are disabled during local development mode.

Phase 3. Operational Use

This handler is designed to integrate with any MCP client supporting the stdio protocol. Verified compatibility exists with: - Cursor - Windsurf - Cline - Claude Desktop

Furthermore, Smithery.ai allows installation of this server across numerous supported clients.

Refer to the specific client guides below for connection procedures.

Cursor Integration

Navigate to Settings -> Features -> MCP Servers and define a new entry: bash

Use any identifier name

name: supabase type: command

If installed via pipx

command: supabase-mcp-server

If installed via uv

command: uv run supabase-mcp-server

Fallback: Use the full absolute path (recommended for reliability)

command: /path/to/your/supabase-mcp-server # Determine path via 'which supabase-mcp-server' (Unix) or 'where supabase-mcp-server' (Win)

Success is indicated by a green connection indicator and display of the server's available tool count. Cursor success visualization

Windsurf Integration

In Cascade -> Click the wrench icon -> Configure, and populate the settings block:

{ "mcpServers": { "supabase": { "command": "/Users/username/.local/bin/supabase-mcp-server", // ADJUST PATH "env": { "QUERY_API_KEY": "your-api-key", // Required - Obtain from thequery.dev "SUPABASE_PROJECT_REF": "your-project-ref", "SUPABASE_DB_PASSWORD": "your-db-password", "SUPABASE_REGION": "us-east-1", // Optional, defaults to us-east-1 "SUPABASE_ACCESS_TOKEN": "your-access-token", // Optional, for Management API "SUPABASE_SERVICE_ROLE_KEY": "your-service-role-key" // Optional, for Auth Admin SDK } } } }

A green indicator and an active 'supabase' server entry confirm correct setup. Windsurf success visualization

Claude Desktop Setup

Claude Desktop uses a JSON structure for MCP server definitions. Follow these steps for configuration:

  1. Locate Executable Path (Essential): bash # macOS/Linux which supabase-mcp-server

# Windows where supabase-mcp-server

Copy the resulting absolute path (e.g., /Users/username/.local/bin/supabase-mcp-server).

  1. Configure in Claude Desktop:
  2. Access Settings → Developer -> Edit Config MCP Servers.
  3. Insert the following JSON structure, ensuring path replacement:

{ "mcpServers": { "supabase": { "command": "/full/path/to/supabase-mcp-server", // REPLACE WITH ACTUAL PATH "env": { "QUERY_API_KEY": "your-api-key", "SUPABASE_PROJECT_REF": "your-project-ref", "SUPABASE_DB_PASSWORD": "your-db-password", "SUPABASE_REGION": "us-east-1", "SUPABASE_ACCESS_TOKEN": "your-access-token", "SUPABASE_SERVICE_ROLE_KEY": "your-service-role-key" } } } }

⚠️ Claude Path Note: Unlike other clients, Claude Desktop mandates the absolute path to the binary; using just the command name will cause a "spawn ENOENT" failure.

Success is verified by the listing of the Supabase handler in Claude Desktop's available servers. Claude success visualization

Cline Setup

Cline utilizes a similar JSON configuration method within VS Code:

  1. Determine Absolute Executable Location (Crucial Step): bash # macOS/Linux which supabase-mcp-server

# Windows where supabase-mcp-server

Save this full path.

  1. Configure in Cline:
  2. Open Cline sidebar in VS Code and navigate to the "MCP Servers" panel.
  3. Select "Configure MCP Servers" to open cline_mcp_settings.json.
  4. Append the following configuration block:

{ "mcpServers": { "supabase": { "command": "/full/path/to/supabase-mcp-server", // Replace with path from step 1 "env": { "QUERY_API_KEY": "your-api-key", "SUPABASE_PROJECT_REF": "your-project-ref", "SUPABASE_DB_PASSWORD": "your-db-password", "SUPABASE_REGION": "us-east-1", "SUPABASE_ACCESS_TOKEN": "your-access-token", "SUPABASE_SERVICE_ROLE_KEY": "your-service-role-key" } } } }

Verification occurs when a green indicator appears next to the entry in the Cline panel, accompanied by a "supabase MCP server connected" status message at the panel's footer. Cline success visualization

Debugging Guidance

If connectivity issues arise, consult these diagnostic steps: - Direct Execution Test: Run supabase-mcp-server directly in your shell. If it fails here, the installation or path is faulty. - Path Validation: If the server launches but the IDE reports no tools, verify the command path used in the client configuration matches the output of which/where. - "No tools found" Resolution: This typically means the client cannot spawn the executable. Use the full path outputted by which supabase-mcp-server (e.g., /Users/user/.local/bin/supabase-mcp-server). - Configuration Source Check: Ensure required environment variables are established either in the client configuration, or persistently in the global location (~/.config/supabase-mcp/.env on Unix-like systems, or %APPDATA%\supabase-mcp\.env on Windows). - Log Review: Detailed operational records are stored locally for deep inspection: - Unix Logs: ~/.local/share/supabase-mcp/mcp_server.log - Windows Logs: %USERPROFILE%\.local\share\supabase-mcp\mcp_server.log - Review via terminal: bash # Unix cat ~/.local/share/supabase-mcp/mcp_server.log

# PowerShell
Get-Content "$env:USERPROFILE\.local\share\supabase-mcp\mcp_server.log"

Submit an issue if these steps fail to resolve your problem.

MCP Inspector Utility

For advanced debugging, especially when running from source, the supabase-mcp-inspector command launches a dedicated diagnostic instance. Combining inspector output with the server logs provides comprehensive insight into handler behavior.

📝 Note: supabase-mcp-inspector functionality when called via package manager is currently under validation and scheduled for correction in an upcoming release.

Capability Summary

Database Interaction Tools

Since v0.3+, the handler offers extensive database management features with mandatory safety layers:

  • SQL Execution: Run PostgreSQL commands, preceded by a risk evaluation.
  • Security Tiers:

    • safe: Strictly read-only commands (SELECT). Always permitted.
    • write: Data manipulation (INSERT, UPDATE, DELETE). Requires enabling 'unsafe' mode.
    • destructive: Structural changes (DROP, CREATE). Requires 'unsafe' mode AND secondary confirmation.
  • Analysis & Validation:

  • Employs pglast for authoritative SQL parsing, providing precise feedback on necessary security context.

  • Schema Version Control:

  • All schema-modifying commands trigger automatic creation of versioned migration scripts.
  • Script names are auto-generated based on operation type and target objects.

  • Security Enforcement:

  • Default operating mode is SAFE (read-only only).
  • All database interactions run within ACID-compliant transactions via asyncpg.
  • High-impact actions mandate a two-stage user consent.

  • Exposed Functions:

  • get_schemas: Schema listing, including object counts and storage footprint.
  • get_tables: Metadata retrieval for tables, views, and foreign tables.
  • get_table_schema: Detailed view of table structure, keys, and relational constraints.
  • execute_postgresql: General-purpose SQL execution against the database.
  • confirm_destructive_operation: Executes high-risk commands post-validation.
  • retrieve_migrations: Fetches migration history with filtering.
  • live_dangerously: Toggles the server's operational security posture between SAFE and UNSAFE.

Management API Interaction Tools

Introduced in v0.3.0, this allows secure, controlled access to Supabase's project control plane:

  • Available Functions:
  • send_management_api_request: Arbitrary requests to the API with automated project reference injection.
  • get_management_api_spec: Retrieves an enhanced API blueprint enriched with explicit safety metadata.
    • Supports targeted queries by API domain, specific path/method, or full enumeration.
    • Includes risk ratings for every known endpoint.
    • Details required parameters and expected response structures.
    • Optimized for use by Large Language Models to understand API capabilities.
  • get_management_api_safety_rules: Lists all defined safety boundaries with accessible explanations.
  • live_dangerously: Toggles the security context for API calls.

  • Security Governance:

  • Utilizes the same unified safety manager as database tools.
  • Operations are classified by risk:
    • safe: Read operations (GET). Permitted by default.
    • unsafe: State-modifying operations (POST, PUT, PATCH, DELETE). Require unsafe mode.
    • blocked: Critical operations (e.g., project deletion). Never permitted.
  • Default mode blocks accidental state changes.
  • Safety rules are enforced via specific path pattern matching.

Constraint: Management API tools are functional only when targeting remote, cloud-based Supabase projects; they are inoperative against local setups.

Auth Administration Tools

Initially conceived as a broad SDK wrapper, focus narrowed to Auth administration due to frequent manual user creation needs. This streamlines test user generation.

Version v0.3.6 enables direct invocation of Supabase Auth Admin methods via the underlying Python SDK: - Includes: - get_auth_admin_methods_spec: To fetch documentation for all accessible Auth Admin calls. - call_auth_admin_method: To execute specific Auth Admin functions with correct parameter mapping. - Supported Operations: - get_user_by_id: Fetch user details by ID. - list_users: Paged retrieval of user accounts. - create_user: Provision a new user entity. - delete_user: Remove a user by ID. - invite_user_by_email: Trigger user invitation flow. - generate_link: Create authentication URLs (magic link, etc.). - update_user_by_id: Modify existing user metadata. - delete_factor: Remove user security factors (Note: SDK dependency status may vary).

Rationale: SDK vs. Raw SQL for Auth

Leveraging the Auth Admin SDK provides substantial benefits over crafting raw SQL against auth schemas: - Enhanced Capabilities: Supports features impossible via SQL (e.g., issuing secure invite links, MFA management). - Reliability: Higher confidence in outcomes compared to manual SQL construction on sensitive auth schemas. - Usability: Provides intuitive, validated methods.

  • Return Structure:
    • Methods return structured Python objects, allowing attribute access via dot notation (e.g., user.id).
  • Known Limitations & Edge Cases:
    • UUID Format: User ID methods strictly enforce valid UUID format.
    • Email Configuration: Invite/link generation functions require transactional email services to be active in the Supabase project.
    • Link Specificity: signup links are for new entities; magiclink and recovery links require pre-existing user records.
    • Error Detail: Errors presented are derived directly from the Supabase backend API responses.
    • Method Parity: Not all Management API endpoints may have direct SDK equivalents (e.g., delete_factor implementation status).

System Logs and Telemetry Access

The server exposes tools for reviewing logs and analytical data across various Supabase components, centralizing troubleshooting:

  • Primary Tool: retrieve_logs - Provides access to operational records from any integrated Supabase service.

  • Log Sources Available:

  • postgres: Database engine logs.
  • api_gateway: Ingress request logs.
  • auth: User authentication event streams.
  • postgrest: Logs from the RESTful API layer.
  • pooler: Connection pooling activity.
  • storage: Object storage interactions.
  • realtime: WebSocket connection and event logs.
  • edge_functions: Serverless function execution traces.
  • cron: Scheduled task execution reports.
  • pgbouncer: PgBouncer connection manager activity.

  • Filtering Capabilities: Supports temporal filtering, text search, attribute filtering, and direct custom SQL queries against log data.

This consolidation streamlines diagnostics across the entire Supabase application stack.

Automated Schema Change Cataloging

In adherence to the principle, "With great power comes great responsibility," the integration of execute_postgresql and the live_dangerously toggle necessitates robust safeguards against accidental data destruction. Since v0.3.8, the server enforces: - Automatic capture of migration scripts for all data-modifying and structure-altering database executions. - Refined security evaluation classifying operations: - safe type: Always permitted (e.g., SELECT). - write type: Requires the user to explicitly enable 'write' mode. - destructive type: Requires 'write' mode AND a mandatory two-step user confirmation (for clients that do not auto-execute tool calls).

Unified Safety Context (Since v0.3.8)

Safety Mode has been harmonized across all server subsystems (DB, API, SDK) via a singular management entity, guaranteeing predictable risk assessment and control application throughout the server's exposed interface.

All functional invocations are mapped to standardized risk tiers: - Low Risk: Non-modifying, read-only activities (SELECTs, GET API calls). - Medium Risk: Data modification without structural change (INSERT/UPDATE/DELETE, most PUT/POST API calls). - High Risk: Operations impacting structure or risking data loss (DROP/TRUNCATE, certain destructive API endpoints). - Extreme Risk: Actions with catastrophic potential (e.g., project deletion). These are permanently inhibited.

Control enforcement based on tier: - Low: Always permitted. - Medium: Requires activation of 'unsafe' mode. - High: Requires 'unsafe' mode AND explicit, per-operation approval. - Extreme: Always denied.

Confirmation Protocol Mechanics

Any function categorized as High Risk will be intercepted, even if the server is operating in unsafe mode. Visualization of High-Risk Interception Execution of these operations is contingent upon explicit user consent provided through the client interface. Visualization of Required Explicit Approval

Revision History

  • 📦 Package installation streamlined via standard managers - ✅ (v0.2.0)
  • 🌎 Added support for specifying diverse Supabase hosting regions - ✅ (v0.2.2)
  • 🎮 Integrated secure interaction with the Supabase Management API layer - ✅ (v0.3.0)
  • 👷‍♂️ Introduced protected execution of read/write SQL operations - ✅ (v0.3.0)
  • 🔄 Enhanced transactional integrity for pooled and direct database links - ✅ (v0.3.2)
  • 🐍 Incorporated Python SDK methods and object structures - ✅ (v0.3.6)
  • 🔍 Strengthened validation mechanisms for inbound SQL statements ✅ (v0.3.8)
  • 📝 Implemented automatic cataloging for all database modifications ✅ (v0.3.8)
  • 📖 Significantly enriched knowledge base and tool definitions for the API specification ✅ (v0.3.8)
  • ✍️ Improved consistency across migration-related tooling for better database version control practices ✅ (v0.3.10)
  • 🥳 Official launch of Query MCP (v0.4.0)

Consult this GitHub discussion for a more comprehensive future development trajectory.

Repository Popularity

Star History Chart


Best regards! ☺️

WIKIPEDIA CONTEXT: Cloud computing is defined as "a paradigm for enabling network access to a scalable and elastic pool of shareable physical or virtual resources with self-service provisioning and administration on-demand," according to ISO standards. Colloquially, this is referred to simply as "the cloud".

== Essential Elements == In 2011, the U.S. National Institute of Standards and Technology (NIST) established five foundational qualities for cloud systems. These are precisely defined as follows:

Self-Service on Demand: A consumer can instantaneously provision computational resources, such as processing capacity or storage space, automatically, without requiring direct intervention from the service provider. Ubiquitous Network Access: Resources are accessible via the network utilizing standard protocols compatible with diverse client platforms (mobile devices, laptops, etc.). Resource Pooling: The vendor's infrastructure capacity is consolidated to serve multiple clients via a multi-tenant architecture, with resources dynamically allocated based on fluctuating demand. Rapid Scalability: Capabilities can be provisioned or de-provisioned elastically, often automatically, to scale capacity up or down instantly in response to load variations. From the user's perspective, available capacity appears virtually limitless. Measured Usage: Cloud environments inherently feature metering capabilities at various service layers (storage, processing, data transfer), enabling usage monitoring, control, and transparent reporting for both the provider and the consumer. By 2023, the International Organization for Standardization (ISO) had further developed and augmented this characteristic set.

== Origins ==

The conceptual groundwork for cloud computing dates back to the 1960s with the popularization of time-sharing concepts via remote job entry (RJE). During this period, the dominant operational model centered around centralized data centers where users submitted batch jobs to human operators managing mainframes. This era was characterized by pioneering efforts to maximize the accessibility and utilization of costly, large-scale computational assets through time-sharing methods. The specific 'cloud' graphic metaphor for abstracted, virtualized services emerged around 1994, employed by General Magic to denote the operational space for mobile agents within their Telescript framework. The attribution for popularizing this metaphor is generally given to David Hoffman, a communications specialist at General Magic, who based it on its existing use in telecommunications diagrams. The term 'cloud computing' gained broader recognition in 1996 following internal documentation at Compaq Computer Corporation detailing future internet computing strategies, reflecting their vision for extensive, interconnected infrastructure.

See Also

`