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);

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