Skip to main content
Glama
HenkDz

Self-Hosted Supabase MCP Server

generate_typescript_types

Generate TypeScript types from your Supabase database schema and save them to a specified file path for type-safe development.

Instructions

Generates TypeScript types from the database schema using the Supabase CLI (supabase gen types) and downloads the file to the specified absolute path. The tool returns the current platform (win32, darwin, linux) to help with path formatting. Requires DATABASE_URL configuration and Supabase CLI installed.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
included_schemasNoDatabase schemas to include in type generation.
output_filenameNoFilename to save the generated types to in the workspace root.database.types.ts
output_pathYesAbsolute path where to download the generated TypeScript file. Examples: Windows: "C:\\path\\to\\project\\database.types.ts", macOS/Linux: "/path/to/project/database.types.ts". This parameter is required.

Implementation Reference

  • The execute function that implements the core logic of the tool: retrieves DB URL, constructs and runs the 'supabase gen types' CLI command, normalizes the output path for cross-platform compatibility, ensures directory exists, writes the generated types to file, and returns structured output with success status and platform info.
    execute: async (input: GenerateTypesInput, context: ToolContext) => {
        const client = context.selfhostedClient;
        const dbUrl = client.getDbUrl(); // Need this getter in the client
    
        if (!dbUrl) {
            return {
                success: false,
                message: 'Error: DATABASE_URL is not configured. Cannot generate types.',
                platform: process.platform,
            };
        }
    
        // Construct the command
        // Use --local flag for self-hosted?
        const schemas = input.included_schemas.join(','); // Comma-separated for the CLI flag
        // Note: The actual command might vary slightly based on Supabase CLI version and context.
        // Using --db-url is generally safer for self-hosted.
        const command = `supabase gen types typescript --db-url "${dbUrl}" --schema "${schemas}"`;
    
        console.error(`Running command: ${command}`);
    
        try {
            const { stdout, stderr, error } = await runExternalCommand(command);
    
            if (error) {
                console.error(`Error executing supabase gen types: ${stderr || error.message}`);
                return {
                    success: false,
                    message: `Command failed: ${stderr || error.message}`,
                    platform: process.platform,
                };
            }
    
            if (stderr) {
                console.error(`supabase gen types produced stderr output: ${stderr}`);
                 // Treat stderr as non-fatal for now, maybe just warnings
            }
    
            // Normalize and save the generated types to the specified absolute path
            let outputPath: string;
            try {
                outputPath = normalizeOutputPath(input.output_path);
                console.error(`Normalized output path: ${outputPath}`);
            } catch (pathError) {
                const pathErrorMessage = pathError instanceof Error ? pathError.message : String(pathError);
                console.error(`Invalid output path: ${pathErrorMessage}`);
                return {
                    success: false,
                    message: `Invalid output path "${input.output_path}": ${pathErrorMessage}`,
                    platform: process.platform,
                };
            }
            
            try {
                // Ensure the directory exists
                const outputDir = dirname(outputPath);
                try {
                    mkdirSync(outputDir, { recursive: true });
                } catch (dirError) {
                    // Ignore error if directory already exists
                    if ((dirError as NodeJS.ErrnoException).code !== 'EEXIST') {
                        throw dirError;
                    }
                }
                
                writeFileSync(outputPath, stdout, 'utf8');
                console.error(`Types saved to: ${outputPath}`);
            } catch (writeError) {
                const writeErrorMessage = writeError instanceof Error ? writeError.message : String(writeError);
                console.error(`Failed to write types file: ${writeErrorMessage}`);
                return {
                    success: false,
                    message: `Type generation succeeded but failed to save file: ${writeErrorMessage}. Platform: ${process.platform}. Attempted path: ${outputPath}`,
                    types: stdout,
                    platform: process.platform,
                };
            }
    
            console.error('Type generation and file save successful.');
            return {
                success: true,
                message: `Types generated successfully and saved to ${outputPath}.${stderr ? `\nWarnings:\n${stderr}` : ''}`,
                types: stdout,
                file_path: outputPath,
                platform: process.platform,
            };
    
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            console.error(`Exception during type generation: ${errorMessage}`);
            return {
                success: false,
                message: `Exception during type generation: ${errorMessage}. Platform: ${process.platform}`,
                platform: process.platform,
            };
        }
    },
  • Zod input and output schemas, plus static JSON mcpInputSchema for MCP tool capabilities, defining parameters like included_schemas, output_filename/path, and response fields.
    // Input schema
    const GenerateTypesInputSchema = z.object({
        included_schemas: z.array(z.string()).optional().default(['public']).describe('Database schemas to include in type generation.'),
        output_filename: z.string().optional().default('database.types.ts').describe('Filename to save the generated types to in the workspace root.'),
        output_path: z.string().describe('Absolute path where to save the file. If provided, output_filename will be ignored.'),
    });
    type GenerateTypesInput = z.infer<typeof GenerateTypesInputSchema>;
    
    // Output schema
    const GenerateTypesOutputSchema = z.object({
        success: z.boolean(),
        message: z.string().describe('Output message from the generation process.'),
        types: z.string().optional().describe('The generated TypeScript types, if successful.'),
        file_path: z.string().optional().describe('The absolute path to the saved types file, if successful.'),
        platform: z.string().describe('Operating system platform (win32, darwin, linux).'),
    });
    
    // Static JSON Schema for MCP capabilities
    const mcpInputSchema = {
        type: 'object',
        properties: {
            included_schemas: {
                type: 'array',
                items: { type: 'string' },
                default: ['public'],
                description: 'Database schemas to include in type generation.',
            },
            output_filename: {
                type: 'string',
                default: 'database.types.ts',
                description: 'Filename to save the generated types to in the workspace root.',
            },
            output_path: {
                type: 'string',
                description: 'Absolute path where to download the generated TypeScript file. Examples: Windows: "C:\\\\path\\\\to\\\\project\\\\database.types.ts", macOS/Linux: "/path/to/project/database.types.ts". This parameter is required.',
            },
        },
        required: ['output_path'], // output_path is required for file download
    };
  • src/index.ts:110-110 (registration)
    Registration of the generateTypesTool in the availableTools object, which is used to populate server capabilities and handle tool calls in the MCP server.
    [generateTypesTool.name]: generateTypesTool as AppTool,
  • src/index.ts:21-21 (registration)
    Import of the generateTypesTool from its implementation file.
    import { generateTypesTool } from './tools/generate_typescript_types.js';
  • Helper function to normalize output paths, handling Windows-specific path formats and using Node.js resolve for final normalization.
    function normalizeOutputPath(inputPath: string): string {
        // Handle Windows drive letters in Unix-style paths (e.g., "/c:/path" -> "C:/path")
        if (process.platform === 'win32' && inputPath.match(/^\/[a-zA-Z]:/)) {
            inputPath = inputPath.substring(1); // Remove leading slash
            inputPath = inputPath.charAt(0).toUpperCase() + inputPath.slice(1); // Uppercase drive letter
        }
        
        // Use Node.js resolve to normalize the path
        return resolve(inputPath);
    }
