home / mcp / postgresql mcp server

PostgreSQL MCP Server

Provides secure, MCP-enabled access to PostgreSQL data for AI agents to query, discover, and sample data.

Installation
Add the following to your MCP client configuration file.

Configuration

View docs
{
  "mcpServers": {
    "abhinv98-postgre-mcp": {
      "command": "apify",
      "args": [
        "call",
        "your-username/postgresql-mcp-server",
        "--input",
        "@config.json"
      ],
      "env": {
        "YOUR_API_KEY": "YOUR_API_KEY"
      }
    }
  }
}

Connect AI agents to PostgreSQL databases using the MCP server. This setup lets you run SQL queries, inspect schema, sample data, and explore relations directly from AI assistants in a secure, controlled way. The server enforces read-only access by default, keeps detailed logs, and works with any PostgreSQL database accessible to you.

How to use

You connect an MCP-compatible AI agent to the PostgreSQL MCP Server and start issuing natural language requests. The agent translates your questions into MCP tool calls and receives structured results that you can act on or generate insights from. Core capabilities you can leverage include listing available tables, describing table schemas, fetching sample data, and executing read-only SQL queries. Security guards ensure only allowed schemas are accessible and operations stay within defined limits. Start by configuring the server with your database, then connect your AI agent and begin asking questions like: which tables exist in the analytics schema, describe the customers table, show a sample of recent orders, or run a read-only query to retrieve top customers by revenue.

How to install

Prerequisites you need before installation are Node.js (version 20 or newer) and npm. Ensure you have access to the PostgreSQL database you want to connect to. The MCP server is designed to run as an Apify Actor in production, but you can also test it locally.

Install dependencies and build the project locally, then run the server for testing.

npm install
npm run build

# Create a test input file, for example input.json, with your database connection and options
cat > input.json <<'JSON'
{
  "connectionString": "postgresql://localhost:5432/testdb",
  "readOnly": true
}
JSON

# Run locally (dist/main.js should be produced by the build step)
node dist/main.js

# Optional: test with MCP Inspector
npx @modelcontextprotocol/inspector dist/main.js

Additional configuration and usage notes

Configuration focuses on safely exposing your database to AI agents. You can restrict access to specific schemas, set a maximum number of rows returned per query, and enforce timeouts to prevent long-running operations. The provided example shows how to connect via a local command that starts the MCP server and reads a separate input configuration.

{
  "connectionString": "postgresql://user:password@host:5432/database",
  "allowedSchemas": ["public", "analytics"],
  "readOnly": true,
  "maxQueryResults": 1000,
  "timeout": 30
}

Security and best practices

Use read-only mode by default to prevent data modifications. Limit access to only the schemas the AI needs. Set a sensible query timeout and enforce a maximum number of rows returned to protect memory usage. Enable SSL/TLS to secure connections and store credentials securely, preferably using secret inputs or a dedicated credentials store. Regularly review query logs to detect unusual patterns and maintain an audit trail of all AI-driven data access.

Example configuration for the MCP client (stdio)

The MCP client can start the server locally using an Express-like workflow that runs the MCP server process and communicates via standard input/output.

{
  "mcpServers": {
    "postgresql": {
      "type": "stdio",
      "command": "apify",
      "args": ["call", "your-username/postgresql-mcp-server", "--input", "@config.json"]
    }
  }
}

Troubleshooting and tips

If you encounter connection issues, verify the connection string, ensure the database is reachable from your execution environment, and confirm credentials are correct. For SSL-related problems, configure sslMode appropriately and provide valid certificates where necessary. If queries time out, increase the timeout or optimize the SQL with proper indexing. Always use read-only mode unless you have a specific need for data modifications.

Tools supported by the MCP server

The server provides four MCP tools to AI agents for interacting with the database: query, list_tables, describe_table, and get_table_sample. Each tool enforces the configured security settings and returns results in a structured format suitable for AI consumption.

Available tools

query

Execute SQL queries against the connected PostgreSQL database with safeguards such as read-only mode, timeouts, and row limits.

list_tables

List all accessible tables within allowed schemas, returning metadata like schema, table name, row count, and table size.

describe_table

Provide a comprehensive schema description for a specific table, including columns, data types, constraints, indexes, and foreign keys.

get_table_sample

Return a sample of rows from a table to help you preview data and explore structure.