Skip to main content
Glama
abushadab

Self-Hosted Supabase MCP Server

by abushadab

apply_migration

Execute SQL migration scripts securely within a transaction and track them in the supabase_migrations.schema_migrations table for self-hosted Supabase databases.

Instructions

Applies a SQL migration script and records it in the supabase_migrations.schema_migrations table within a transaction.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
nameNoAn optional descriptive name for the migration.
sqlYesThe SQL DDL content of the migration.
versionYesThe migration version string (e.g., '20240101120000').

Implementation Reference

  • The main handler function that applies the provided SQL migration within a database transaction and records the migration version in the supabase_migrations.schema_migrations table.
    execute: async (input: ApplyMigrationInput, context: ToolContext) => {
        const client = context.selfhostedClient;
    
        try {
            // Ensure pg is configured and available
            if (!client.isPgAvailable()) {
                 throw new Error('Direct database connection (DATABASE_URL) is required for applying migrations but is not configured or available.');
            }
    
            await client.executeTransactionWithPg(async (pgClient: PoolClient) => {
                // 1. Execute the provided migration SQL
                console.error(`Executing migration SQL for version ${input.version}...`);
                await pgClient.query(input.sql);
                console.error('Migration SQL executed successfully.');
    
                // 2. Insert the record into the migrations table
                console.error(`Recording migration version ${input.version} in schema_migrations...`);
                await pgClient.query(
                    'INSERT INTO supabase_migrations.schema_migrations (version, name) ' +
                    'VALUES ($1, $2);',
                     [input.version, input.name ?? '']
                 );
                console.error(`Migration version ${input.version} recorded.`);
            });
    
            return {
                success: true,
                version: input.version,
                message: `Migration ${input.version} applied successfully.`,
            };
        } catch (error: unknown) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            console.error(`Failed to apply migration ${input.version}:`, errorMessage);
            // Return a structured error response recognized by handleSqlResponse if needed,
            // or let the SDK handle the thrown error.
            // Here, we'll just rethrow to let SDK handle it.
            // Alternatively, return { success: false, version: input.version, message: 'Failed: ' + errorMessage };
            throw new Error(`Failed to apply migration ${input.version}: ${errorMessage}`);
        }
    },
  • Zod schemas for input and output validation, type inference, and static JSON schema for MCP tool capabilities.
    // Input schema
    const ApplyMigrationInputSchema = z.object({
        version: z.string().describe("The migration version string (e.g., '20240101120000')."),
        name: z.string().optional().describe("An optional descriptive name for the migration."),
        sql: z.string().describe("The SQL DDL content of the migration."),
    });
    type ApplyMigrationInput = z.infer<typeof ApplyMigrationInputSchema>;
    
    // Output schema
    const ApplyMigrationOutputSchema = z.object({
        success: z.boolean(),
        version: z.string(),
        message: z.string().optional(),
    });
    
    // Static JSON Schema for MCP capabilities
    const mcpInputSchema = {
        type: 'object',
        properties: {
            version: { type: 'string', description: "The migration version string (e.g., '20240101120000')." },
            name: { type: 'string', description: 'An optional descriptive name for the migration.' },
            sql: { type: 'string', description: 'The SQL DDL content of the migration.' },
        },
        required: ['version', 'sql'],
    };
  • src/index.ts:103-103 (registration)
    Registers the `applyMigrationTool` in the `availableTools` map, which is filtered and used to expose tools to the MCP server.
    [applyMigrationTool.name]: applyMigrationTool as AppTool,
  • src/index.ts:14-14 (registration)
    Imports the `applyMigrationTool` for use in the MCP server.
    import { applyMigrationTool } from './tools/apply_migration.js';

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/abushadab/selfhosted-supabase-mcp-basic-auth'

If you have feedback or need assistance with the MCP directory API, please join our Discord server