Supabase MCP server

Provides a secure bridge to Supabase databases, enabling schema exploration, relationship understanding, and safe query execution while enforcing security measures like query validation, rate limiting, and sensitive data masking.
Back to servers
Setup instructions
Provider
gh-Sentry01
Release date
Mar 19, 2025
Language
TypeScript

The Supabase MCP server acts as a bridge between AI assistants (like GitHub Copilot) and your Supabase database, allowing the AI to understand your schema, assist with queries, and provide context-aware suggestions related to your data model.

Prerequisites

Before installing the MCP server, ensure you have:

  • Node.js 18+ installed
  • npm or yarn package manager
  • Supabase project with admin API key
  • VS Code with Copilot/MCP support
  • Git

Installation

Setting Up the Server

  1. Create a new directory and initialize the project:

    mkdir mcp-server-supabase
    cd mcp-server-supabase
    npm init -y
    
  2. Install the required dependencies:

    npm install @supabase/supabase-js @modelcontextprotocol/server dotenv
    
  3. Create the necessary file structure:

    • src/index.js - Main entry point
    • src/supabase-client.js - Supabase connection handling
    • src/schema-provider.js - Database schema extraction
    • src/query-handler.js - Safe query execution
    • config.js - Configuration management
    • .env - Environment variables

Creating the Server Files

Create the following files with their respective content:

src/index.js

const { MCPServer } = require('@modelcontextprotocol/server');
const { getSupabaseClient } = require('./supabase-client');
const { SchemaProvider } = require('./schema-provider');
const { QueryHandler } = require('./query-handler');
const config = require('./config');

async function main() {
  try {
    // Initialize Supabase client
    const supabaseClient = getSupabaseClient(config.supabase.url, config.supabase.key);
    
    // Create providers
    const schemaProvider = new SchemaProvider(supabaseClient);
    const queryHandler = new QueryHandler(supabaseClient, config.security.allowedQueries);
    
    // Initialize MCP server
    const server = new MCPServer({
      name: 'mcp-server-supabase',
      version: '1.0.0',
    });
    
    // Register handlers
    server.registerHandler('getSchema', async () => {
      return await schemaProvider.getFullSchema();
    });
    
    server.registerHandler('getTableInfo', async (params) => {
      return await schemaProvider.getTableInfo(params.tableName);
    });
    
    server.registerHandler('executeQuery', async (params) => {
      return await queryHandler.execute(params.query, params.params);
    });
    
    // Start the server
    await server.start();
    console.log('MCP Supabase server is running');
  } catch (error) {
    console.error('Failed to start MCP server:', error);
    process.exit(1);
  }
}

main();

src/supabase-client.js

const { createClient } = require('@supabase/supabase-js');

function getSupabaseClient(url, apiKey) {
  if (!url || !apiKey) {
    throw new Error('Supabase URL and API key must be provided');
  }
  
  return createClient(url, apiKey, {
    auth: { persistSession: false },
  });
}

module.exports = { getSupabaseClient };

src/schema-provider.js

class SchemaProvider {
  constructor(supabaseClient) {
    this.supabase = supabaseClient;
  }
  
  async getFullSchema() {
    // Query Supabase for full database schema
    const { data, error } = await this.supabase
      .rpc('get_schema_information', {});
    
    if (error) throw new Error(`Failed to get schema: ${error.message}`);
    
    return data;
  }
  
  async getTableInfo(tableName) {
    // Get detailed information about a specific table
    const { data, error } = await this.supabase
      .rpc('get_table_information', { table_name: tableName });
    
    if (error) throw new Error(`Failed to get table info: ${error.message}`);
    
    return data;
  }
}

module.exports = { SchemaProvider };

src/query-handler.js

class QueryHandler {
  constructor(supabaseClient, allowedQueryTypes = ['SELECT']) {
    this.supabase = supabaseClient;
    this.allowedQueryTypes = allowedQueryTypes; 
  }
  
  validateQuery(queryString) {
    // Basic SQL injection prevention and query type validation
    const normalizedQuery = queryString.trim().toUpperCase();
    
    // Check if the query starts with allowed query types
    const isAllowed = this.allowedQueryTypes.some(
      type => normalizedQuery.startsWith(type)
    );
    
    if (!isAllowed) {
      throw new Error(`Query type not allowed. Allowed types: ${this.allowedQueryTypes.join(', ')}`);
    }
    
    return true;
  }
  
  async execute(queryString, params = {}) {
    // Validate query before execution
    this.validateQuery(queryString);
    
    // Execute the query through Supabase
    const { data, error } = await this.supabase
      .rpc('execute_query', { query_string: queryString, query_params: params });
    
    if (error) throw new Error(`Query execution failed: ${error.message}`);
    
    return data;
  }
}

module.exports = { QueryHandler };

config.js

require('dotenv').config();

