How to Intermediate · 3 min read

How to use PostgreSQL MCP server

Quick answer
The PostgreSQL MCP server acts as a bridge between AI agents and PostgreSQL databases using the Model Context Protocol (MCP). You run the MCP server to expose PostgreSQL as a tool, then connect your AI agent to it via the MCP client for querying and managing data programmatically.

PREREQUISITES

  • Python 3.8+
  • PostgreSQL installed and running
  • pip install mcp psycopg[binary]
  • PostgreSQL connection credentials

Setup PostgreSQL MCP server

Install the mcp Python package and the PostgreSQL driver psycopg[binary]. Ensure your PostgreSQL server is running and accessible with valid credentials. The MCP server will expose PostgreSQL as a tool for AI agents.

bash
pip install mcp psycopg[binary]

Step by step usage

Run a Python script to start the PostgreSQL MCP server. This server listens for MCP client requests and executes SQL queries on your PostgreSQL database. Below is a complete example that starts the MCP server using stdio transport.

python
import os
from mcp.server import Server
from mcp.server.stdio import stdio_server
import psycopg

# PostgreSQL connection parameters
PG_CONN_INFO = {
    "host": os.environ.get("PG_HOST", "localhost"),
    "port": int(os.environ.get("PG_PORT", 5432)),
    "user": os.environ.get("PG_USER", "postgres"),
    "password": os.environ.get("PG_PASSWORD", ""),
    "dbname": os.environ.get("PG_DBNAME", "postgres")
}

class PostgresMCPServer(Server):
    def __init__(self):
        super().__init__()
        self.conn = psycopg.connect(**PG_CONN_INFO)

    async def handle_tool_call(self, tool_name, input_text):
        # Only support 'query' tool for SQL execution
        if tool_name != "query":
            return f"Error: Unsupported tool {tool_name}"
        try:
            with self.conn.cursor() as cur:
                cur.execute(input_text)
                if cur.description:  # SELECT query
                    rows = cur.fetchall()
                    columns = [desc.name for desc in cur.description]
                    # Format output as CSV-like string
                    header = ", ".join(columns)
                    data = "\n".join(", ".join(str(cell) for cell in row) for row in rows)
                    return f"{header}\n{data}"
                else:
                    self.conn.commit()
                    return "Query executed successfully."
        except Exception as e:
            return f"Error executing query: {e}"

if __name__ == "__main__":
    server = PostgresMCPServer()
    stdio_server(server)

Common variations

  • You can modify the handle_tool_call method to support multiple tools or more complex SQL operations.
  • Use different MCP transports like SSE or TCP instead of stdio if needed.
  • Run the MCP server asynchronously with an async PostgreSQL driver like asyncpg for higher throughput.
  • Connect AI agents using the official mcp Python client to send SQL queries and receive results.

Troubleshooting

  • If you see connection errors, verify your PostgreSQL credentials and network access.
  • Ensure the MCP server script has access to environment variables for DB connection.
  • For SQL syntax errors, test queries directly in psql or a DB client first.
  • If the MCP client cannot connect, confirm the transport method matches (stdio, SSE, TCP).

Key Takeaways

  • Use the mcp Python package to run a PostgreSQL MCP server exposing SQL query capabilities.
  • Implement handle_tool_call to execute SQL queries and return results to AI agents.
  • Configure PostgreSQL connection securely via environment variables for production use.
Verified 2026-04
Verify ↗