Skip to main content
Glama
abushadab

Self-Hosted Supabase MCP Server

by abushadab

create_auth_user

Generate a new user in auth.users using email, password, and optional metadata. Handle with caution due to plain password usage. Designed for Self-Hosted Supabase MCP Server integration.

Instructions

Creates a new user directly in auth.users. WARNING: Requires plain password, insecure. Use with extreme caution.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
app_metadataNoOptional app metadata.
emailYesThe email address for the new user.
passwordYesPlain text password (min 6 chars). WARNING: Insecure.
roleNoUser role.authenticated
user_metadataNoOptional user metadata.

Implementation Reference

  • The execute function of the createAuthUserTool, which performs a direct PostgreSQL INSERT into auth.users table, hashing the password with crypt and gen_salt, handling errors like duplicate emails, and returning the created user.
    execute: async (input: CreateAuthUserInput, context: ToolContext): Promise<CreateAuthUserOutput> => { // Use CreateAuthUserOutput
        const client = context.selfhostedClient;
        const { email, password, role, app_metadata, user_metadata } = input;
    
        // Direct DB connection is absolutely required for this direct insert
        if (!client.isPgAvailable()) {
             context.log('Direct database connection (DATABASE_URL) is required to create an auth user directly.', 'error');
            throw new Error('Direct database connection (DATABASE_URL) is required to create an auth user directly.');
        }
    
        console.warn(`SECURITY WARNING: Creating user ${email} with plain text password via direct DB insert.`);
        context.log(`Attempting to create user ${email}...`, 'warn');
    
        // Use transaction to ensure atomicity and get pg client
        const createdUser = await client.executeTransactionWithPg(async (pgClient: PoolClient) => {
            // Check if pgcrypto extension is available (needed for crypt)
            try {
                await pgClient.query("SELECT crypt('test', gen_salt('bf'))");
            } catch (err) {
                 throw new Error('Failed to execute crypt function. Ensure pgcrypto extension is enabled in the database.');
            }
            
            // Construct the INSERT statement with parameterization
            const sql = `
                INSERT INTO auth.users (
                    instance_id, email, encrypted_password, role,
                    raw_app_meta_data, raw_user_meta_data, 
                    aud, email_confirmed_at, confirmation_sent_at -- Set required defaults
                )
                VALUES (
                    COALESCE(current_setting('app.instance_id', TRUE), '00000000-0000-0000-0000-000000000000')::uuid,
                    $1, crypt($2, gen_salt('bf')),
                    $3,
                    $4::jsonb,
                    $5::jsonb,
                    'authenticated', now(), now()
                )
                RETURNING id, email, role, raw_app_meta_data, raw_user_meta_data, created_at::text, last_sign_in_at::text;
            `;
    
            const params = [
                email,
                password,
                role || 'authenticated', // Default role
                JSON.stringify(app_metadata || {}),
                JSON.stringify(user_metadata || {})
            ];
    
            try {
                const result = await pgClient.query(sql, params);
                if (result.rows.length === 0) {
                     throw new Error('User creation failed, no user returned after insert.');
                }
                return CreatedAuthUserZodSchema.parse(result.rows[0]);
            } catch (dbError: unknown) {
                let errorMessage = 'Unknown database error during user creation';
                let isUniqueViolation = false;
    
                if (typeof dbError === 'object' && dbError !== null && 'code' in dbError) {
                    // Check PG error code for unique violation safely
                    if (dbError.code === '23505') {
                        isUniqueViolation = true;
                        errorMessage = `User creation failed: Email '${email}' likely already exists.`;
                    } else if ('message' in dbError && typeof dbError.message === 'string') {
                         errorMessage = `Database error (${dbError.code}): ${dbError.message}`;
                    } else {
                        errorMessage = `Database error code: ${dbError.code}`;
                    }
                } else if (dbError instanceof Error) {
                    errorMessage = `Database error during user creation: ${dbError.message}`;
                } else {
                     errorMessage = `Database error during user creation: ${String(dbError)}`;
                }
    
                console.error('Error creating user in DB:', dbError); // Log the original error
    
                // Throw a specific error message
                throw new Error(errorMessage);
            }
        });
    
        console.error(`Successfully created user ${email} with ID ${createdUser.id}.`);
        context.log(`Successfully created user ${email} with ID ${createdUser.id}.`);
        return createdUser; // Matches CreateAuthUserOutput (AuthUser)
    },
  • Zod input schema for the create_auth_user tool, validating email, password, role, and metadata.
    const CreateAuthUserInputSchema = z.object({
        email: z.string().email().describe('The email address for the new user.'),
        password: z.string().min(6).describe('Plain text password (min 6 chars). WARNING: Insecure.'),
        role: z.string().optional().describe('User role.'),
        app_metadata: z.record(z.unknown()).optional().describe('Optional app metadata.'),
        user_metadata: z.record(z.unknown()).optional().describe('Optional user metadata.'),
    });
  • Zod output schema for the created auth user, matching the AuthUser structure.
    const CreatedAuthUserZodSchema = z.object({
        id: z.string().uuid(),
        email: z.string().email().nullable(),
        role: z.string().nullable(),
        created_at: z.string().nullable(),
        last_sign_in_at: z.string().nullable(), // Will likely be null on creation
        raw_app_meta_data: z.record(z.unknown()).nullable(),
        raw_user_meta_data: z.record(z.unknown()).nullable(),
        // Add other fields returned by the INSERT if necessary
    });
  • src/index.ts:27-27 (registration)
    Imports the createAuthUserTool from its implementation file.
    import { createAuthUserTool } from './tools/create_auth_user.js';
  • src/index.ts:116-116 (registration)
    Registers the createAuthUserTool in the availableTools object used by the MCP server.
    [createAuthUserTool.name]: createAuthUserTool as AppTool,
Behavior4/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 effectively communicates critical behavioral traits: this is a write operation (implied by 'Creates'), it requires a plain password (security risk), and it operates directly on auth.users. The warning about insecurity and extreme caution adds valuable context beyond basic functionality, though it could mention permissions or side effects.

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 perfectly concise with only two sentences that each earn their place: the first states the purpose, and the second provides critical warnings. It's front-loaded with the core functionality and wastes no words, making it highly efficient for an AI agent 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 complexity (a write operation with security implications), no annotations, and no output schema, the description does well by covering the purpose and major risks. However, it lacks details on what the tool returns (e.g., user ID or confirmation) and doesn't mention prerequisites like admin permissions, leaving some gaps for a mutation tool.

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 5 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema (e.g., it doesn't explain the semantics of 'app_metadata' vs 'user_metadata'). This meets the baseline of 3 when the schema does the heavy lifting.

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 ('Creates a new user') and target resource ('directly in auth.users'), distinguishing it from sibling tools like 'update_auth_user' or 'delete_auth_user' which modify or remove users rather than create them. It uses precise language that leaves no ambiguity about the tool's function.

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 explicit guidance on when to use this tool ('Creates a new user') and includes a strong warning about security risks ('WARNING: Requires plain password, insecure. Use with extreme caution.'), which implicitly suggests caution and potential alternatives. However, it doesn't explicitly name alternative methods or specify when not to use it beyond the security warning.

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

Related 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/abushadab/selfhosted-supabase-mcp-basic-auth'

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