module.exports = {
  supabase: {
    url: process.env.SUPABASE_URL,
    key: process.env.SUPABASE_SERVICE_KEY,
  },
  server: {
    port: process.env.PORT || 3000,
  },
  security: {
    allowedQueries: process.env.ALLOWED_QUERY_TYPES 
      ? process.env.ALLOWED_QUERY_TYPES.split(',') 
      : ['SELECT'],
  }
};

.env

Create this file based on the example below and add your Supabase credentials:

SUPABASE_URL=https://your-project-ref.supabase.co
SUPABASE_SERVICE_KEY=your-service-key
PORT=3000
ALLOWED_QUERY_TYPES=SELECT

Supabase Database Setup

You'll need to create these stored procedures in your Supabase database:

  1. get_schema_information() - Returns database schema
  2. get_table_information(table_name TEXT) - Returns info about specific table
  3. execute_query(query_string TEXT, query_params JSONB) - Safely executes queries

VS Code Integration

Add the Supabase MCP server to your VS Code settings.json:

"mcp": {
  "inputs": [],
  "servers": {
    "mcp-server-supabase": {
      "command": "node",
      "args": [
        "/path/to/mcp-server-supabase/src/index.js"
      ],
      "env": {
        "SUPABASE_URL": "https://your-project-ref.supabase.co",
        "SUPABASE_SERVICE_KEY": "your-service-key",
        "ALLOWED_QUERY_TYPES": "SELECT"
      }
    }
  }
}

Usage

Once installed and configured, you can interact with your Supabase database through AI assistants like GitHub Copilot.

Example Interactions

You can use natural language prompts to explore your database:

  • Schema exploration:

    What tables do I have in my Supabase database?
    
  • Table information:

    What columns are in the users table?
    
  • Query assistance:

    Help me write a query to get all users who signed up in the last 7 days
    

Starting the Server

To start the MCP server manually:

node src/index.js

When integrated with VS Code and properly configured, the server will start automatically when needed.

Troubleshooting

Common Issues

Server won't start

  • Check your Node.js version (should be 18+)
  • Verify your Supabase credentials are correct
  • Check for error logs in the terminal

Schema not loading

  • Verify your Supabase service key has the necessary permissions
  • Check that the database functions are properly created
  • Look for errors in the server console output

VS Code can't connect

  • Check that the server path in settings.json is correct
  • Restart VS Code after configuration changes
  • Verify the server process is running

Security Considerations

  • Always use a scoped API key with minimum required permissions
  • Default to SELECT-only queries for safety
  • Consider implementing row-level security in Supabase

How to install this MCP server

For Claude Code

To add this MCP server to Claude Code, run this command in your terminal:

claude mcp add-json "mcp-server-supabase" '{"command":"node","args":["/path/to/mcp-server-supabase/src/index.js"],"env":{"SUPABASE_URL":"https://your-project-ref.supabase.co","SUPABASE_SERVICE_KEY":"your-service-key","ALLOWED_QUERY_TYPES":"SELECT"}}'

See the official Claude Code MCP documentation for more details.

For Cursor

There are two ways to add an MCP server to Cursor. The most common way is to add the server globally in the ~/.cursor/mcp.json file so that it is available in all of your projects.

If you only need the server in a single project, you can add it to the project instead by creating or adding it to the .cursor/mcp.json file.

Adding an MCP server to Cursor globally

To add a global MCP server go to Cursor Settings > Tools & Integrations and click "New MCP Server".

When you click that button the ~/.cursor/mcp.json file will be opened and you can add your server like this:

{
    "mcpServers": {
        "mcp-server-supabase": {
            "command": "node",
            "args": [
                "/path/to/mcp-server-supabase/src/index.js"
            ],
            "env": {
                "SUPABASE_URL": "https://your-project-ref.supabase.co",
                "SUPABASE_SERVICE_KEY": "your-service-key",
                "ALLOWED_QUERY_TYPES": "SELECT"
            }
        }
    }
}

Adding an MCP server to a project

To add an MCP server to a project you can create a new .cursor/mcp.json file or add it to the existing one. This will look exactly the same as the global MCP server example above.

How to use the MCP server

Once the server is installed, you might need to head back to Settings > MCP and click the refresh button.

The Cursor agent will then be able to see the available tools the added MCP server has available and will call them when it needs to.

You can also explicitly ask the agent to use the tool by mentioning the tool name and describing what the function does.

For Claude Desktop

To add this MCP server to Claude Desktop:

1. Find your configuration file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json

2. Add this to your configuration file:

{
    "mcpServers": {
        "mcp-server-supabase": {
            "command": "node",
            "args": [
                "/path/to/mcp-server-supabase/src/index.js"
            ],
            "env": {
                "SUPABASE_URL": "https://your-project-ref.supabase.co",
                "SUPABASE_SERVICE_KEY": "your-service-key",
                "ALLOWED_QUERY_TYPES": "SELECT"
            }
        }
    }
}

3. Restart Claude Desktop for the changes to take effect

Want to 10x your AI skills?

Get a free account and learn to code + market your apps using AI (with or without vibes!).

Nah, maybe later