Behavior3/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 adds useful context beyond basic functionality by mentioning the download action, platform return for path formatting, and prerequisites. However, it lacks details on error handling, rate limits, or what happens if the file already exists, which are important for a tool that writes files.

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 appropriately sized and front-loaded, with the core purpose stated first, followed by key behavioral details and prerequisites. Every sentence adds necessary information without redundancy, making it efficient and easy to parse.

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

Completeness4/5

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

Given the tool's complexity (file generation with prerequisites) and no output schema, the description is mostly complete. It covers the purpose, key behavior, and prerequisites, but could improve by detailing the return value format or error scenarios. However, it adequately supports tool selection and invocation in context.

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 already documents all parameters thoroughly. The description adds some value by implying the use of 'supabase gen types' and mentioning platform-specific path examples, but it does not provide additional semantic details beyond what the schema specifies, such as format constraints or interactions between parameters.

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 ('Generates TypeScript types from the database schema') using the Supabase CLI, identifies the resource ('database schema'), and distinguishes it from sibling tools like 'execute_sql' or 'list_tables' by focusing on type generation rather than data manipulation or listing operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool ('Generates TypeScript types from the database schema') and mentions prerequisites ('Requires DATABASE_URL configuration and Supabase CLI installed'), but it does not explicitly state when not to use it or name specific alternatives among the sibling tools.

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