Skip to main content
Glama
cesarvarela

PostgreSQL MCP Server

by cesarvarela

query-table

Retrieve data from PostgreSQL tables using filtering, sorting, and pagination. Supports WHERE conditions with exact matches, IN arrays, and LIKE patterns for precise data extraction.

Instructions

Query data from a specific table with filtering, pagination, and sorting. Supports WHERE conditions with exact matches, arrays (IN), and LIKE patterns.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tableYes
columnsNo
whereNo
paginationNo
sortNo

Implementation Reference

  • The main handler function for the 'query-table' tool. Validates inputs, builds a dynamic SQL SELECT query with WHERE, ORDER BY, LIMIT/OFFSET clauses, executes it via executePostgresQuery, and returns paginated results with total count.
    export async function queryTable(
      rawParams: any
    ): McpToolResponse {
      try {
        // Validate and parse parameters
        const params = queryTableSchema.parse(rawParams);
        // Check database connection status
        const connectionStatus = getConnectionStatus();
        if (connectionStatus.status !== 'connected') {
          return createDatabaseUnavailableResponse("query table data");
        }
        
        const { table, columns, where, pagination, sort } = params;
    
        // Validate table name
        const sanitizedTable = sanitizeIdentifier(table);
    
        // Build SELECT clause
        let selectClause = "*";
        if (columns?.length) {
          const sanitizedColumns = columns.map((col: string) => sanitizeIdentifier(col));
          selectClause = sanitizedColumns.join(", ");
        }
    
        // Build WHERE clause
        let whereClause = "";
        let queryParams: any[] = [];
        let paramIndex = 1;
    
        if (where && Object.keys(where).length > 0) {
          const whereConditions: string[] = [];
          
          for (const [column, value] of Object.entries(where)) {
            const sanitizedColumn = sanitizeIdentifier(column);
            
            if (value === null) {
              whereConditions.push(`${sanitizedColumn} IS NULL`);
            } else if (Array.isArray(value)) {
              // Handle IN operator for arrays
              const placeholders = value.map(() => `$${paramIndex++}`).join(", ");
              whereConditions.push(`${sanitizedColumn} IN (${placeholders})`);
              queryParams.push(...value);
            } else if (typeof value === 'string' && value.includes('%')) {
              // Handle LIKE operator for strings with wildcards
              whereConditions.push(`${sanitizedColumn} LIKE $${paramIndex}`);
              queryParams.push(value);
              paramIndex++;
            } else {
              // Handle equality
              whereConditions.push(`${sanitizedColumn} = $${paramIndex}`);
              queryParams.push(value);
              paramIndex++;
            }
          }
          
          whereClause = `WHERE ${whereConditions.join(" AND ")}`;
        }
    
        // Build ORDER BY clause
        let orderClause = "";
        if (sort) {
          const sanitizedSortColumn = sanitizeIdentifier(sort.column);
          const direction = sort.direction || 'ASC';
          orderClause = `ORDER BY ${sanitizedSortColumn} ${direction}`;
        }
    
        // Build LIMIT/OFFSET clause
        let limitClause = "";
        if (pagination) {
          limitClause = `LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`;
          queryParams.push(pagination.limit, pagination.offset);
        }
    
        // Construct final query
        const query = `
          SELECT ${selectClause}
          FROM ${sanitizedTable}
          ${whereClause}
          ${orderClause}
          ${limitClause}
        `.trim().replace(/\s+/g, ' ');
    
        debug("Executing table query: %s", query);
        const results = await executePostgresQuery(query, queryParams);
        
        // Get total count for pagination info
        let totalCount: number | undefined;
        if (pagination) {
          const countQuery = `
            SELECT COUNT(*) as total
            FROM ${sanitizedTable}
            ${whereClause}
          `.trim().replace(/\s+/g, ' ');
          
          const countParams = queryParams.slice(0, queryParams.length - 2); // Remove limit/offset params
          const countResult = await executePostgresQuery(countQuery, countParams);
          totalCount = parseInt(countResult[0].total);
        }
        
        const response = {
          table: sanitizedTable,
          count: results.length,
          data: results,
          ...(totalCount !== undefined && {
            pagination: {
              total: totalCount,
              limit: pagination!.limit,
              offset: pagination!.offset,
              hasMore: pagination!.offset + pagination!.limit < totalCount,
            }
          }),
        };
    
        return createMcpSuccessResponse(response);
    
      } catch (error) {
        return createMcpErrorResponse("query table", error);
      }
    }
  • Zod schema (queryTableShape and queryTableSchema) defining the input parameters for the query-table tool: table (required), optional columns, where conditions, pagination, and sort.
    export const queryTableShape: ZodRawShape = {
      table: z.string().min(1, "Table name is required"),
      columns: z.array(z.string().min(1)).optional(),
      where: z.record(z.any()).optional(),
      pagination: paginationSchema.optional(),
      sort: sortSchema.optional(),
    };
    
    export const queryTableSchema = z.object(queryTableShape);
  • index.ts:27-32 (registration)
    Registration of the 'query-table' tool on the McpServer, providing name, description, input schema (queryTableShape), and handler (queryTable).
    server.tool(
      "query-table",
      "Query data from a specific table with filtering, pagination, and sorting. Supports WHERE conditions with exact matches, arrays (IN), and LIKE patterns.",
      queryTableShape,
      queryTable
    );
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. It mentions filtering capabilities (WHERE conditions with exact matches, arrays, and LIKE patterns) but omits critical behavioral details: whether this is a read-only operation, potential rate limits, error handling, or what the return format looks like (especially without an output schema). For a query tool with 5 parameters and no annotations, this is insufficient.

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, well-structured sentence that efficiently lists key features without redundancy. It's front-loaded with the core purpose and follows with supporting details. Every word earns its place, making it highly concise.

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 (5 parameters with nested objects, no annotations, no output schema), the description is incomplete. It lacks details on behavioral traits (e.g., read-only nature, error responses), full parameter semantics, and output format. For a query tool that likely returns data, the absence of output schema or description of return values is a significant gap.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the schema provides no parameter documentation. The description adds some value by mentioning filtering, pagination, and sorting, which map to 'where', 'pagination', and 'sort' parameters, and specifies support for exact matches, arrays (IN), and LIKE patterns for 'where'. However, it doesn't explain 'table' or 'columns' parameters, leaving 2 of 5 parameters undocumented, failing to compensate for the low coverage.

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's purpose: 'Query data from a specific table with filtering, pagination, and sorting.' It specifies the verb ('query'), resource ('data from a specific table'), and key capabilities. However, it doesn't explicitly differentiate from sibling tools like 'execute-query' or 'get-table-info', which prevents a perfect score.

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. With siblings like 'execute-query' (likely for raw SQL) and 'get-table-info' (likely for metadata), the agent has no indication of the appropriate context for this structured query tool. No exclusions or prerequisites are mentioned.

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

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