query
Execute SQL SELECT queries on PostgreSQL databases using parameterized inputs. Enables AI models to interact with data through standardized database operations.
Instructions
Execute a SELECT query
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| params | No | Query parameters (optional) | |
| sql | Yes | SQL SELECT query (use $1, $2, etc. for parameters) |
Implementation Reference
- src/index.ts:318-351 (handler)The private async handleQuery method implements the core logic for the 'query' tool: ensures DB connection, validates it's a SELECT query, handles parameter conversion, executes the query, and returns JSON-stringified rows.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)}` ); } }
- src/index.ts:172-188 (schema)Input schema definition for the 'query' tool, specifying required 'sql' string and optional 'params' array of primitive types.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)The 'query' tool is registered in the ListTools response with its name, description, and input 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'], }, },
- src/index.ts:259-260 (registration)In the CallToolRequest handler, the 'query' tool name is matched to dispatch to the handleQuery method.case 'query': return await this.handleQuery(request.params.arguments);
- src/index.ts:44-47 (helper)Helper function used by handleQuery (and handleExecute) to convert SQL queries with ? placeholders to PostgreSQL-compatible $1, $2, etc. numbered parameters.function convertToNamedParams(query: string): string { let paramIndex = 0; return query.replace(/\?/g, () => `$${++paramIndex}`); }