Skip to main content
Glama
melihbirim

PostgreSQL MCP Server

by melihbirim

execute_query

Run read-only SQL queries (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH) on PostgreSQL databases, with optional row limits, to retrieve or analyze data securely.

Instructions

Execute a read-only SQL query (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH statements only)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNoMaximum number of rows to return (default: 100)
queryYesSQL query to execute (read-only operations only)

Implementation Reference

  • The handler function for the 'execute_query' tool. It processes the input query and limit, adds a LIMIT if necessary for SELECT queries, executes the query using the helper executeQuery, formats the results as a markdown table, and returns them. Includes error handling.
    async ({ query, limit }) => {
      try {
        const maxLimit = limit || 100;
        
        // Add LIMIT clause if not present and it's a SELECT query
        let finalQuery = query.trim();
        const normalizedQuery = finalQuery.toLowerCase();
        
        if (normalizedQuery.startsWith('select') && !normalizedQuery.includes('limit')) {
          finalQuery += ` LIMIT ${maxLimit}`;
        }
        
        const rows = await executeQuery(finalQuery);
        
        if (rows.length === 0) {
          return {
            content: [
              {
                type: "text",
                text: "Query executed successfully. No rows returned.",
              },
            ],
          };
        }
    
        // Format results as a table
        const headers = Object.keys(rows[0]);
        let result = `Query Results (${rows.length} rows):\n\n`;
        
        // Add headers
        result += headers.join(' | ') + '\n';
        result += headers.map(() => '---').join(' | ') + '\n';
        
        // Add rows
        rows.forEach(row => {
          const values = headers.map(header => {
            const value = row[header];
            return value === null ? 'NULL' : String(value);
          });
          result += values.join(' | ') + '\n';
        });
    
        return {
          content: [
            {
              type: "text",
              text: result,
            },
          ],
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error";
        return {
          content: [
            {
              type: "text",
              text: `Error executing query: ${errorMessage}`,
            },
          ],
        };
      }
    }
  • Zod schema defining the input parameters for the 'execute_query' tool: required 'query' string and optional 'limit' number.
    {
      query: z.string().describe("SQL query to execute (read-only operations only)"),
      limit: z.number().describe("Maximum number of rows to return (default: 100)").optional(),
    },
  • src/index.ts:294-363 (registration)
    Registration of the 'execute_query' tool using server.tool(), including name, description, input schema, and handler function.
    server.tool(
      "execute_query",
      "Execute a read-only SQL query (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH statements only)",
      {
        query: z.string().describe("SQL query to execute (read-only operations only)"),
        limit: z.number().describe("Maximum number of rows to return (default: 100)").optional(),
      },
      async ({ query, limit }) => {
        try {
          const maxLimit = limit || 100;
          
          // Add LIMIT clause if not present and it's a SELECT query
          let finalQuery = query.trim();
          const normalizedQuery = finalQuery.toLowerCase();
          
          if (normalizedQuery.startsWith('select') && !normalizedQuery.includes('limit')) {
            finalQuery += ` LIMIT ${maxLimit}`;
          }
          
          const rows = await executeQuery(finalQuery);
          
          if (rows.length === 0) {
            return {
              content: [
                {
                  type: "text",
                  text: "Query executed successfully. No rows returned.",
                },
              ],
            };
          }
    
          // Format results as a table
          const headers = Object.keys(rows[0]);
          let result = `Query Results (${rows.length} rows):\n\n`;
          
          // Add headers
          result += headers.join(' | ') + '\n';
          result += headers.map(() => '---').join(' | ') + '\n';
          
          // Add rows
          rows.forEach(row => {
            const values = headers.map(header => {
              const value = row[header];
              return value === null ? 'NULL' : String(value);
            });
            result += values.join(' | ') + '\n';
          });
    
          return {
            content: [
              {
                type: "text",
                text: result,
              },
            ],
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : "Unknown error";
          return {
            content: [
              {
                type: "text",
                text: `Error executing query: ${errorMessage}`,
              },
            ],
          };
        }
      }
    );
  • Helper function 'executeQuery' that performs the actual database query execution with read-only safety checks. Used by the 'execute_query' handler and other tools.
    async function executeQuery(query: string, params: any[] = []): Promise<any[]> {
      const client = await getDbConnection();
      
      // Basic safety checks for read-only operations
      const normalizedQuery = query.trim().toLowerCase();
      const readOnlyPrefixes = ['select', 'show', 'describe', 'explain', 'with'];
      const isReadOnly = readOnlyPrefixes.some(prefix => normalizedQuery.startsWith(prefix));
      
      if (!isReadOnly) {
        throw new Error("Only read-only queries (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH) are allowed for security.");
      }
      
      try {
        const result = await client.query(query, params);
        return result.rows;
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
        throw new Error(`Query execution failed: ${errorMessage}`);
      }
    }
Behavior3/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 clearly states the read-only constraint and acceptable statement types, which is valuable. However, it doesn't mention important behavioral aspects like error handling, timeout behavior, result format, or authentication requirements that would be helpful for an agent.

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 that communicates the essential information with zero waste. It's appropriately sized and front-loaded with the core purpose, making it easy for an agent to parse quickly.

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

Completeness3/5

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

For a query execution tool with no annotations and no output schema, the description provides adequate but minimal information. It covers the read-only constraint and acceptable statement types, but doesn't address result format, error conditions, or performance characteristics that would help an agent use it effectively.

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 fully documents both parameters. The description adds no additional parameter information beyond what's in the schema descriptions. The baseline of 3 is appropriate when the schema does all the parameter documentation work.

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 'SQL query', specifying it's for read-only operations with explicit statement types (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH). It distinguishes from siblings like describe_table and get_schema by focusing on arbitrary query execution rather than metadata retrieval.

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 about when to use this tool (for read-only SQL queries) and implicitly distinguishes it from siblings by not being for connection management or schema inspection. However, it doesn't explicitly state when NOT to use it or name specific alternatives for different query types.

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/melihbirim/pg-mcp'

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