Skip to main content
Glama
martymarkenson

PostgreSQL MCP Server

Execute SQL Query

execute-sql-query

Execute SELECT queries on a PostgreSQL database to retrieve data securely. Only read-only operations are permitted.

Instructions

Execute a SQL query on the database. Only SELECT statements are allowed for security.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYesThe SQL query to execute

Implementation Reference

  • The async handler function for execute-sql-query. Validates SQL using sqlValidation, then executes it via initDb().unsafe(sql) and returns the JSON-stringified results, or an error message on failure.
      async ({ sql }) => {
        const validation = sqlValidation(sql);
        if (!validation.success) {
          return {
            content: [{
              type: "text",
              text: `❌ Query validation failed: ${validation.message}`
            }],
            isError: true
          };
        }
        try {
          const results = await initDb().unsafe(sql);
          return {
            content: [{
              type: "text",
              text: JSON.stringify(results, null, 2)
            }]
          };
        } catch (err: unknown) {
          const error = err as Error;
          return {
            content: [{
              type: "text",
              text: `❌ Query execution failed: ${error.message}`
            }],
            isError: true
          };
        }
      }
    );
  • The input schema for execute-sql-query, defining a single 'sql' parameter of type string via Zod.
    {
      title: "Execute SQL Query",
      description: "Execute a SQL query on the database. Only SELECT statements are allowed for security.",
      inputSchema: {
        sql: z.string().describe("The SQL query to execute")
      },
  • src/server.ts:165-204 (registration)
    Registration of the 'execute-sql-query' tool using server.registerTool with title, description, inputSchema, and handler.
    server.registerTool(
      "execute-sql-query",
      {
        title: "Execute SQL Query",
        description: "Execute a SQL query on the database. Only SELECT statements are allowed for security.",
        inputSchema: {
          sql: z.string().describe("The SQL query to execute")
        },
      },
      async ({ sql }) => {
        const validation = sqlValidation(sql);
        if (!validation.success) {
          return {
            content: [{
              type: "text",
              text: `❌ Query validation failed: ${validation.message}`
            }],
            isError: true
          };
        }
        try {
          const results = await initDb().unsafe(sql);
          return {
            content: [{
              type: "text",
              text: JSON.stringify(results, null, 2)
            }]
          };
        } catch (err: unknown) {
          const error = err as Error;
          return {
            content: [{
              type: "text",
              text: `❌ Query execution failed: ${error.message}`
            }],
            isError: true
          };
        }
      }
    );
  • The sqlValidation helper function that checks SQL for dangerous keywords (DROP, DELETE, TRUNCATE, ALTER, CREATE, INSERT, UPDATE) to ensure only SELECT statements are executed.
    function sqlValidation(sql: string) {
      const dangerousKeywords = ["DROP", "DELETE", "TRUNCATE", "ALTER", "CREATE", "INSERT", "UPDATE"];
      
      // check if these keywords appear at the start of statements allows them in column names, comments, etc.
      const statements = sql.split(';').map(s => s.trim()).filter(s => s.length > 0);
      
      for (const statement of statements) {
        // Skip empty statements and comments
        if (!statement || statement.startsWith('--') || statement.startsWith('/*')) {
          continue;
        }
        
        // Check if statement starts with a dangerous keyword
        const firstWord = statement.split(/\s+/)[0].toUpperCase();
        if (dangerousKeywords.includes(firstWord)) {
          return {
            success: false,
            message: `Dangerous operation detected: ${firstWord}. Only SELECT statements are allowed.`
          };
        }
      }
      
      return {
        success: true,
        message: "SQL is safe"
      };
    }
  • The initDb helper function that lazily initializes and returns the database connection.
    const initDb = () => {
      if(!dbConnection) {
        dbConnection = getDb();
      }
      return dbConnection;
    };
Behavior3/5

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

No annotations provided, so description carries full burden. It discloses the SELECT-only constraint but omits behaviors like result format, error handling, or execution limits. This is minimal for a read-only query tool.

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 no unnecessary words. It front-loads the purpose and constraint.

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?

For a tool with one parameter and no output schema, the description covers purpose and constraint well. However, it lacks details on output format or error behavior, which would enhance completeness for an 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 coverage is 100%, and the description adds no extra meaning to the 'sql' parameter beyond what the schema provides. Baseline 3 is appropriate as the schema already documents it adequately.

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', the resource 'SQL query on the database', and a critical constraint 'Only SELECT statements are allowed'. This distinguishes it from siblings like get-all-tables and test-postgres-connection.

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 a clear usage constraint ('Only SELECT statements') and a reason (security). It implicitly tells when to use (read queries) but doesn't explicitly state when not to or suggest alternatives, though siblings are limited.

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/martymarkenson/Postgres-Connector-MCP'

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