Skip to main content
Glama
antonorlov

MCP PostgreSQL Server

execute

Execute INSERT, UPDATE, or DELETE queries to modify PostgreSQL database data through parameterized SQL statements.

Instructions

Execute an INSERT, UPDATE, or DELETE query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYesSQL query (INSERT, UPDATE, DELETE) (use $1, $2, etc. for parameters)
paramsNoQuery parameters (optional)

Implementation Reference

  • The handler function that implements the core logic for the 'execute' tool. It ensures database connection, validates non-SELECT SQL, converts parameters if needed, executes the query, and returns rowCount and command.
    private async handleExecute(args: any) {
      await this.ensureConnection();
    
      if (!args.sql) {
        throw new McpError(ErrorCode.InvalidParams, 'SQL query is required');
      }
    
      const sql = args.sql.trim().toUpperCase();
      if (sql.startsWith('SELECT')) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Use query tool for SELECT statements'
        );
      }
    
      try {
        // Convert ? parameters to $1, $2, etc. if needed
        const preparedSql = args.sql.includes('?') ? convertToNamedParams(args.sql) : args.sql;
        const result = await this.client!.query(preparedSql, args.params || []);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                rowCount: result.rowCount,
                command: result.command,
              }, null, 2),
            },
          ],
        };
      } catch (error) {
        throw new McpError(
          ErrorCode.InternalError,
          `Query execution failed: ${getErrorMessage(error)}`
        );
      }
    }
  • The schema definition for the 'execute' tool as returned by listTools, specifying input schema with required 'sql' and optional 'params'.
    {
      name: 'execute',
      description: 'Execute an INSERT, UPDATE, or DELETE query',
      inputSchema: {
        type: 'object',
        properties: {
          sql: {
            type: 'string',
            description: 'SQL query (INSERT, UPDATE, DELETE) (use $1, $2, etc. for parameters)',
          },
          params: {
            type: 'array',
            items: {
              type: ['string', 'number', 'boolean', 'null'],
            },
            description: 'Query parameters (optional)',
          },
        },
        required: ['sql'],
      },
    },
  • src/index.ts:261-262 (registration)
    Registration/dispatch of the 'execute' tool handler in the CallToolRequestSchema switch statement.
    case 'execute':
      return await this.handleExecute(request.params.arguments);
  • Helper utility to convert SQL ? placeholders to PostgreSQL positional parameters $1, $2, etc., used in the execute handler.
    function convertToNamedParams(query: string): string {
      let paramIndex = 0;
      return query.replace(/\?/g, () => `$${++paramIndex}`);
    }
  • src/index.ts:137-253 (registration)
    The listTools handler that registers/declares the 'execute' tool with its schema.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'connect_db',
          description: 'Connect to PostgreSQL database. NOTE: Default connection exists - only use when requested or if other commands fail',
          inputSchema: {
            type: 'object',
            properties: {
              host: {
                type: 'string',
                description: 'Database host',
              },
              port: {
                type: 'number',
                description: 'Database port (default: 5432)',
              },
              user: {
                type: 'string',
                description: 'Database user',
              },
              password: {
                type: 'string',
                description: 'Database password',
              },
              database: {
                type: 'string',
                description: 'Database name',
              },
            },
            required: ['host', 'user', 'password', 'database'],
          },
        },
        {
          name: 'query',
          description: 'Execute a SELECT query',
          inputSchema: {
            type: 'object',
            properties: {
              sql: {
                type: 'string',
                description: 'SQL SELECT query (use $1, $2, etc. for parameters)',
              },
              params: {
                type: 'array',
                items: {
                  type: ['string', 'number', 'boolean', 'null'],
                },
                description: 'Query parameters (optional)',
              },
            },
            required: ['sql'],
          },
        },
        {
          name: 'execute',
          description: 'Execute an INSERT, UPDATE, or DELETE query',
          inputSchema: {
            type: 'object',
            properties: {
              sql: {
                type: 'string',
                description: 'SQL query (INSERT, UPDATE, DELETE) (use $1, $2, etc. for parameters)',
              },
              params: {
                type: 'array',
                items: {
                  type: ['string', 'number', 'boolean', 'null'],
                },
                description: 'Query parameters (optional)',
              },
            },
            required: ['sql'],
          },
        },
        {
          name: 'list_schemas',
          description: 'List all schemas in the database',
          inputSchema: {
            type: 'object',
            properties: {},
            required: [],
          },
        },
        {
          name: 'list_tables',
          description: 'List tables in the database',
          inputSchema: {
            type: 'object',
            properties: {
              schema: {
                type: 'string',
                description: 'Schema name (default: public)',
              },
            },
            required: [],
          },
        },
        {
          name: 'describe_table',
          description: 'Get table structure',
          inputSchema: {
            type: 'object',
            properties: {
              table: {
                type: 'string',
                description: 'Table name',
              },
              schema: {
                type: 'string',
                description: 'Schema name (default: public)',
              },
            },
            required: ['table'],
          },
        },
      ],
    }));
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. While it indicates this is a mutation tool (INSERT, UPDATE, DELETE), it doesn't cover critical aspects like required permissions, transaction behavior, error handling, rate limits, or what happens on success/failure. The description is insufficient for a tool that modifies data.

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, efficient sentence with zero wasted words. It's appropriately sized and front-loaded with the core functionality.

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 mutation tool with no annotations and no output schema, the description is incomplete. It doesn't address behavioral expectations, error conditions, or return values. Given the complexity of executing data-modifying SQL queries, this leaves significant gaps for an AI agent.

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 both parameters thoroughly. The description doesn't add any meaningful semantic context beyond what's in the schema (e.g., it doesn't explain parameter binding patterns or SQL injection risks). Baseline 3 is appropriate 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.

Purpose4/5

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

The description clearly states the tool executes SQL queries (INSERT, UPDATE, DELETE), which is a specific verb+resource combination. However, it doesn't distinguish this tool from its sibling 'query' tool, which likely handles SELECT queries, leaving some ambiguity about when to use each.

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 like the 'query' sibling tool. It mentions the types of SQL queries supported but doesn't specify prerequisites, exclusions, or contextual usage scenarios.

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

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