Skip to main content
Glama
antonorlov

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}, ...]}.

ParametersJSON Schema
NameRequiredDescriptionDefault
tableYesTable name
schemaNoSchema name (default: 'public')

TDQS

A4.3/5.0
Behavior4/5

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

The readOnlyHint annotation already covers non-mutation, and the description adds concrete behavioral detail beyond it by specifying the exact result shape and fields. It does not go into error behavior or edge cases, but given the annotation coverage, the added precision about return contents earns a solid score.

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 two sentences plus a compact inline return-shape definition. It front-loads the core purpose, adds a usage cue, and then gives the exact response structure without any filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple 2-parameter read-only introspection tool, the description is complete: it states what the tool does, when to use it, what it returns, and the annotations cover safety. No output schema exists, but the inline return format compensates for that.

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%: both 'table' and 'schema' are documented in the schema. The description adds no parameter-specific meaning beyond what the schema already provides, so the baseline of 3 is appropriate.

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

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb and resource: 'Show the structure of one table', and enumerates exactly what is returned (column names, data types, nullability, defaults, primary-key membership). This clearly distinguishes it from siblings like query/execute (run statements) and list_tables/list_schemas (enumerate catalog objects).

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

Usage Guidelines4/5

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

It gives explicit guidance: 'Call this before writing non-trivial queries against a table.' This is clear contextual advice, though it does not name alternatives or state when not to use the tool. It stops short of the explicit when/when-not/alternatives structure that would earn a 5.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYesOne INSERT / UPDATE / DELETE / DDL statement. Use $1, $2, ... for parameters.
paramsNoPositional parameter values bound to $1, $2, ... placeholders.

TDQS

A4.2/5.0
Behavior4/5

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

Adds critical context beyond annotations: it returns an error and changes nothing due to the server being read-only, and explains how to enable writes. This is transparent and consistent with destructiveHint=true and readOnlyHint=false—no contradiction.

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?

Two concise sentences that front-load the purpose, then immediately disclose the disabled state and the fix. No wasted words, and the structure is logical.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a disabled write tool with no output schema, the description fully explains current behavior and the enabling condition. It doesn't describe success response when enabled, but that's irrelevant given the disabled state; the agent knows calling it will fail now.

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 covers both parameters fully (sql statement and positional params), including the placeholder syntax. The description restates the statement type but adds no new parameter semantics beyond what the schema already provides, so baseline 3 is appropriate.

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

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description explicitly states it runs data-modifying SQL (INSERT/UPDATE/DELETE/DDL), which distinguishes it from sibling tools like query and describe_table. It also indicates the tool is currently disabled, adding precise scope.

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

Usage Guidelines4/5

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

It clearly says the tool is disabled, explains the server read-only condition, and gives the exact flag needed to enable it (PG_ALLOW_WRITE=true). This provides strong when-not-to-use guidance, though it doesn't explicitly name alternatives like query for read operations.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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, ...]}.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.7/5.0
Behavior4/5

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

Annotations already declare readOnlyHint=true, so the safe-read nature is covered. The description adds useful behavioral context by specifying 'every schema in the connected database' and providing the return shape, which is valuable since there is no output schema.

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?

Two concise sentences with no filler. The core action is front-loaded, followed by usage guidance and a compact return-format note.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a zero-parameter, read-only discoverability tool, the description is complete: it states the operation, the scope, the recommended next step, and the return shape. Nothing an agent needs to call it successfully is missing.

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 tool has zero parameters and an empty input schema, so there is nothing to explain. Baseline for a zero-parameter tool is 4; the description correctly omits irrelevant parameter details.

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

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb and resource: 'List every schema in the connected database.' The scope is clear and it differentiates itself from sibling tools by framing itself as the entry point before list_tables.

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

Usage Guidelines5/5

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

Explicitly directs the agent when to use the tool: 'Start here when exploring an unfamiliar database.' It also names the next step, list_tables, giving clear usage sequencing among siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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, ...]}.

ParametersJSON Schema
NameRequiredDescriptionDefault
schemaNoSchema name (default: 'public')

TDQS

A4.5/5.0
Behavior4/5

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

The annotations already declare readOnlyHint=true, so the read-only nature is established. The description adds useful behavioral context beyond that: the default schema behavior and the exact return shape {tables: [name, ...]}, which is valuable because there is no output schema.

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?

Three sentences with no wasted words: the first states purpose and default, the second gives usage guidance, and the third documents the return format. It is front-loaded and every sentence earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple list tool with one optional parameter and annotations covering safety, the description is complete. It tells the agent what the tool does, when to use it, what the default is, and what the response looks like, so nothing essential is missing.

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 coverage is 100%, and the schema already documents the single optional schema parameter with its default value. The description repeats the default-public behavior, so it adds no meaning beyond what the input schema provides.

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

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb and resource: 'List all tables in a schema (default: 'public')'. It also distinguishes itself from the sibling describe_table by noting that describe_table should be used afterward for column details, making the tool's role clear.

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

