Skip to main content
Glama
1Levick3

PostgreSQL MCP Server

by 1Levick3

execute_custom_query

Execute custom SQL queries on PostgreSQL databases to retrieve, analyze, or modify data directly through database connections.

Instructions

Execute a custom SQL query against the database. WARNING: Use with care. Do not expose to untrusted input.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionStringYesPostgreSQL connection string
queryYesSQL query to execute
valuesNoOptional parameter values for the query
timeoutNoOptional query timeout in milliseconds

Implementation Reference

  • Core implementation of the executeCustomQuery tool handler that connects to the database, executes the SQL query with optional parameters and timeout, and returns a structured result.
    export async function executeCustomQuery(
      connectionString: string,
      query: string,
      values: unknown[] = [],
      options: { timeout?: number } = {}
    ): Promise<CustomQueryResult> {
      const db = DatabaseConnection.getInstance();
      try {
        await db.connect(connectionString);
        const result = await db.query(query, values, options);
        return {
          success: true,
          message: 'Query executed successfully',
          details: result
        };
      } catch (error) {
        return {
          success: false,
          message: `Query execution failed: ${error instanceof Error ? error.message : String(error)}`,
          details: null
        };
      } finally {
        await db.disconnect();
      }
    } 
  • Tool definition including name, description, and detailed input schema for validation.
    const TOOL_DEFINITIONS = [
      {
        name: 'execute_custom_query',
        description: 'Execute a custom SQL query against the database. WARNING: Use with care. Do not expose to untrusted input.',
        inputSchema: {
          type: 'object',
          properties: {
            connectionString: {
              type: 'string',
              description: 'PostgreSQL connection string'
            },
            query: {
              type: 'string',
              description: 'SQL query to execute'
            },
            values: {
              type: 'array',
              description: 'Optional parameter values for the query',
              items: { type: 'string' }
            },
            timeout: {
              type: 'number',
              description: 'Optional query timeout in milliseconds'
            }
          },
          required: ['connectionString', 'query']
        }
      }
    ];
  • src/index.ts:68-73 (registration)
    Registers the tool in the MCP server capabilities.tools dictionary.
    capabilities: {
      tools: TOOL_DEFINITIONS.reduce((acc, tool) => {
        acc[tool.name] = tool;
        return acc;
      }, {} as Record<string, any>),
    },
  • src/index.ts:101-117 (registration)
    Registers the tool handler in the CallToolRequestSchema switch statement, extracting arguments, calling the implementation, and formatting the MCP response.
    case 'execute_custom_query': {
      const { connectionString, query, values, timeout } = request.params.arguments as {
        connectionString: string;
        query: string;
        values?: unknown[];
        timeout?: number;
      };
      const result = await executeCustomQuery(connectionString, query, values ?? [], { timeout });
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2)
          }
        ]
      };
    }
Behavior4/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 effectively communicates critical behavioral traits: that this is a potentially dangerous operation (executing arbitrary SQL), includes security warnings, and implies it can modify data. However, it doesn't specify what happens on success/failure, whether transactions are used, or what format results are returned in.

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 perfectly concise with just two sentences that each earn their place: the first states the core functionality, the second provides critical warnings. It's front-loaded with the main purpose and appropriately sized for the tool's complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a potentially destructive database operation with no annotations and no output schema, the description provides adequate but incomplete context. It covers the dangerous nature and security considerations well, but doesn't explain what happens on execution (e.g., returns results, affects rows), error handling, or result formats, leaving gaps for the agent to navigate.

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?

With 100% schema description coverage, the schema already documents all 4 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema, so it meets the baseline expectation but doesn't provide additional value regarding parameter usage or semantics.

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

Purpose5/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 with a specific verb ('execute') and resource ('custom SQL query against the database'), making it immediately understandable. It distinguishes what this tool does from potential alternatives by specifying it's for custom SQL execution rather than predefined operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear contextual guidance with the 'WARNING: Use with care. Do not expose to untrusted input' statement, which helps the agent understand appropriate usage scenarios and security considerations. However, it doesn't specify when to use this tool versus alternative query methods or database tools since no sibling tools are listed.

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/1Levick3/postgresql-mcp-server'

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