Skip to main content
Glama
HenkDz

PostgreSQL MCP Server

pg_execute_sql

Execute SQL statements on PostgreSQL databases with parameter support, transaction handling, and timeout control for data operations and schema management.

Instructions

Execute arbitrary SQL statements - sql="ANY_VALID_SQL" with optional parameters and transaction support. Examples: sql="CREATE INDEX ...", sql="WITH complex_cte AS (...) SELECT ...", transactional=true

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionStringNoPostgreSQL connection string (optional)
sqlYesSQL statement to execute (can be any valid PostgreSQL SQL)
parametersNoParameter values for prepared statement placeholders ($1, $2, etc.)
expectRowsNoWhether to expect rows back (false for statements like CREATE, DROP, etc.)
timeoutNoQuery timeout in milliseconds
transactionalNoWhether to wrap in a transaction

Implementation Reference

  • Full tool definition including the handler execute function for pg_execute_sql. This is the core implementation that handles tool calls, validates input, invokes the SQL execution helper, and formats the output.
    export const executeSqlTool: PostgresTool = {
      name: 'pg_execute_sql',
      description: 'Execute arbitrary SQL statements - sql="ANY_VALID_SQL" with optional parameters and transaction support. Examples: sql="CREATE INDEX ...", sql="WITH complex_cte AS (...) SELECT ...", transactional=true',
      inputSchema: ExecuteSqlInputSchema,
      execute: async (args: unknown, getConnectionStringVal: GetConnectionStringFn): Promise<ToolOutput> => {
        const { 
          connectionString: connStringArg,
          sql,
          parameters,
          expectRows,
          timeout,
          transactional
        } = args as {
          connectionString?: string;
          sql: string;
          parameters?: unknown[];
          expectRows?: boolean;
          timeout?: number;
          transactional?: boolean;
        };
    
        const resolvedConnString = getConnectionStringVal(connStringArg);
    
        try {
          // Input validation
          if (!sql?.trim()) {
            return { 
              content: [{ type: 'text', text: 'Error: sql is required' }], 
              isError: true 
            };
          }
    
          const result = await executeSql({
            connectionString: resolvedConnString,
            sql,
            parameters: parameters ?? [],
            expectRows: expectRows ?? true,
            timeout,
            transactional: transactional ?? false
          }, getConnectionStringVal);
    
          let responseText = result.message;
          
          if (result.rows && result.rows.length > 0) {
            responseText += `\n\nResults:\n${JSON.stringify(result.rows, null, 2)}`;
          }
    
          return { content: [{ type: 'text', text: responseText }] };
    
        } catch (error) {
          return { 
            content: [{ type: 'text', text: `Error executing SQL: ${error instanceof Error ? error.message : String(error)}` }], 
            isError: true 
          };
        }
      }
    }; 
  • Zod schema for input validation of pg_execute_sql tool parameters.
    const ExecuteSqlInputSchema = z.object({
      connectionString: z.string().optional().describe('PostgreSQL connection string (optional)'),
      sql: z.string().describe('SQL statement to execute (can be any valid PostgreSQL SQL)'),
      parameters: z.array(z.unknown()).optional().default([]).describe('Parameter values for prepared statement placeholders ($1, $2, etc.)'),
      expectRows: z.boolean().optional().default(true).describe('Whether to expect rows back (false for statements like CREATE, DROP, etc.)'),
      timeout: z.number().optional().describe('Query timeout in milliseconds'),
      transactional: z.boolean().optional().default(false).describe('Whether to wrap in a transaction')
    });
  • Helper function that performs the actual database connection, SQL execution (supporting transactions), result processing, and error handling for pg_execute_sql.
    async function executeSql(
      input: ExecuteSqlInput,
      getConnectionString: GetConnectionStringFn
    ): Promise<{ sql: string; rowsAffected?: number; rows?: unknown[]; message: string }> {
      const resolvedConnectionString = getConnectionString(input.connectionString);
      const db = DatabaseConnection.getInstance();
      const { sql, parameters, expectRows, timeout, transactional } = input;
    
      try {
        await db.connect(resolvedConnectionString);
        
        const queryOptions = timeout ? { timeout } : {};
    
        if (transactional) {
          return await db.transaction(async (client) => {
            const result = await client.query(sql, parameters || []);
            
            if (expectRows) {
              return {
                sql,
                rowsAffected: Array.isArray(result.rows) ? result.rows.length : 0,
                rows: result.rows,
                message: `SQL executed successfully in transaction. Retrieved ${Array.isArray(result.rows) ? result.rows.length : 0} rows.`
              };
            }
            return {
              sql,
              rowsAffected: result.rowCount || 0,
              message: `SQL executed successfully in transaction. Rows affected: ${result.rowCount || 0}`
            };
          });
        }
        const result = await db.query(sql, parameters || [], queryOptions);
        
        if (expectRows) {
          return {
            sql,
            rowsAffected: Array.isArray(result) ? result.length : 0,
            rows: result,
            message: `SQL executed successfully. Retrieved ${Array.isArray(result) ? result.length : 0} rows.`
          };
        }
        return {
          sql,
          rowsAffected: Array.isArray(result) ? result.length : 1,
          message: 'SQL executed successfully. Operation completed.'
        };
      } catch (error) {
        throw new McpError(ErrorCode.InternalError, `Failed to execute SQL: ${error instanceof Error ? error.message : String(error)}`);
      } finally {
        await db.disconnect();
      }
    }
  • src/index.ts:30-30 (registration)
    Import of the pg_execute_sql tool (as executeSqlTool) from data.ts.
    import { executeQueryTool, executeMutationTool, executeSqlTool } from './tools/data.js';
  • src/index.ts:245-247 (registration)
    Registration of pg_execute_sql tool (executeSqlTool) in the allTools array passed to the MCP server constructor.
    executeQueryTool,
    executeMutationTool,
    executeSqlTool,
Behavior2/5

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

With no annotations provided, the description carries full burden but only mentions transaction support. It doesn't disclose critical behavioral traits like whether this can execute destructive operations (DROP, DELETE), authentication requirements, rate limits, error handling, or what happens when expectRows mismatches query type.

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 efficiently structured in a single sentence with embedded examples, front-loading the core purpose. Every element (arbitrary SQL, parameter support, transaction support, examples) earns its place without redundancy.

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 powerful SQL execution tool with 6 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain return values, error behavior, security implications, or how parameters interact (e.g., transactional with expectRows). The complexity demands more complete 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 already documents all parameters thoroughly. The description adds minimal value by mentioning 'optional parameters and transaction support' and providing examples that hint at sql parameter usage, but doesn't add meaningful semantics beyond what the schema provides.

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 verb ('Execute') and resource ('arbitrary SQL statements'), with specific examples showing the scope. It distinguishes from siblings like pg_execute_query and pg_execute_mutation by emphasizing 'arbitrary' SQL capability.

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 with examples (CREATE INDEX, WITH complex_cte) and mentions transactional support, but doesn't explicitly state when to use this vs. specialized siblings like pg_execute_query for read-only operations or pg_execute_mutation for write operations.

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