Skip to main content
Glama
martymarkenson

PostgreSQL MCP Server

Test Postgres Connection

test-postgres-connection

Verify PostgreSQL database connectivity and check connection status to ensure the database is accessible for queries.

Instructions

Test the Postgres connection and return connection status

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Inline async handler function that initializes the DB connection, tests it using testDB helper, and returns formatted success or error response.
    async () => {
      try {
        // Show current configuration (without password)
        const config = {
          host: process.env.DB_HOST,
          port: process.env.DB_PORT || '5432',
          database: process.env.DB_NAME,
          username: process.env.DB_USERNAME,
          password: '***hidden***'
        };
    
        // Attempt to connect and test
        const db = initDb();
        const testResult = await testDB(db);
        
        if (testResult.success) {
          return {
            content: [{
              type: "text",
              text: `✅ Database connection successful!\n\nConfiguration:\n${JSON.stringify(config, null, 2)}\n\nConnection test result: ${JSON.stringify(testResult.result, null, 2)}`
            }]
          };
        } else {
          return {
            content: [{
              type: "text",
              text: `❌ Database connection failed!\n\nConfiguration:\n${JSON.stringify(config, null, 2)}\n\nError: ${testResult.error}`
            }],
            isError: true
          };
        }
      } catch (error) {
        return {
          content: [{
            type: "text",
            text: `❌ Unexpected error during connection test: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    }
  • src/server.ts:85-132 (registration)
    Registration of the 'test-postgres-connection' tool with server.registerTool, including name, metadata (title, description), and the handler function.
    server.registerTool(
      "test-postgres-connection",
      {
        title: "Test Postgres Connection",
        description: "Test the Postgres connection and return connection status",
      },
      async () => {
        try {
          // Show current configuration (without password)
          const config = {
            host: process.env.DB_HOST,
            port: process.env.DB_PORT || '5432',
            database: process.env.DB_NAME,
            username: process.env.DB_USERNAME,
            password: '***hidden***'
          };
    
          // Attempt to connect and test
          const db = initDb();
          const testResult = await testDB(db);
          
          if (testResult.success) {
            return {
              content: [{
                type: "text",
                text: `✅ Database connection successful!\n\nConfiguration:\n${JSON.stringify(config, null, 2)}\n\nConnection test result: ${JSON.stringify(testResult.result, null, 2)}`
              }]
            };
          } else {
            return {
              content: [{
                type: "text",
                text: `❌ Database connection failed!\n\nConfiguration:\n${JSON.stringify(config, null, 2)}\n\nError: ${testResult.error}`
              }],
              isError: true
            };
          }
        } catch (error) {
          return {
            content: [{
              type: "text",
              text: `❌ Unexpected error during connection test: ${error instanceof Error ? error.message : String(error)}`
            }],
            isError: true
          };
        }
      }
    );
  • testDB helper function that performs a simple SELECT query to verify the database connection and returns success/error status.
    const testDB = async (db: postgres.Sql) => {
      try {
        // Simple query to test connection
        const result = await db`SELECT 1 as test`;
        return { success: true, message: "Connection successful", result };
      } catch (error) {
        return { 
          success: false, 
          message: "Connection failed", 
          error: error instanceof Error ? error.message : String(error)
        };
      }
    };
  • initDb helper that lazily initializes the global dbConnection using getDb.
    const initDb = () => {
      if(!dbConnection) {
        dbConnection = getDb();
      }
      return dbConnection;
    };
  • getDb helper that creates a new postgres connection using environment variables.
    const getDb = () => {
      const db = postgres({
            host: process.env.DB_HOST,
            port: parseInt(process.env.DB_PORT || '5432'),
            database: process.env.DB_NAME,
            username: process.env.DB_USERNAME,
            password: process.env.DB_PASSWORD,
            ssl: 'prefer'
    
          });
      return db;
    };
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It states the tool tests a connection and returns status, but lacks details on behavioral traits such as what 'connection' refers to (e.g., default, specified), whether it's read-only or has side effects, error handling, or performance implications. This is inadequate for a tool with zero annotation coverage.

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 a single, efficient sentence: 'Test the Postgres connection and return connection status.' It's front-loaded with the core action and outcome, with zero wasted words, making it highly concise and well-structured.

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?

Given the tool's purpose (testing a database connection) with no annotations and no output schema, the description is incomplete. It doesn't explain what 'connection status' entails (e.g., success/failure, latency, error details), how the connection is determined, or potential side effects. This leaves gaps for an agent to use it effectively.

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 input schema has 0 parameters with 100% coverage, so no parameter documentation is needed. The description doesn't add param info, which is fine here. A baseline of 4 is appropriate since the schema fully handles parameters, and the description doesn't need to compensate.

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

Purpose4/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: 'Test the Postgres connection and return connection status.' It specifies the verb ('Test'), resource ('Postgres connection'), and outcome ('return connection status'). However, it doesn't explicitly differentiate from sibling tools like 'execute-sql-query' or 'get-all-tables,' which prevents a perfect score.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools, prerequisites, or specific contexts where connection testing is appropriate versus executing queries or fetching tables. This leaves the agent without usage direction.

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/martymarkenson/Postgres-Connector-MCP'

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