Skip to main content
Glama
melihbirim

PostgreSQL MCP Server

by melihbirim

connect_database

Establish a connection to a PostgreSQL database using specified host, port, database name, username, password, and SSL settings. Facilitates secure database interactions and query execution.

Instructions

Connect to a PostgreSQL database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
hostNoDatabase host (default: localhost)
passwordNoDatabase password
portNoDatabase port (default: 5432)
sslNoUse SSL connection (default: false)
usernameYesDatabase username

Implementation Reference

  • src/index.ts:65-115 (registration)
    Registration of the 'connect_database' tool using server.tool(). Includes tool name, description, input schema defined with Zod, and inline asynchronous handler function.
    server.tool(
      "connect_database",
      "Connect to a PostgreSQL database",
      {
        host: z.string().describe("Database host (default: localhost)").optional(),
        port: z.number().describe("Database port (default: 5432)").optional(),
        database: z.string().describe("Database name"),
        username: z.string().describe("Database username"),
        password: z.string().describe("Database password").optional(),
        ssl: z.boolean().describe("Use SSL connection (default: false)").optional(),
      },
      async ({ host, port, database, username, password, ssl }) => {
        try {
          // Close existing connection if any
          if (dbClient) {
            await dbClient.end();
          }
    
          // Create new connection
          dbClient = new Client({
            host: host || "localhost",
            port: port || 5432,
            database,
            user: username,
            password,
            ssl: ssl || false,
          });
    
          await dbClient.connect();
    
          return {
            content: [
              {
                type: "text",
                text: `Successfully connected to PostgreSQL database '${database}' on ${host || "localhost"}:${port || 5432}`,
              },
            ],
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : "Unknown connection error";
          return {
            content: [
              {
                type: "text",
                text: `Failed to connect to database: ${errorMessage}`,
              },
            ],
          };
        }
      }
    );
  • The handler function for the connect_database tool. It closes any existing database connection, creates a new PostgreSQL Client with the provided configuration (using defaults where applicable), connects to the database, and returns a success message or error details.
    async ({ host, port, database, username, password, ssl }) => {
      try {
        // Close existing connection if any
        if (dbClient) {
          await dbClient.end();
        }
    
        // Create new connection
        dbClient = new Client({
          host: host || "localhost",
          port: port || 5432,
          database,
          user: username,
          password,
          ssl: ssl || false,
        });
    
        await dbClient.connect();
    
        return {
          content: [
            {
              type: "text",
              text: `Successfully connected to PostgreSQL database '${database}' on ${host || "localhost"}:${port || 5432}`,
            },
          ],
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown connection error";
        return {
          content: [
            {
              type: "text",
              text: `Failed to connect to database: ${errorMessage}`,
            },
          ],
        };
      }
    }
  • Input schema for the connect_database tool, defined using Zod object with parameters for PostgreSQL connection: host, port, database, username, password, ssl, including descriptions and optionals.
      host: z.string().describe("Database host (default: localhost)").optional(),
      port: z.number().describe("Database port (default: 5432)").optional(),
      database: z.string().describe("Database name"),
      username: z.string().describe("Database username"),
      password: z.string().describe("Database password").optional(),
      ssl: z.boolean().describe("Use SSL connection (default: false)").optional(),
    },
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 states the basic action. It lacks critical behavioral details: whether this establishes a persistent connection, requires authentication, has side effects (e.g., opening network ports), error handling, or what 'connect' means in context (e.g., returns a connection object).

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 with zero wasted words. It's appropriately sized for a tool with a straightforward purpose and well-documented schema, making it easy to parse.

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 connection tool with no annotations and no output schema, the description is inadequate. It doesn't explain what happens after connecting (e.g., state changes, returned handles), error conditions, or dependencies on other tools. Given the complexity of database connections, more context is needed.

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?

Schema description coverage is 100%, so parameters are fully documented in the schema. The description adds no parameter-specific information beyond implying PostgreSQL context, which doesn't enhance understanding of individual parameters. Baseline 3 is appropriate as the schema does the heavy lifting.

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 action ('Connect to') and resource ('a PostgreSQL database'), making the purpose unambiguous. However, it doesn't differentiate from sibling tools like 'disconnect_database' or explain what 'connect' entails operationally, preventing 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?

No guidance is provided on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing a database instance), when to reconnect, or how it relates to siblings like 'execute_query' or 'disconnect_database'.

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

Related 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/melihbirim/pg-mcp'

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