Skip to main content
Glama
HenkDz

PostgreSQL MCP Server

pg_execute_mutation

Execute INSERT, UPDATE, DELETE, or UPSERT operations in PostgreSQL databases to modify table data using specified parameters and conditions.

Instructions

Execute data modification operations (INSERT/UPDATE/DELETE/UPSERT) - operation="insert/update/delete/upsert" with table and data. Examples: operation="insert", table="users", data={"name":"John","email":"john@example.com"}

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionStringNoPostgreSQL connection string (optional)
operationYesMutation operation: insert (add rows), update (modify rows), delete (remove rows), upsert (insert or update)
tableYesTable name for the operation
dataNoData object with column-value pairs (required for insert/update/upsert)
whereNoWHERE clause for update/delete operations (without WHERE keyword)
conflictColumnsNoColumns for conflict resolution in upsert (ON CONFLICT)
returningNoRETURNING clause to get back inserted/updated data
schemaNoSchema name (defaults to public)public

Implementation Reference

  • Handler function that processes tool arguments, performs basic validation, calls the executeMutation helper, and formats the response.
    execute: async (args: unknown, getConnectionStringVal: GetConnectionStringFn): Promise<ToolOutput> => {
      const { 
        connectionString: connStringArg,
        operation,
        table,
        data,
        where,
        conflictColumns,
        returning,
        schema
      } = args as {
        connectionString?: string;
        operation: 'insert' | 'update' | 'delete' | 'upsert';
        table: string;
        data?: Record<string, unknown>;
        where?: string;
        conflictColumns?: string[];
        returning?: string;
        schema?: string;
      };
    
      const resolvedConnString = getConnectionStringVal(connStringArg);
    
      try {
        // Input validation
        if (!table?.trim()) {
          return { 
            content: [{ type: 'text', text: 'Error: table is required' }], 
            isError: true 
          };
        }
    
        const result = await executeMutation({
          connectionString: resolvedConnString,
          operation,
          table,
          data,
          where,
          conflictColumns,
          returning,
          schema: schema || 'public'
        } as ExecuteMutationInput, getConnectionStringVal);
    
        let responseText = `${operation.toUpperCase()} operation completed successfully. Rows affected: ${result.rowsAffected}`;
        
        if (result.returning && result.returning.length > 0) {
          responseText += `\n\nReturning data:\n${JSON.stringify(result.returning, null, 2)}`;
        }
    
        return { content: [{ type: 'text', text: responseText }] };
    
      } catch (error) {
        return { 
          content: [{ type: 'text', text: `Error executing ${operation} operation: ${error instanceof Error ? error.message : String(error)}` }], 
          isError: true 
        };
      }
    }
  • Core helper function that constructs and executes the specific SQL mutation (INSERT, UPDATE, DELETE, UPSERT) using dynamic SQL building and database connection.
    async function executeMutation(
      input: ExecuteMutationInput,
      getConnectionString: GetConnectionStringFn
    ): Promise<{ operation: string; rowsAffected: number; returning?: unknown[] }> {
      const resolvedConnectionString = getConnectionString(input.connectionString);
      const db = DatabaseConnection.getInstance();
      const { operation, table, data, where, conflictColumns, returning, schema } = input;
    
      try {
        await db.connect(resolvedConnectionString);
        
        const schemaPrefix = (schema && schema !== 'public') ? `"${schema}".` : '';
        const tableName = `${schemaPrefix}"${table}"`;
    
        switch (operation) {
          case 'insert': {
            if (!data || Object.keys(data).length === 0) {
              throw new McpError(ErrorCode.InvalidParams, 'Data object is required for insert operation');
            }
    
            const columns = Object.keys(data);
            const values = Object.values(data);
            const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
            
            let insertSQL = `INSERT INTO ${tableName} (${columns.map(col => `"${col}"`).join(', ')}) VALUES (${placeholders})`;
            
            if (returning) {
              insertSQL += ` RETURNING ${returning}`;
            }
    
            const result = await db.query(insertSQL, values);
            return {
              operation: 'insert',
              rowsAffected: Array.isArray(result) ? result.length : 1,
              returning: returning ? result : undefined
            };
          }
    
          case 'update': {
            if (!data || Object.keys(data).length === 0) {
              throw new McpError(ErrorCode.InvalidParams, 'Data object is required for update operation');
            }
            if (!where) {
              throw new McpError(ErrorCode.InvalidParams, 'WHERE clause is required for update operation to prevent accidental full table updates');
            }
    
            const columns = Object.keys(data);
            const values = Object.values(data);
            const setClause = columns.map((col, i) => `"${col}" = $${i + 1}`).join(', ');
            
            let updateSQL = `UPDATE ${tableName} SET ${setClause} WHERE ${where}`;
            
            if (returning) {
              updateSQL += ` RETURNING ${returning}`;
            }
    
            const result = await db.query(updateSQL, values);
            return {
              operation: 'update',
              rowsAffected: Array.isArray(result) ? result.length : 1,
              returning: returning ? result : undefined
            };
          }
    
          case 'delete': {
            if (!where) {
              throw new McpError(ErrorCode.InvalidParams, 'WHERE clause is required for delete operation to prevent accidental full table deletion');
            }
    
            let deleteSQL = `DELETE FROM ${tableName} WHERE ${where}`;
            
            if (returning) {
              deleteSQL += ` RETURNING ${returning}`;
            }
    
            const result = await db.query(deleteSQL);
            return {
              operation: 'delete',
              rowsAffected: Array.isArray(result) ? result.length : 1,
              returning: returning ? result : undefined
            };
          }
    
          case 'upsert': {
            if (!data || Object.keys(data).length === 0) {
              throw new McpError(ErrorCode.InvalidParams, 'Data object is required for upsert operation');
            }
            if (!conflictColumns || conflictColumns.length === 0) {
              throw new McpError(ErrorCode.InvalidParams, 'Conflict columns are required for upsert operation');
            }
    
            const columns = Object.keys(data);
            const values = Object.values(data);
            const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
            const conflictCols = conflictColumns.map(col => `"${col}"`).join(', ');
            const updateClause = columns
              .filter(col => !conflictColumns.includes(col))
              .map(col => `"${col}" = EXCLUDED."${col}"`)
              .join(', ');
            
            let upsertSQL = `INSERT INTO ${tableName} (${columns.map(col => `"${col}"`).join(', ')}) VALUES (${placeholders}) ON CONFLICT (${conflictCols})`;
            
            if (updateClause) {
              upsertSQL += ` DO UPDATE SET ${updateClause}`;
            } else {
              upsertSQL += ' DO NOTHING';
            }
            
            if (returning) {
              upsertSQL += ` RETURNING ${returning}`;
            }
    
            const result = await db.query(upsertSQL, values);
            return {
              operation: 'upsert',
              rowsAffected: Array.isArray(result) ? result.length : 1,
              returning: returning ? result : undefined
            };
          }
    
          default:
            throw new McpError(ErrorCode.InvalidParams, `Unknown operation: ${operation}`);
        }
      } catch (error) {
        throw new McpError(ErrorCode.InternalError, `Failed to execute ${operation}: ${error instanceof Error ? error.message : String(error)}`);
      } finally {
        await db.disconnect();
      }
    }
  • Zod schema defining the input parameters for the pg_execute_mutation tool.
    const ExecuteMutationInputSchema = z.object({
      connectionString: z.string().optional().describe('PostgreSQL connection string (optional)'),
      operation: z.enum(['insert', 'update', 'delete', 'upsert']).describe('Mutation operation: insert (add rows), update (modify rows), delete (remove rows), upsert (insert or update)'),
      table: z.string().describe('Table name for the operation'),
      data: z.record(z.unknown()).optional().describe('Data object with column-value pairs (required for insert/update/upsert)'),
      where: z.string().optional().describe('WHERE clause for update/delete operations (without WHERE keyword)'),
      conflictColumns: z.array(z.string()).optional().describe('Columns for conflict resolution in upsert (ON CONFLICT)'),
      returning: z.string().optional().describe('RETURNING clause to get back inserted/updated data'),
      schema: z.string().optional().default('public').describe('Schema name (defaults to public)')
    });
  • Definition and export of the PostgresTool object for pg_execute_mutation.
    export const executeMutationTool: PostgresTool = {
      name: 'pg_execute_mutation',
      description: 'Execute data modification operations (INSERT/UPDATE/DELETE/UPSERT) - operation="insert/update/delete/upsert" with table and data. Examples: operation="insert", table="users", data={"name":"John","email":"john@example.com"}',
      inputSchema: ExecuteMutationInputSchema,
      execute: async (args: unknown, getConnectionStringVal: GetConnectionStringFn): Promise<ToolOutput> => {
        const { 
          connectionString: connStringArg,
          operation,
          table,
          data,
          where,
          conflictColumns,
          returning,
          schema
        } = args as {
          connectionString?: string;
          operation: 'insert' | 'update' | 'delete' | 'upsert';
          table: string;
          data?: Record<string, unknown>;
          where?: string;
          conflictColumns?: string[];
          returning?: string;
          schema?: string;
        };
    
        const resolvedConnString = getConnectionStringVal(connStringArg);
    
        try {
          // Input validation
          if (!table?.trim()) {
            return { 
              content: [{ type: 'text', text: 'Error: table is required' }], 
              isError: true 
            };
          }
    
          const result = await executeMutation({
            connectionString: resolvedConnString,
            operation,
            table,
            data,
            where,
            conflictColumns,
            returning,
            schema: schema || 'public'
          } as ExecuteMutationInput, getConnectionStringVal);
    
          let responseText = `${operation.toUpperCase()} operation completed successfully. Rows affected: ${result.rowsAffected}`;
          
          if (result.returning && result.returning.length > 0) {
            responseText += `\n\nReturning data:\n${JSON.stringify(result.returning, null, 2)}`;
          }
    
          return { content: [{ type: 'text', text: responseText }] };
    
        } catch (error) {
          return { 
            content: [{ type: 'text', text: `Error executing ${operation} operation: ${error instanceof Error ? error.message : String(error)}` }], 
            isError: true 
          };
        }
      }
    };
  • src/index.ts:225-257 (registration)
    Inclusion of executeMutationTool in the allTools array passed to the MCP server constructor for registration.
    const allTools: PostgresTool[] = [
      // Core Analysis & Debugging
      analyzeDatabaseTool,
      debugDatabaseTool,
      
      // Schema & Structure Management (Meta-Tools)
      manageSchemaTools,
      manageFunctionsTool,
      manageTriggersTools,
      manageIndexesTool,
      manageConstraintsTool,
      manageRLSTool,
      
      // User & Security Management
      manageUsersTool,
      
      // Query & Performance Management
      manageQueryTool,
      
      // Data Operations (Enhancement Tools)
      executeQueryTool,
      executeMutationTool,
      executeSqlTool,
      
      // Documentation & Metadata
      manageCommentsTool,
      
      // Data Migration & Monitoring
      exportTableDataTool,
      importTableDataTool,
      copyBetweenDatabasesTool,
      monitorDatabaseTool
    ];
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states this is for data modification operations, implying mutations, but doesn't cover critical behaviors: no mention of permissions required, transaction handling, error behavior, or what happens on failure. The example shows basic usage but lacks depth on constraints, side effects, or safety considerations for a mutation tool.

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

Conciseness4/5

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

The description is appropriately concise with two sentences: a clear purpose statement followed by a concrete example. The example efficiently demonstrates key parameters. No wasted words, though it could be slightly more structured by separating usage notes from the example.

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

Completeness2/5

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

For a complex mutation tool with 8 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain return values, error handling, transaction behavior, or security implications. The example helps but doesn't compensate for missing behavioral context needed for safe database operations.

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 8 parameters thoroughly. The description adds minimal value beyond the schema: it mentions operation, table, and data in the example but doesn't explain parameter interactions (e.g., when 'where' is required) or provide additional context. Baseline 3 is appropriate when schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Execute data modification operations (INSERT/UPDATE/DELETE/UPSERT)' with specific verbs and resources. It distinguishes from sibling tools like pg_execute_query by focusing on mutations rather than queries, though it doesn't explicitly name alternatives. The example reinforces the purpose but doesn't fully differentiate from all siblings.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It mentions the operation types but doesn't explain when to choose insert vs update vs delete vs upsert, nor does it reference sibling tools like pg_execute_query for read operations or pg_manage_* tools for schema changes. Usage context is implied but not explicit.

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/postgresql-mcp-server'

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