Skip to main content
Glama
MCP PostgreSQL Server

MCP PostgreSQL Server

Servidor PostgreSQL MCP

Un servidor de Protocolo de Contexto de Modelo que proporciona operaciones con bases de datos PostgreSQL. Este servidor permite que los modelos de IA interactúen con bases de datos PostgreSQL mediante una interfaz estandarizada.

Instalación

Instalación manual

npm install mcp-postgres-server

O ejecutar directamente con:

npx mcp-postgres-server

Related MCP server: postgresql-mcp-server

Configuración

El servidor requiere las siguientes variables de entorno:

{
  "mcpServers": {
    "postgres": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "mcp-postgres-server"],
      "env": {
        "PG_HOST": "your_host",
        "PG_PORT": "5432",
        "PG_USER": "your_user",
        "PG_PASSWORD": "your_password",
        "PG_DATABASE": "your_database"
      }
    }
  }
}

Herramientas disponibles

1. connect_db

Establecer conexión a la base de datos PostgreSQL utilizando las credenciales proporcionadas.

use_mcp_tool({
  server_name: "postgres",
  tool_name: "connect_db",
  arguments: {
    host: "localhost",
    port: 5432,
    user: "your_user",
    password: "your_password",
    database: "your_database"
  }
});

2. consulta

Ejecuta consultas SELECT con parámetros opcionales de sentencias preparadas. Admite marcadores de posición de parámetros de estilo PostgreSQL ($1, $2) y MySQL (?).

use_mcp_tool({
  server_name: "postgres",
  tool_name: "query",
  arguments: {
    sql: "SELECT * FROM users WHERE id = $1",
    params: [1]
  }
});

3. ejecutar

Ejecute consultas INSERT, UPDATE o DELETE con parámetros opcionales de sentencias preparadas. Admite marcadores de posición de parámetros de estilo PostgreSQL ($1, $2) y MySQL (?).

use_mcp_tool({
  server_name: "postgres",
  tool_name: "execute",
  arguments: {
    sql: "INSERT INTO users (name, email) VALUES ($1, $2)",
    params: ["John Doe", "john@example.com"]
  }
});

4. esquemas_de_lista

Enumere todos los esquemas en la base de datos conectada.

use_mcp_tool({
  server_name: "postgres",
  tool_name: "list_schemas",
  arguments: {}
});

5. tablas_de_lista

Enumera las tablas de la base de datos conectada. Acepta un parámetro de esquema opcional (el valor predeterminado es "público").

// List tables in the 'public' schema (default)
use_mcp_tool({
  server_name: "postgres",
  tool_name: "list_tables",
  arguments: {}
});

// List tables in a specific schema
use_mcp_tool({
  server_name: "postgres",
  tool_name: "list_tables",
  arguments: {
    schema: "my_schema"
  }
});

6. describe_tabla

Obtiene la estructura de una tabla específica. Acepta un parámetro de esquema opcional (el valor predeterminado es "público").

// Describe a table in the 'public' schema (default)
use_mcp_tool({
  server_name: "postgres",
  tool_name: "describe_table",
  arguments: {
    table: "users"
  }
});

// Describe a table in a specific schema
use_mcp_tool({
  server_name: "postgres",
  tool_name: "describe_table",
  arguments: {
    table: "users",
    schema: "my_schema"
  }
});

Características

  • Manejo seguro de conexiones con limpieza automática

  • Soporte de declaraciones preparadas para parámetros de consulta

  • Compatibilidad con marcadores de posición de parámetros de estilo PostgreSQL ($1, $2) y de estilo MySQL (?)

  • Manejo integral de errores y validación

  • Compatibilidad con TypeScript

  • Gestión automática de conexiones

  • Admite sintaxis y funciones específicas de PostgreSQL

  • Compatibilidad con múltiples esquemas para operaciones de bases de datos

Seguridad

  • Utiliza sentencias preparadas para evitar la inyección de SQL

  • Admite el manejo seguro de contraseñas a través de variables de entorno

  • Valida las consultas antes de su ejecución

  • Cierra automáticamente las conexiones cuando termina

Manejo de errores

El servidor proporciona mensajes de error detallados para problemas comunes:

  • Fallos de conexión

  • Consultas no válidas

  • Parámetros faltantes

  • Errores de base de datos

Licencia

Instituto Tecnológico de Massachusetts (MIT)

Available Tools

5 tools
describe_tableDescribe a tableA
Read-only

Show the structure of one table: column names, data types, nullability, defaults, and primary-key membership. Call this before writing non-trivial queries against a table. Returns {columns: [{column, type, nullable, default, is_primary_key}, ...]}.

Inputs: table (required), schema.

executeRun a write statement (disabled)A
Destructive

Run a data-modifying SQL statement (INSERT/UPDATE/DELETE or DDL). Currently DISABLED: the server is read-only, so this returns an error and changes nothing. To enable writes, the operator must start the server with PG_ALLOW_WRITE=true.

Inputs: sql (required), params.

list_schemasList schemasA
Read-only

List every schema in the connected database. Start here when exploring an unfamiliar database, then call list_tables for the schema you care about. Returns {schemas: [name, ...]}.

Inputs: no named parameters.

list_tablesList tablesA
Read-only

List all tables in a schema (default: 'public'). Use this before querying tables you have not seen yet, then call describe_table for column details. Returns {tables: [name, ...]}.

Inputs: schema.

queryRun read-only SQLA
Read-only

Run one read-only SQL statement against the connected PostgreSQL database and get rows back as JSON. Send exactly one statement per call (SELECT, WITH, EXPLAIN, or SHOW). It runs inside an engine-enforced read-only transaction, so any write is refused by the database. Use this tool for all data reading, aggregation, and query planning. Returns {rows, rowCount, returnedRows, truncated}, plus hint when truncated is true. Prefer $1, $2 placeholders with the params array over interpolating values. Results are capped at ~32768 bytes; truncated:true means rows were dropped - add LIMIT/WHERE or select fewer columns.

Inputs: sql (required), params.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.5/5.0

    Scored across 5 tools

    Disambiguation5/5

    Each tool targets a clearly separate concern: read queries, write execution, schema discovery, table discovery, and column metadata. There is no meaningful overlap, and the descriptions reinforce the boundaries.

    Naming Consistency5/5

    All tool names follow a clean verb_object pattern in snake_case: query, execute, list_schemas, list_tables, describe_table. The naming convention is consistent and predictable.

    Tool Count5/5

    Five tools is well-scoped for a PostgreSQL server: one read path, one write path, and three introspection tools for exploring the database structure. No tool feels redundant or missing.

    Completeness4/5

    The tool surface covers the core database workflow well: discover schemas, inspect tables, describe columns, run read queries, and execute writes. The only caveat is that execute is disabled by default, so write workflows are not available unless the operator explicitly enables them.

    Maintenance

    ActivityStale
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to interact with PostgreSQL databases through the Model Context Protocol, supporting SQL queries, schema management, and data operations.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to safely interact with PostgreSQL databases, perform queries, inspect schemas, and analyze query performance.
      2
      ISC
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to securely query and modify PostgreSQL databases, supporting SQL queries, table management, and schema inspection.
      -