Usage Guidelines5/5

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

It explicitly says to use the tool before querying tables not yet seen, and directs the agent to call describe_table next for column details. This provides clear when-to-use guidance and names the relevant alternative.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYesOne SQL statement. Use $1, $2, ... for parameters.
paramsNoPositional parameter values bound to $1, $2, ... placeholders.

TDQS

A4.7/5.0
Behavior5/5

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

Beyond the readOnlyHint annotation, the description adds meaningful behavioral detail: the engine-enforced read-only transaction, the exact return shape {rows, rowCount, returnedRows, truncated}, the ~32768 byte cap with truncated:true behavior, and concrete remediation advice (add LIMIT/WHERE or fewer columns). This goes far beyond what annotations alone provide.

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 compact and every sentence earns its place: purpose, statement constraint, enforcement, usage scope, return shape, binding guidance, and truncation handling. The most important information is front-loaded in the first sentence, and there is no filler or repetition of schema content.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given there is no output schema, the description fully compensates by detailing the return fields and truncation behavior. It also covers statement type restrictions, read-only enforcement, result size cap, and safe parameter binding. An agent has everything needed to invoke this tool correctly without additional inference.

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?

With 100% schema description coverage, the schema already documents both parameters. The description adds value above the baseline by instructing agents to 'prefer $1, $2 placeholders with the params array over interpolating values,' a safety/security nuance not present in the schema, and by enforcing 'exactly one statement per call.'

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

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a precise verb+resource: 'Run one read-only SQL statement against the connected PostgreSQL database and get rows back as JSON.' It further specifies allowed statement types (SELECT, WITH, EXPLAIN, SHOW), which clearly separates it from siblings like list_tables or execute.

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

Usage Guidelines4/5

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

The description explicitly states when to use the tool: 'Use this tool for all data reading, aggregation, and query planning.' The 'read-only' framing and 'any write is refused' communicate the boundary against writes, though it doesn't explicitly name the write sibling (execute) as the alternative, so it falls just short of full 5.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

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

  1. 6 tool updatesv0.3.0
    • Removedconnect_db
    • Changeddescribe_table3 fields changed
      • addedInput schema / $schema
        Added value: +"http://json-schema.org/draft-07/schema#"
      • addedInput schema / additionalProperties
        Added value: +false
      • changedInput schema / properties / schema / description
        Previous value: -"Schema name (default: public)"New value: +"Schema name (default: 'public')"
    • Changedexecute4 fields changed
      • addedInput schema / $schema
        Added value: +"http://json-schema.org/draft-07/schema#"
      • addedInput schema / additionalProperties
        Added value: +false
      • changedInput schema / properties / params / description
        Previous value: -"Query parameters (optional)"New value: +"Positional parameter values bound to $1, $2, ... placeholders."
      • changedInput schema / properties / sql / description
        Previous value: -"SQL query (INSERT, UPDATE, DELETE) (use $1, $2, etc. for parameters)"New value: +"One INSERT / UPDATE / DELETE / DDL statement. Use $1, $2, ... for parameters."
    • Changedlist_schemas2 fields changed
      • addedInput schema / $schema
        Added value: +"http://json-schema.org/draft-07/schema#"
      • removedInput schema / required
        Removed value: -[]
    • Changedlist_tables4 fields changed
      • addedInput schema / $schema
        Added value: +"http://json-schema.org/draft-07/schema#"
      • addedInput schema / additionalProperties
        Added value: +false
      • changedInput schema / properties / schema / description
        Previous value: -"Schema name (default: public)"New value: +"Schema name (default: 'public')"
      • removedInput schema / required
        Removed value: -[]
    • Changedquery4 fields changed
      • addedInput schema / $schema
        Added value: +"http://json-schema.org/draft-07/schema#"
      • addedInput schema / additionalProperties
        Added value: +false
      • changedInput schema / properties / params / description
        Previous value: -"Query parameters (optional)"New value: +"Positional parameter values bound to $1, $2, ... placeholders."
      • changedInput schema / properties / sql / description
        Previous value: -"SQL SELECT query (use $1, $2, etc. for parameters)"New value: +"One SQL statement. Use $1, $2, ... for parameters."
  2. 6 tool updates
    • First observedconnect_db
    • First observeddescribe_table
    • First observedexecute
    • First observedlist_schemas
    • First observedlist_tables
    • First observedquery

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

ActivityMaintained
ResponsivenessUnresponsive

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.
    7 npm
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to safely interact with PostgreSQL databases, perform queries, inspect schemas, and analyze query performance.
    2
    -