Skip to main content
Glama
HenkDz

Self-Hosted Supabase MCP Server

apply_migration

Execute SQL migration scripts within transactions to update self-hosted Supabase databases, tracking applied migrations in the schema_migrations table.

Instructions

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

Input Schema

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

Implementation Reference

  • The execute handler function that applies the provided SQL migration using a direct PG client within a transaction and records the migration 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 input schema and type for the apply_migration tool, defining version, optional name, and sql parameters.
    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>;
  • Zod output schema for the apply_migration tool, including success boolean, version, and optional message.
    const ApplyMigrationOutputSchema = z.object({
        success: z.boolean(),
        version: z.string(),
        message: z.string().optional(),
    });
  • Export of the applyMigrationTool object, defining the tool name, description, schemas, and execute handler.
    export const applyMigrationTool = {
        name: 'apply_migration',
        description: 'Applies a SQL migration script and records it in the supabase_migrations.schema_migrations table within a transaction.',
        inputSchema: ApplyMigrationInputSchema,
        mcpInputSchema: mcpInputSchema,
        outputSchema: ApplyMigrationOutputSchema,
        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}`);
            }
        },
    }; 
  • src/index.ts:103-103 (registration)
    Registration of the apply_migration tool in the availableTools object used by the MCP server.
    [applyMigrationTool.name]: applyMigrationTool as AppTool,
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions transactional execution and recording, which is useful, but lacks critical details like whether this requires admin permissions, what happens on failure (e.g., rollback), if it's idempotent, or any rate limits. For a tool that modifies database schema, this leaves significant behavioral gaps.

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

Conciseness5/5

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

The description is a single, well-structured sentence that efficiently conveys the core functionality without redundancy. It's front-loaded with the primary action and includes essential behavioral context (transactional execution and recording). Every word earns its place with no wasted text.

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

Completeness3/5

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

Given the tool's complexity (applies SQL migrations with transactional safety) and lack of both annotations and output schema, the description is moderately complete. It covers the what and how but misses important context like error handling, permissions, and return values. For a mutation tool with no structured safety hints, it should provide more operational guidance.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema fully documents all three parameters (version, name, sql). The description doesn't add any parameter-specific semantics beyond what's in the schema—it doesn't explain parameter relationships, formatting constraints, or usage examples. This meets the baseline for high schema coverage.

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

Purpose5/5

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

The description clearly states the specific action ('applies a SQL migration script') and resource ('records it in the supabase_migrations.schema_migrations table'), distinguishing it from sibling tools like 'execute_sql' (which doesn't record migrations) and 'list_migrations' (which only lists them). It precisely defines the tool's function with both execution and tracking components.

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?

The description implies usage context through 'SQL migration script' and 'within a transaction', suggesting it's for database schema changes. However, it doesn't explicitly state when to use this versus alternatives like 'execute_sql' for non-migration SQL or 'list_migrations' for checking status. No explicit when-not-to-use guidance or prerequisites are provided.

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

Install Server

Other Tools

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/HenkDz/selfhosted-supabase-mcp'

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