supa-mgmt-query-engine
A Model Context Protocol (MCP) server designed for comprehensive management of Supabase environments. It facilitates secure execution of SQL against the database, orchestration of schema migrations, and interaction with the Supabase Management API and Auth Admin SDK, all overlaid with robust, multi-layered security mechanisms.
Author

alexander-zuev
Quick Info
Actions
Tags
Database Interaction & Control Hub for Supabase (MCP)
🌅 Celebrating over 17,000 installs via PyPI and nearing 30,000 downloads on Smithery.ai — this project was a rewarding endeavor! 🥳 My sincere thanks to everyone who adopted and used this server over the last several months. I trust it proved valuable. Given the recent release of the official MCP server by the Supabase community (link to official repo), I am retiring active maintenance on this iteration. The official counterpart is rapidly gaining features and is the recommended path forward. Please migrate your usage there!
This open-source MCP facilitator empowers your IDE to securely dispatch SQL commands, govern schema evolution, invoke the Supabase Management API, and leverage the Auth Admin SDK, all while enforcing crucial safety protocols.
Contents
Setup Guide • Capabilities Summary • Debugging Tips • Release History
🌟 Core Functionality Highlights
- 💻 Compatibility across Cursor, Windsurf, Cline, and other clients adhering to the
stdiocommunication protocol. - 🔐 Granular control over read-only versus read-write execution contexts for SQL operations.
- 🔍 Dynamic runtime validation of SQL statements accompanied by a corresponding risk assessment score.
- 🛡️ A comprehensive three-level defense system governing SQL execution: benign, modification, and destructive.
- 🔄 Reliable management of database sessions using transaction pooling for both dedicated and shared connections.
- 📝 Automated tracking and versioning for all database schema modifications.
- 💻 Interface with Supabase Project Administration via the dedicated Management API client.
- 🧑💻 Administration of user accounts and authentication settings using the integrated Supabase Auth Admin SDK (Python based).
- 🔨 Provision of auxiliary utilities to optimize interaction between clients (Cursor & Windsurf) and the MCP layer.
- 📦 Extremely straightforward deployment and initialization using standard Python toolchains (uv, pipx, etc.).
🚀 Initial Setup
Prerequisites
Your operating system must have the following software installed: - Python interpreter version 3.12 or newer.
If utilizing the uv package manager, confirm its presence via official installation instructions.
Database Dependency Note
The core MCP server itself no longer mandates a local PostgreSQL installation because it now relies on asyncpg which omits the need for PostgreSQL development headers.
However, if you run a local Supabase stack, you will still require PostgreSQL:
MacOS bash brew install postgresql@16
Windows - Obtain and install PostgreSQL 16+ from https://www.postgresql.org/download/windows/ - Ensure both "PostgreSQL Server" and "Command Line Tools" are selected during installation.
Phase 1. Installation
Since version 0.2.0, package installation is the primary method. Use your preferred Python package manager:
bash
If pipx is available (highly recommended)
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 installation involves cloning the repository and executing pipx install -e . from the root directory.
Building from Source
For local testing or development purposes: bash uv venv
For Unix-like systems
source .venv/bin/activate
For Windows (Cmd/PowerShell)
.venv\Scripts\activate
Install package in editable mode
uv pip install -e .
Installation via Smithery.ai
Guidance on connecting your Smithery.ai clients to this operational server can be found here.
Phase 2. Configuration Details
To function correctly, the Supabase MCP server necessitates configuration credentials for connecting to your database, accessing the Management API, and utilizing the Auth Admin SDK. This section itemizes all configurable parameters and setup procedures.
🔑 Mandatory Requirement: As of version 0.4, operation requires a valid API key obtainable at no cost from [thequery.dev] to enable server functionality.
Environmental Variables
Configuration relies on the following environment settings:
| Setting | Required | Default Value | Purpose |
|---|---|---|---|
SUPABASE_PROJECT_REF |
Essential | 127.0.0.1:54322 |
The unique identifier for your Supabase project (or local host:port address) |
SUPABASE_DB_PASSWORD |
Essential | postgres |
The credential for database access |
SUPABASE_REGION |
Required* | us-east-1 |
The AWS region hosting your Supabase deployment |
SUPABASE_ACCESS_TOKEN |
Optional | None | Token for authenticated access to the Supabase Management API |
SUPABASE_SERVICE_ROLE_KEY |
Optional | None | Key required for invoking the Auth Admin SDK features |
QUERY_API_KEY |
Essential | None | The requisite API key obtained from thequery.dev |
Local Default Note: Defaults are tailored for local Supabase development environments. For remote deployments, you must supply values for
SUPABASE_PROJECT_REFandSUPABASE_DB_PASSWORD.🚨 CRITICAL WARNING: When targeting remote Supabase instances, accurately setting
SUPABASE_REGIONis paramount. Connection failures, especially "Tenant or user not found" errors, are almost always traceable to a region mismatch with your actual project location. Verify this in your Supabase dashboard under Project Settings.
Connection Modalities
Database Linkage
- The server establishes its PostgreSQL link via the designated transaction connection pooler endpoint.
- Local setups default to a direct link:
127.0.0.1:54322. - Remote projects utilize the pooled endpoint format:
postgresql://postgres.[ref]:[pass]@aws-0-[region].pooler.supabase.com:6543/postgres
⚠️ Pooling Limitation: The server strictly enforces transaction pooling; session-based connections are unsupported due to architectural constraints with the MCP framework.
Management API Linkage
- Necessitates the presence of
SUPABASE_ACCESS_TOKEN. - Connects against the official endpoint:
https://api.supabase.com. - Operational only with externally hosted Supabase instances (not applicable to local setups).
Auth Administrator SDK Linkage
- Requires the setting of
SUPABASE_SERVICE_ROLE_KEY. - For local instances, it targets:
http://127.0.0.1:54321. - For remote projects, the target is:
https://[project_ref].supabase.co.
Configuration Loading Hierarchy
Configuration settings are prioritized as follows (highest precedence first):
- Environment Variables: Values defined directly in the execution environment.
- Local .env File: A
.envfile present in the current operational directory (active only when running from source). - System-Wide Configuration File:
- Windows:
%APPDATA%\supabase-mcp\.env - macOS/Linux:
~/.config/supabase-mcp/.env - Inherent Defaults: Values used for local development if no other configuration is detected.
⚠️ Package Install Caveat: If installed via
pipxoruv, environment variables sourced from a project-local.envfile will not be loaded. Rely on environment variables or the system-wide config file.
Configuration Setup Methods
Method 1: Client-Specific Environment Setup (Recommended)
Define the necessary environment variables directly within your MCP client's configuration interface (refer to Step 3 guides for client specifics). This method keeps credentials proximal to the client settings.
Method 2: Global Configuration File
Establish a persistent .env file accessible system-wide for all MCP server invocations:
bash
Create directory structure
On macOS/Linux
mkdir -p ~/.config/supabase-mcp
On Windows (PowerShell)
mkdir -Force "$env:APPDATA\supabase-mcp"
Open/Create the environment file
On macOS/Linux
nano ~/.config/supabase-mcp/.env
On Windows (PowerShell)
notepad "$env:APPDATA\supabase-mcp.env"
Populate the file with your parameters:
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: Project-Scoped Configuration (Source Install Only)
When executing the server directly from source code, a .env file placed in the root project folder will be honored, using the same key/value structure.
Locating Supabase Credentials
- Project Reference: Extracted from the dashboard URL:
https://supabase.com/dashboard/project/<project-ref>. - Database Password: Established during initial project setup or found under Project Settings → Database.
- Access Token: Generated via your account tokens page: https://supabase.com/dashboard/account/tokens.
- Service Role Key: Accessible in Project Settings → API → Project API keys.
Supported Geographical Regions
This server supports all official Supabase hosting zones:
us-west-1- West US (N. California)us-east-1- East US (N. Virginia) - Default settingus-east-2- East US (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)
Operational Constraints
- Self-Hosting Incompatibility: Limited strictly to official Supabase.com cloud instances and local test environments.
- Connection String Policy: Custom PostgreSQL connection strings are explicitly disallowed.
- Pooling Mode: Only transaction pooling is supported for database connectivity.
- API/SDK Features: Management API and Auth Admin features are non-functional when connected to local setups.
Phase 3. Operational Guide
Compatibility exists with any MCP client supporting the standard stdio channel. This server has been verified functional with:
- Cursor
- Windsurf
- Cline
- Claude Desktop
Furthermore, smithery.ai offers streamlined deployment for this server across its supported clients.
Consult the client-specific integration guides below:
Cursor Integration
Navigate to Settings → Features → MCP Servers, then introduce a new entry using this structure: bash
Arbitrary name assignment
name: supabase type: command
If installed via pipx
command: supabase-mcp-server
If installed via uv
command: uv run supabase-mcp-server
If preceding commands fail, use the absolute execution path (preferred)
command: /full/path/to/supabase-mcp-server # Determine path via 'which supabase-mcp-server' (Unix) or 'where supabase-mcp-server' (Windows)
Success is indicated by a green connection indicator and a count of exposed server capabilities.
Windsurf Integration
In Cascade settings, access the configuration panel (hammer icon), and populate the following JSON:
{ "mcpServers": { "supabase": { "command": "/Users/username/.local/bin/supabase-mcp-server", // Update this path "env": { "QUERY_API_KEY": "your-api-key", // Necessary - 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 } } } }
Verification involves observing the green status indicator and the active listing of the Supabase server.
Claude Desktop Integration
Claude Desktop utilizes JSON configuration for MCP linkage. Follow these steps for Supabase integration:
- Locate the Executable Path (Crucial step): bash # On macOS/Linux which supabase-mcp-server
# On Windows where supabase-mcp-server
Save the returned absolute path (e.g., /Users/username/.local/bin/supabase-mcp-server).
- Configure in Claude Desktop:
- Access Settings → Developer -> Edit Config MCP Servers.
- Insert the following JSON structure:
{ "mcpServers": { "supabase": { "command": "/full/path/to/supabase-mcp-server", // Substitute with actual path from step 1 "env": { "QUERY_API_KEY": "your-api-key", // Required "SUPABASE_PROJECT_REF": "your-project-ref", "SUPABASE_DB_PASSWORD": "your-db-password", "SUPABASE_REGION": "us-east-1", // Defaulted "SUPABASE_ACCESS_TOKEN": "your-access-token", // Optional "SUPABASE_SERVICE_ROLE_KEY": "your-service-role-key" // Optional } } } }
⚠️ Claude Path Sensitivity: Unlike other clients, Claude Desktop demands the full, absolute path to the binary. Specifying only the command name (
supabase-mcp-server) will trigger an "spawn ENOENT" error.
Successful setup will display the Supabase MCP server in the list of active services.
Cline Integration
Cline configuration mirrors the JSON approach. To integrate:
- Determine Absolute Path: bash # On macOS/Linux which supabase-mcp-server
# On Windows where supabase-mcp-server
Copy the resulting absolute file location.
- Update Cline Settings:
- Open Cline within VS Code.
- Navigate to the Cline sidebar's "MCP Servers" tab.
- Click "Configure MCP Servers" to open
cline_mcp_settings.json. - Integrate the configuration block:
{ "mcpServers": { "supabase": { "command": "/full/path/to/supabase-mcp-server", // Insert path from step 1 "env": { "QUERY_API_KEY": "your-api-key", // Required "SUPABASE_PROJECT_REF": "your-project-ref", "SUPABASE_DB_PASSWORD": "your-db-password", "SUPABASE_REGION": "us-east-1", // Defaulted "SUPABASE_ACCESS_TOKEN": "your-access-token", // Optional "SUPABASE_SERVICE_ROLE_KEY": "your-service-role-key" // Optional } } } }
Confirmation is marked by a green status indicator adjacent to the server in the Cline panel and a "supabase MCP server connected" status message at the bottom of the panel.
🐞 Troubleshooting Common Issues
Consult these troubleshooting guidelines:
- Installation Check: Execute supabase-mcp-server directly in your terminal to confirm the binary runs without dependency errors.
- Execution Verification: If the direct execution succeeds, the installation is sound. Connection issues usually stem from incorrect command paths provided to the IDE/client configuration.
- "No tools discovered" Error: If Cursor reports "Client closed - no tools available" despite installation:
- Use which supabase-mcp-server (Unix) or where supabase-mcp-server (Windows) to find the exact executable location.
- Replace the simple command name with this absolute path in your client settings (e.g., use /Users/user/.local/bin/supabase-mcp-server instead of just supabase-mcp-server).
- Credential Resolution: Ensure secrets are set either in the client's environment configuration or within the global .env file located at ~/.config/supabase-mcp/.env (Unix) or %APPDATA%\supabase-mcp\.env (Windows).
- Log Examination: Detailed operational logs are written to assist diagnostics:
- Path:
- macOS/Linux: ~/.local/share/supabase-mcp/mcp_server.log
- Windows: %USERPROFILE%\.local\share\supabase-mcp\mcp_server.log
- Viewing logs:
bash
# On macOS/Linux
cat ~/.local/share/supabase-mcp/mcp_server.log
# On Windows (PowerShell)
Get-Content "$env:USERPROFILE\.local\share\supabase-mcp\mcp_server.log"
If issues persist or instructions appear inaccurate, please submit a detailed report via the issue tracker.
Integrated MCP Inspector Utility
For deep diagnostics, the MCP Inspector tool is invaluable. If built from source, execute supabase-mcp-inspector from the project root to launch an inspection instance. Combining this with log analysis provides a complete view of server activity.
📝 Note: The package-installed version of
supabase-mcp-inspectoris temporarily known to have execution instability; this will be rectified in the subsequent release cycle.
🗺️ Feature Set Deep Dive
Database Querying Tools
Since v0.3+, the server offers robust database administration features protected by integrated safety mechanisms:
- SQL Command Dispatch: Execution of PostgreSQL statements complete with explicit risk classification.
-
Three-Stage Safety Framework:
safe: Strictly read-only actions (SELECT). Always permissible.write: Data manipulation (INSERT, UPDATE, DELETE). Requires elevation to unsafe mode.destructive: Structural changes (DROP, CREATE). Demands unsafe mode plus explicit user confirmation.
-
Semantic Validation: Utilizes the
pglastPostgreSQL parser for precise analysis, providing actionable feedback regarding required safety postures. -
Automated Schema Versioning: All DDL operations automatically trigger the creation of versioned migration scripts, named contextually based on the action and target.
-
Safety Enforcement: The default SAFE context blocks all state-altering calls. All commands execute within an atomic transaction via
asyncpg. - Tool Manifest:
get_schemas: Enumerates schemas, including size metrics and table counts.get_tables: Lists base tables, foreign tables, and defined views along with associated metadata.get_table_schema: Retrieves the comprehensive definition of a specific table (columns, constraints, relations).execute_postgresql: Runs raw SQL against the connected database.confirm_destructive_operation: Executes high-consequence commands following user validation.retrieve_migrations: Fetches recorded migration scripts, supporting filtering and pagination.live_dangerously: Toggles the operational safety context between benign and elevated modes.
Management API Interface Tools
Starting with v0.3.0, the server provides secure pathways to the Supabase Management API, governed by consistent safety rules:
- Available Tools:
send_management_api_request: For sending generic requests to the Management API, automatically injecting the necessary project reference.get_management_api_spec: Retrieves an enhanced API specification detailing safety tiers for every endpoint.- Supports retrieval filtered by domain, specific path/method, or the complete catalog.
- Includes explicit risk assessment data for each entry.
- Maps out precise parameter needs and expected response structures.
- Designed to improve LLM comprehension of the Management API's scope.
get_management_api_safety_rules: Accesses all configured safety criteria with plain-language explanations.-
live_dangerously: Toggles the overarching operational safety level. -
Safety Policy: Applies the identical safety manager used for database access, ensuring uniformity.
- Risk Categorization:
safe: Read-only interactions (GET). Always permitted.unsafe: State-altering actions (POST, PUT, PATCH, DELETE). Requires unsafe mode activation.blocked: Actions with existential risk (e.g., project deletion). Never permitted.
- The default configuration mandates safe mode, preventing accidental state modifications.
- Rules are applied via path-based pattern matching for precision.
Crucial Note: Management API functionalities are exclusively functional against projects hosted on Supabase.com; they are non-operational in local development environments.
Auth Administration Capabilities
My motivation for integrating Auth Admin SDK methods arose from the frequent need to manually provision and manage test user accounts, a process often error-prone and tedious. Now, instructing Cursor to create a test user is instantaneous. Refer to the official Auth Admin SDK documentation for the full method set.
Since v0.3.6, the server allows direct invocation of Supabase Auth Admin functions via the Python SDK:
- Includes:
- get_auth_admin_methods_spec to pull documentation for all exposed Auth Admin endpoints.
- call_auth_admin_method for direct execution with managed parameter mapping.
- Implemented Methods:
- get_user_by_id: Fetches user details by identifier.
- list_users: Retrieves user records with pagination support.
- create_user: Provisions a new user entity.
- delete_user: Erases a user record by ID.
- invite_user_by_email: Dispatches an invitation URL to a specified email address.
- generate_link: Creates specialized email links for login or recovery.
- update_user_by_id: Modifies user attributes based on ID.
- delete_factor: Revokes a user's registered authentication factor (currently noted as an SDK limitation).
Rationale for SDK vs. Raw SQL Auth Access
Employing the dedicated Auth Admin SDK offers substantial benefits over crafting direct SQL against the auth schema:
- Extended Scope: Enables critical functions like user invitations and MFA management that SQL cannot easily replicate.
- Reliability: Provides a more dependable interface compared to writing and validating raw SQL for sensitive auth tables.
- Usability: Features clearly defined methods, built-in validation, and superior error reporting.
- Output Format: Methods yield structured Python objects, allowing clean dot notation access (e.g.,
user.id) instead of dictionary indexing (user["id"]). - Constraints & Gotchas:
- UUID Format: Many ID-dependent calls strictly enforce valid UUID format; deviations result in specific validation failures.
- Email Setup: Functions like
invite_user_by_emailrequire that email transmission services are properly configured in your Supabase project settings. - Link Specificity: Generated links vary;
signuplinks do not require prior user existence, whereasmagiclinkandrecoverylinks do. - Error Reporting: The server surfaces detailed API errors from Supabase, which may differ slightly from dashboard messages.
- Method Gaps: Certain documented API methods, like
delete_factor, might not yet be fully realized within the Python SDK wrapper.
System Monitoring (Logs & Telemetry)
This server grants unified access to telemetry streams across all Supabase components, streamlining monitoring and issue resolution:
-
Tool:
retrieve_logs- Provides gateway access to logs from any connected Supabase service. -
Log Streams Available:
postgres: Core database server activity.api_gateway: HTTP request routing logs.auth: User authentication event records.postgrest: Logs from the primary RESTful API layer.pooler: Connection pooling statistics.storage: Object storage (S3) transaction records.realtime: WebSocket subscription stream data.edge_functions: Serverless function invocation traces.cron: Logs for scheduled job execution.pgbouncer: Connection pooling transaction details.
Simplifies cross-stack debugging by eliminating the need to context-switch between various external monitoring portals.
Automated Database Change Tracking
"Power must be managed responsibly." While the execute_postgresql tool combined with the live_dangerously switch offers immense transactional power, it introduces the risk of single-prompt, irreversible structural modifications. To mitigate this inherent danger, version 0.3.8 introduced:
- Automatic generation of migration scripts for all data modification or structural changes executed against the database.
- Refined safety modes for query execution, categorized as:
- safe type: Always permitted. Covers all read-only interactions.
- write type: Requires user enablement of write mode.
- destructive type: Requires write mode enabled AND a mandatory two-step confirmation sequence for clients that do not auto-execute tool calls.
Unifying Principle: Universal Safety Manager
Beginning with release v0.3.8, the safety protocol was standardized across all integrated services (DB, API, SDK) via a singular safety manager. This ensures consistent governance and a unified control surface for security settings throughout the MCP server.
All dispatched operations (SQL, API calls, SDK invocations) are mapped to the following risk tiers:
- Low risk: Operations that query but do not alter state or structure (e.g., SELECT, GET requests).
- Medium risk: Data modification operations that do not affect schema (e.g., INSERT/UPDATE/DELETE, most idempotent API requests).
- High risk: Operations capable of structural modification or data eradication (e.g., DROP statements, DELETE API endpoints).
- Extreme risk: Actions carrying irreversible, catastrophic consequences (e.g., project deletion), which are permanently disallowed.
Control enforcement based on risk level: - Low risk: Always authorized. - Medium risk: Activation of the unsafe execution context is required. - High risk: Requires unsafe context plus explicit user-driven confirmation. - Extreme risk: Blocked by default and always blocked.
Confirmation Workflow
Any operation classified as High Risk will be halted, irrespective of the current unsafe mode setting.
Execution demands explicit, separate user approval for each such request.
🗓️ Release Chronology
- 📦 Package installation simplified via standard managers - ✅ (v0.2.0)
- 🌎 Enabled configuration for distinct Supabase geographical regions - ✅ (v0.2.2)
- 🎮 Implemented programmatic interface to Supabase Management API with safety gating - ✅ (v0.3.0)
- 👷♂️ Support for controlled read/write execution of SQL queries with layered safety features - ✅ (v0.3.0)
- 🔄 Enhanced durability for database sessions using transaction pools across connection types - ✅ (v0.3.2)
- 🐍 Added support for methods and data structures mirroring the native Python SDK capabilities - ✅ (v0.3.6)
- 🔍 Substantially improved accuracy in SQL query parsing and validation ✅ (v0.3.8)
- 📝 Introduced automatic temporal tracking for all database modifications ✅ (v0.3.8)
- 📖 Major enhancement to API specification knowledge base and associated tooling ✅ (v0.3.8)
- ✍️ Improved standardization of migration tooling for better database version control organization ✅ (v0.3.10)
- 🥳 Official v0.4.0 release announcement (Query MCP)
For forward-looking development plans, consult this GitHub discussion thread.
Star Trajectory
Keep coding! ☺️
WIKIPEDIA NOTE: XMLHttpRequest (XHR) represents an interface, implemented as a JavaScript object, whose member functions facilitate the transmission of HTTP requests from a web browser to a server. These methods enable browser-based applications to dispatch server inquiries post-page-load and subsequently receive data back. XHR is foundational to the concept of Ajax programming. Before Ajax became prevalent, server interaction relied primarily on hyperlink navigation and form submissions, processes which typically resulted in a complete page refresh.
