Skip to main content
Glama
antonorlov

MCP PostgreSQL Server

query

Execute SQL SELECT queries on PostgreSQL databases to retrieve data using parameterized statements for secure database interactions.

Instructions

Execute a SELECT query

Input Schema

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

Implementation Reference

  • The handler function that executes the 'query' tool logic: validates input, ensures DB connection, runs SELECT query with parameters, returns result rows as JSON.
    private async handleQuery(args: any) {
      await this.ensureConnection();
    
      if (!args.sql) {
        throw new McpError(ErrorCode.InvalidParams, 'SQL query is required');
      }
    
      if (!args.sql.trim().toUpperCase().startsWith('SELECT')) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Only SELECT queries are allowed with query tool'
        );
      }
    
      try {
        // Convert ? parameters to $1, $2, etc. if needed
        const sql = args.sql.includes('?') ? convertToNamedParams(args.sql) : args.sql;
        const result = await this.client!.query(sql, args.params || []);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(result.rows, null, 2),
            },
          ],
        };
      } catch (error) {
        throw new McpError(
          ErrorCode.InternalError,
          `Query execution failed: ${getErrorMessage(error)}`
        );
      }
    }
  • Input schema definition for the 'query' tool, specifying 'sql' as required string and optional 'params' array.
    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'],
    },
  • src/index.ts:169-189 (registration)
    Registration of the 'query' tool in the ListTools handler, including name, description, and schema.
    {
      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'],
      },
    },
  • Utility function used by the query handler to convert ? placeholders to PostgreSQL $1, $2, etc. parameters.
    function convertToNamedParams(query: string): string {
      let paramIndex = 0;
      return query.replace(/\?/g, () => `$${++paramIndex}`);
    }
  • src/index.ts:259-260 (registration)
    Dispatch/registration in the CallToolRequest handler switch statement routing 'query' calls to handleQuery.
    case 'query':
      return await this.handleQuery(request.params.arguments);
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. 'Execute a SELECT query' implies a read-only operation, but it doesn't confirm safety (e.g., that it won't modify data), describe error handling, rate limits, or authentication needs. For a database query tool with zero annotation coverage, 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 ('Execute a SELECT query'), making it immediately clear. Every word earns its place, and there's no unnecessary elaboration or repetition.

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 database operations and the lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., result sets, error messages), performance implications, or connection requirements. For a tool that executes SQL queries, more context is needed to guide the agent 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%, with both parameters ('sql' and 'params') well-documented in the schema. The description adds no parameter semantics beyond what the schema provides (e.g., it doesn't explain SQL syntax, parameter binding rules, or result formatting). With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't enhance parameter understanding.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

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

The description 'Execute a SELECT query' clearly states the verb ('Execute') and resource ('SELECT query'), making the purpose understandable. However, it doesn't distinguish this tool from its sibling 'execute' (which likely handles non-SELECT queries), leaving ambiguity about when to use each. The purpose is clear but lacks sibling differentiation.

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. It doesn't mention when to use 'query' vs 'execute' (a sibling tool), nor does it specify prerequisites like needing an established database connection. Without any usage context or exclusions, the agent must infer when this tool is appropriate.

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