Skip to main content
Glama
cesarvarela

PostgreSQL MCP Server

by cesarvarela

connection-status

Check PostgreSQL database connection status, view error details, and retry connection when database is unavailable.

Instructions

Check database connection status, view error details, and retry connection. Use retry: true to attempt reconnection when database is unavailable.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
retryNo

Implementation Reference

  • The main handler function for the 'connection-status' tool. Validates input parameters, checks current connection status or performs retry if requested, and returns formatted response with troubleshooting information.
    export async function connectionStatus(
      rawParams: any
    ): McpToolResponse {
      try {
        // Validate and parse parameters
        const params = connectionStatusSchema.parse(rawParams);
        
        debug("Connection status tool called with retry: %s", params.retry);
        
        // If retry is requested, attempt to reconnect
        if (params.retry) {
          debug("Attempting connection retry...");
          const retrySuccess = await retryConnection();
          const status = getConnectionStatus();
          
          return createMcpSuccessResponse({
            action: "retry_attempted",
            connection_status: status.status,
            retry_successful: retrySuccess,
            error: status.error,
            last_attempt: status.lastAttempt,
            message: retrySuccess 
              ? "Database connection retry successful" 
              : `Database connection retry failed: ${status.error}`,
            troubleshooting: retrySuccess ? null : {
              common_issues: [
                "Check if PostgreSQL server is running",
                "Verify DATABASE_URL environment variable is correct", 
                "Ensure database credentials are valid",
                "Check network connectivity to database server",
                "Verify firewall settings allow database connections"
              ],
              next_steps: [
                "Review your database configuration in .env file",
                "Test connection manually with psql or database client",
                "Check database server logs for connection errors",
                "Use connection-status tool with retry: true to test again"
              ]
            }
          });
        }
        
        // Return current status without retry attempt
        const status = getConnectionStatus();
        
        return createMcpSuccessResponse({
          connection_status: status.status,
          error: status.error,
          last_attempt: status.lastAttempt,
          message: status.status === 'connected' 
            ? "Database connection is healthy" 
            : status.status === 'failed'
            ? `Database connection failed: ${status.error}`
            : "Database connection status unknown - no connection attempt made yet",
          retry_available: true,
          troubleshooting: status.status === 'failed' ? {
            common_issues: [
              "Check if PostgreSQL server is running",
              "Verify DATABASE_URL environment variable is correct", 
              "Ensure database credentials are valid",
              "Check network connectivity to database server",
              "Verify firewall settings allow database connections"
            ],
            next_steps: [
              "Review your database configuration in .env file",
              "Test connection manually with psql or database client", 
              "Check database server logs for connection errors",
              "Use connection-status tool with retry: true to attempt reconnection"
            ]
          } : null
        });
        
      } catch (error) {
        debug("Error in connection status tool: %o", error);
        return createMcpErrorResponse("check connection status", error);
      }
    }
  • Zod schema defining the input parameters for the connection-status tool (retry: boolean, optional, defaults to false).
    // Zod schema for input validation
    export const connectionStatusShape: ZodRawShape = {
      retry: z.boolean().optional().default(false),
    };
    
    export const connectionStatusSchema = z.object(connectionStatusShape);
  • index.ts:76-81 (registration)
    Registers the 'connection-status' tool with the MCP server, providing name, description, input schema, and handler function.
    server.tool(
      "connection-status",
      "Check database connection status, view error details, and retry connection. Use retry: true to attempt reconnection when database is unavailable.",
      connectionStatusShape,
      connectionStatus
    );
  • Helper function that returns the current database connection status, any error message, and timestamp of last connection attempt.
    export function getConnectionStatus(): {
      status: ConnectionStatus;
      error: string | null;
      lastAttempt: Date | null;
    } {
      return {
        status: connectionStatus,
        error: connectionError,
        lastAttempt: lastConnectionAttempt,
      };
    }
  • Helper function to attempt database reconnection by executing a test query and updating the global connection status.
    export async function retryConnection(): Promise<boolean> {
      debug("Attempting to retry database connection...");
      lastConnectionAttempt = new Date();
      
      try {
        const result = await executePostgresQuery("SELECT 1 as test");
        const success = result.length === 1 && result[0].test === 1;
        
        if (success) {
          connectionStatus = 'connected';
          connectionError = null;
          debug("Connection retry successful");
          return true;
        } else {
          connectionStatus = 'failed';
          connectionError = "Connection test query returned unexpected result";
          debug("Connection retry failed: unexpected result");
          return false;
        }
      } catch (error) {
        connectionStatus = 'failed';
        connectionError = error instanceof Error ? error.message : String(error);
        debug("Connection retry failed: %o", error);
        return false;
      }
    }
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses that the tool can check status, view error details, and retry connections, which covers basic behavior. However, it doesn't mention important aspects like whether this requires special permissions, what format error details come in, or if there are rate limits on retry attempts.

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 two sentences that each earn their place. The first sentence states the core functionality, and the second provides specific parameter guidance. No wasted words or redundant information.

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 diagnostic tool with no annotations and no output schema, the description provides adequate but minimal information. It covers what the tool does and parameter usage, but doesn't explain what the output looks like (status format, error detail structure) or potential side effects of retrying.

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

Parameters4/5

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

The schema has 0% description coverage for its single parameter. The description compensates by explaining the 'retry' parameter's purpose ('attempt reconnection when database is unavailable') and when to use it ('Use retry: true'). This adds meaningful context beyond the bare schema.

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 specific verbs ('check', 'view', 'retry') and resource ('database connection status'). It distinguishes from siblings like execute-query or get-schema by focusing on connection health rather than data 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 context for when to use the tool ('when database is unavailable') and mentions the retry parameter usage. However, it doesn't explicitly state when NOT to use it or name specific alternatives among the sibling tools.

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