Skip to main content
Glama
Maxim2324

MCP PostgreSQL Server

by Maxim2324

query

Run SELECT queries on PostgreSQL databases securely using SQL commands and parameters. Explore schemas, analyze data, and retrieve results efficiently with this MCP tool.

Instructions

Execute a SELECT query

Input Schema

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

Implementation Reference

  • Core handler function that validates input, executes the SQL query via model, logs performance, and formats results. This implements the main logic of the 'query' tool.
    async executeQuery(query, params = []) {
      const startTime = Date.now();
      
      try {
        // Validate input
        this.validateQueryInput(query, params);
        
        const results = await this.queryModel.executeQuery(query, params);
        logQuery(query, params);
        logPerformance('query_execution', Date.now() - startTime);
        
        return this.formatResults(results);
      } catch (error) {
        if (error instanceof ValidationError) {
          throw error;
        }
        throw new Error(`Query execution failed: ${error.message}`);
      }
    }
  • Input validation and schema checking for SQL queries, ensuring read-only, no injection risks, no unsafe functions.
    validateQuery(sql) {
      if (!sql || typeof sql !== 'string') {
        return {
          isValid: false,
          errors: ['Query cannot be empty']
        };
      }
      
      const errors = [];
      
      // Check if query is read-only
      if (!this.isReadOnly(sql)) {
        errors.push('Only read-only queries are allowed');
      }
      
      // Check for commenting out parts of the query (potential SQL injection techniques)
      if (/--.*$/m.test(sql)) {
        errors.push('SQL comments are not allowed');
      }
      
      // Check for multiple statements (potential SQL injection)
      if (/;\s*\w+/i.test(sql)) {
        errors.push('Multiple SQL statements are not allowed');
      }
      
      // Check for potentially unsafe functions
      const unsafeFunctions = [
        /\bcopy\s*\(/i,
        /\bpg_read_file\s*\(/i,
        /\bpg_read_binary_file\s*\(/i,
        /\bpg_sleep\s*\(/i,
        /\bpg_terminate_backend\s*\(/i
      ];
      
      for (const pattern of unsafeFunctions) {
        if (pattern.test(sql)) {
          errors.push('Query contains potentially unsafe functions');
          break;
        }
      }
      
      return {
        isValid: errors.length === 0,
        errors
      };
    }
  • Registers the 'query' tool endpoint as POST /query with rate limiting and validation middleware.
    router.post('/query', 
        rateLimit('query', 100), 
        validateQuery, 
        queryController.executeQuery
    );
  • Database-level helper that executes the actual SQL query with timeout, row limits, and metadata extraction.
    async executeQuery(sql, params = [], timeout = config.query.maxExecutionTime) {
      const client = await dbConnector.getClient();
      
      try {
        // Set statement timeout
        await client.query(`SET statement_timeout TO ${timeout};`);
        
        const startTime = Date.now();
        const result = await client.query(sql, params);
        const executionTime = Date.now() - startTime;
        
        // Limit the number of rows returned
        const limitedRows = result.rows.slice(0, config.query.maxRowsReturned);
        const rowsLimited = result.rows.length > config.query.maxRowsReturned;
        
        return {
          rows: limitedRows,
          rowCount: result.rowCount,
          fields: result.fields.map(field => ({
            name: field.name,
            dataTypeID: field.dataTypeID,
            dataType: this._getDataTypeName(field.dataTypeID)
          })),
          metadata: {
            executionTime,
            rowsLimited,
            totalRows: result.rowCount,
            returnedRows: limitedRows.length,
            query: sql,
            params
          }
        };
      } catch (error) {
        throw error;
      } finally {
        client.release();
      }
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. It states the action ('Execute a SELECT query') but doesn't describe what happens: whether it returns results, error handling, performance implications, or security constraints (e.g., read-only access). For a query execution tool, this leaves critical behavioral traits unspecified.

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 waste. It's front-loaded with the core action and resource, making it immediately understandable without unnecessary elaboration. Every word earns its place by directly conveying the tool's purpose.

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?

Given the complexity of a database query tool with no annotations and no output schema, the description is incomplete. It doesn't explain return values (e.g., result sets, error formats), usage context (e.g., requires prior connection), or limitations (e.g., query timeout, row limits). For a tool that executes arbitrary SQL, 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 ('sql' and 'params') with clear descriptions. The description adds no additional meaning beyond what the schema provides, such as examples of valid SQL syntax or parameter binding details. 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 verb ('Execute') and resource ('SELECT query'), making the purpose unambiguous. It distinguishes from siblings like 'connect_db' or 'list_tables' by focusing on query execution rather than connection or metadata listing. However, it doesn't explicitly differentiate from 'execute' which might handle non-SELECT queries, leaving some ambiguity.

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 'execute' (which might handle INSERT/UPDATE) or 'describe_table' (for schema inspection). It lacks context about prerequisites (e.g., requires an established database connection) or exclusions (e.g., only for SELECT queries, not data modification).

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

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