Skip to main content
Glama
HenkDz

PostgreSQL MCP Server

pg_debug_database

Debug common PostgreSQL database issues including connection problems, performance bottlenecks, lock conflicts, and replication errors to identify and resolve database problems.

Instructions

Debug common PostgreSQL issues

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionStringNo
issueYes
logLevelNoinfo

Implementation Reference

  • Handler implementation for the pg_debug_database tool, including input validation, execution of core debug logic, and formatting of output.
    export const debugDatabaseTool: PostgresTool = {
      name: 'pg_debug_database',
      description: 'Debug common PostgreSQL issues',
      inputSchema: DebugDatabaseInputSchema,
      async execute(params: unknown, getConnectionString: GetConnectionStringFn): Promise<ToolOutput> {
        const validationResult = DebugDatabaseInputSchema.safeParse(params);
        if (!validationResult.success) {
          const errorDetails = validationResult.error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ');
          return {
            content: [{ type: 'text', text: `Invalid input: ${errorDetails}` }],
            isError: true,
          };
        }
        try {
          const result = await executeDebugDatabase(validationResult.data, getConnectionString);
          // Convert DebugResult to ToolOutput format
          return {
            content: [
              { type: 'text', text: `Debug Result for Issue: ${result.issue}` },
              { type: 'text', text: `Status: ${result.status}` },
              { type: 'text', text: `Details:\n${result.details.join('\n')}` },
              { type: 'text', text: `Recommendations:\n${result.recommendations.join('\n')}` },
            ],
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          return {
            content: [{ type: 'text', text: `Error debugging database: ${errorMessage}` }],
            isError: true,
          };
        }
      }
    };
  • Zod input schema defining parameters for the pg_debug_database tool.
    const DebugDatabaseInputSchema = z.object({
      connectionString: z.string().optional(),
      issue: z.enum(['connection', 'performance', 'locks', 'replication']),
      logLevel: z.enum(['info', 'debug', 'trace']).optional().default('info'),
    });
  • src/index.ts:227-228 (registration)
    Registration of debugDatabaseTool (pg_debug_database) in the allTools array, which is passed to the MCP PostgreSQLServer constructor.
    analyzeDatabaseTool,
    debugDatabaseTool,
  • Core helper function that handles database connection and dispatches to specific debug functions based on the issue type.
    async function executeDebugDatabase(
      input: DebugDatabaseInput,
      getConnectionString: GetConnectionStringFn
    ): Promise<DebugResult> {
      const resolvedConnectionString = getConnectionString(input.connectionString);
      const db = DatabaseConnection.getInstance();
    
      try {
        await db.connect(resolvedConnectionString);
    
        switch (input.issue) {
          case 'connection':
            return await debugConnection(db);
          case 'performance':
            return await debugPerformance(db);
          case 'locks':
            return await debugLocks(db);
          case 'replication':
            return await debugReplication(db);
          default:
            // This case should be unreachable due to Zod validation
            throw new McpError(ErrorCode.InvalidParams, `Unsupported issue type: ${input.issue}`);
        }
      } finally {
        // Ensure disconnect is called even if connect fails or other errors occur
        await db.disconnect();
      }
    }
  • Helper function for debugging connection issues, including max connections usage and idle connections.
    async function debugConnection(db: DatabaseConnection): Promise<DebugResult> {
      const result: DebugResult = {
        issue: 'connection',
        status: 'ok',
        details: [],
        recommendations: []
      };
    
      try {
        // Check max connections
        const maxConns = await db.query<{ setting: string }>(
          "SELECT setting FROM pg_settings WHERE name = 'max_connections'"
        );
        const currentConns = await db.query<{ count: string }>(
          'SELECT count(*) FROM pg_stat_activity'
        );
    
        const max = Number.parseInt(maxConns[0].setting);
        const current = Number.parseInt(currentConns[0].count);
        const percentage = (current / max) * 100;
    
        result.details.push(
          `Current connections: ${current}/${max} (${percentage.toFixed(1)}%)`
        );
    
        if (percentage > 80) {
          result.status = 'warning';
          result.recommendations.push(
            'High connection usage. Consider implementing connection pooling',
            'Review application connection handling',
            'Monitor for connection leaks'
          );
        }
    
        // Check for idle connections
        const idleConns = await db.query<{ count: string }>(
          "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle'"
        );
        const idleCount = Number.parseInt(idleConns[0].count);
        if (idleCount > 5) {
          result.details.push(`High number of idle connections: ${idleCount}`);
          result.recommendations.push(
            'Consider implementing connection timeouts',
            'Review connection pool settings'
          );
        }
    
      } catch (error: unknown) {
        result.status = 'error';
        result.details.push(`Connection error: ${error instanceof Error ? error.message : String(error)}`);
      }
    
      return result;
    }
Behavior2/5

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

With no annotations, the description carries full burden but only hints at behavior ('debug') without details on actions (e.g., read-only vs. destructive), side effects, or output. It fails to disclose critical traits like whether it modifies data, requires specific permissions, or handles errors.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with no wasted words, making it appropriately concise. However, it's under-specified rather than optimally structured for clarity.

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?

For a 3-parameter tool with no annotations, no output schema, and 0% schema coverage, the description is incomplete. It lacks details on behavior, parameters, and expected outcomes, making it inadequate for effective tool selection and invocation.

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 description must compensate but adds no parameter meaning. It doesn't explain what 'connectionString', 'issue', or 'logLevel' do, leaving all three parameters undocumented beyond their schema enums.

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

Purpose2/5

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

The description 'Debug common PostgreSQL issues' states a general purpose but lacks specificity about what 'debug' entails (e.g., diagnostics, analysis, fixes) and doesn't distinguish from siblings like pg_analyze_database or pg_monitor_database. It's vague about the verb and resource scope.

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

Usage Guidelines1/5

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

No guidance on when to use this tool versus alternatives is provided. It doesn't mention prerequisites, context, or exclusions, leaving the agent to guess based on the generic description and sibling names.

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

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