Logotipo de Postgres MCP Server

Postgres MCP Server

Organización
microsoft

Connect your coding agent to PostgreSQL. postgres-mcp lets you generate

Editormicrosoft
Repositoriopostgres-mcp
Forks
1
Estrellas
26
Herramientas disponibles
13
Tipo de transportestdio
Categorías
LicenciaMIT
Enlaces
  • Conecta herramientas a flujos de trabajo con IA

    Postgres MCP Server ofrece funciones MCP que pueden usar los clientes y agentes de IA compatibles.

  • 13 herramientas disponibles

    Explora a continuación las acciones que se pueden invocar, con sus nombres y descripciones cuando el servidor los proporcione.

  • Configuración lista para copiar

    Usa los ejemplos de instalación para configurar este servidor en tu cliente MCP preferido.

  • Indicadores de interés en el código abierto

    26 estrellas y 1 forks en el repositorio enlazado.

Postgres MCP Server

Platforms: Claude | Copilot | Codex | Open Code Postgres: local | on-prem | azure | aws | gcp Release status: Preview

Connect your coding agent to PostgreSQL. postgres-mcp lets you generate queries and run analytics, design database schemas, diagnose performance of the server and queries, securely manage connections, and import data. It is compatible with any MCP client — GitHub Copilot, Claude Code, Codex, Open Code, Cursor, VS Code, and more.

Quick start

1. Save a connection profile

Create a named profile once — the password is stored in your OS keyring, never in a config file:

sh
# add a profile from a libpq URI or key=value string
npx -y @microsoft/postgres-mcp connection add local \
  "postgresql://postgres@localhost:5432/postgres"

# store its password securely (hidden prompt)
npx -y @microsoft/postgres-mcp connection set-password local

# check it
npx -y @microsoft/postgres-mcp connection list

Profiles created by connection add permit write tools unless access_mode: ro is set. For autonomous agents that should not write, use an explicit read-only profile and a read-only database role — see Read-only profiles.

2. Add postgres-mcp to your coding agent

The server speaks MCP over stdio. Point your client at npx @microsoft/postgres-mcp run — no credentials go in the client config; the coding agent discovers and connects to your saved profile at runtime.

GitHub Copilot CLI, Claude Code, Cursor & Claude Desktop — clients that use the mcpServers format (~/.copilot/mcp-config.json, mcp.json, .cursor/mcp.json, claude_desktop_config.json, …):

jsonc
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@microsoft/postgres-mcp", "run"]
    }
  }
}

Running headless or in CI, without a keyring? The server can also take a database connection string from the environment — see Connecting without a profile in the guide.

3. Ask your coding agent

"List the tables in my PostgreSQL database." "Show me the 10 most recent orders from my PostgreSQL database." "What's slowing down my PostgreSQL server right now?"

The agent calls the server's tools (postgres_mcp_connect, postgres_mcp_query, postgres_mcp_db_context, …) for you.


What it can do

AreaTools
Connectionslist / add / remove profiles, connect, disconnect, list databases
Queryread‑only SQL (postgres_mcp_query), DDL/DML (postgres_mcp_modify)
Schemafetch CREATE scripts for tables, indexes, functions, sequences…
Datadescribe a CSV, bulk‑load a CSV via COPY
Diagnosticsprobe server capabilities, collect performance metric groups

See the usage guide for tools, configuration, authentication (including Microsoft Entra ID), TLS, and the security model.


Security in one minute

  • The server doesn't decide what's allowed — your database does. It just passes requests along to PostgreSQL and runs them as the database user in your connection profile. It can't tell the difference between a request you meant to make and one the AI invented or was tricked into making, so anything that database user can do, the AI can do. What actually protects you is the permissions you give that user, the approval prompts in your MCP client, and the model you choose to run. See Security model for who's responsible for what, plus a checklist for locking things down.
  • postgres_mcp_query is read‑only. Omitted profile access_mode permits write tools; set access_mode: ro and use a read-only database role unless writes are intentionally delegated.
  • Microsoft Entra ID (AAD) is selected automatically for Azure profiles without a stored keyring password. Store a profile password to use password authentication instead.
  • Local file reads (postgres_mcp_bulk_load_csv, postgres_mcp_describe_csv) are limited to the MCP server's startup working directory by default and paths allowed with allow-access-to-path <path>. A file allows only itself; a directory allows recursive access.
  • Secrets are scrubbed from error messages before they leave the process.

See more info about security model in the usage guide.


Requirements

  • Node.js 22+ (to run via npx).
  • Linux x64/arm64, macOS x64/arm64, or Windows x64. Windows ARM uses x64 emulation.
  • A reachable PostgreSQL database — local, Docker, on‑premises, Azure Database for PostgreSQL, Amazon RDS/Aurora, Google Cloud SQL/AlloyDB, or any wire‑compatible server.

Changelog

See CHANGELOG.md for release notes.

License

Licensed under the MIT License © Microsoft.

Instalación

TypingMind
{
  "mcpServers": {
    "postgres-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@microsoft/postgres-mcp",
        "run"
      ]
    }
  }
}

Herramientas disponibles

  • pgsql_list_connection_profiles

    List all available PostgreSQL connection profiles. Returns a list of profiles with ID, name, host, port, and default database. Use the profile ID with pgsql_connect to establish a connection.

  • pgsql_connect

    Connect to a PostgreSQL database server using a profile ID and optional database name. The profile ID is retrieved from pgsql_list_connection_profiles. Returns a connection ID that is used to interact with the database with other pgsql tools. If a specific database is given and the connection fails, use $pgsql_list_databases against a connection to the default database to find the correct database name. The connection ID is a string formatted as 'pgsql/{profile_id}[/{database name}]', where if no database name is present it's the default database for the profile.

  • pgsql_disconnect

    Disconnect from a PostgreSQL database server using a connection ID.

  • pgsql_list_databases

    List all databases on the connected PostgreSQL server. Requires a connectionId from pgsql_connect. Returns a list of database names available on the server.

  • pgsql_db_context

    Get context about this database by fetching the CREATE scripts for a specific type of database object or all types. Use this tool to retrieve detailed context about the database objects (e.g. tables, indexes, functions, sequences, comments, ownership, default_privileges, fdw, or all) within a given schema or across all schemas. Note: Always call this tool first to fetch the most up-to-date database schema context before executing any queries or modifications. This tool is strictly read-only and prevents duplicate or conflicting operations by ensuring you know the current state.

  • pgsql_bulk_load_csv

    Bulk‐load CSV file via COPY into a PostgreSQL table. Supports column mapping, optional SQL transforms, truncate-before-insert, and PK-based upsert. Use this to bulk-load CSV data into an existing table. The path must live under an approved bulk-load path (the current working directory by default, or one approved via postgres-mcp allow-access-to-path <path> / PGSQL_MCP_ALLOWED_PATHS). A directory grants recursive access to descendants; a file grants access only to that exact canonical file. Example: pgsql_bulk_load_csv( connectionId='tools://server/mydb', path='/path/to/file.csv', table='mytable', mapping={'col1': 'col1', 'col2': 'col2'}, transforms={'col2': 'src.col2::int'}, mode='upsert' )

  • pgsql_describe_csv

    Describe the structure and contents of a CSV file. Returns a YAML description of the CSV file, including fields, types, and metadata. Useful for preparing to import CSV data into a database. The selected file path must be approved for CSV access (via postgres-mcp allow-access-to-path <path> or PGSQL_MCP_ALLOWED_PATHS). A directory grants recursive access to descendants; a file grants access only to that exact canonical file.

  • pgsql_get_server_capabilities

    CALL THIS FIRST before diagnosing performance issues. Discovers what diagnostic tools are available for the connected server. Returns PostgreSQL version, Azure detection status, and available diagnostic groups for pgsql_get_metrics_group. Each group includes its ID, description, and metric count. Shows why certain groups may be unavailable (missing extensions, version requirements, Azure-only features). Required step before using pgsql_get_metrics_group for troubleshooting.

  • pgsql_get_metrics_group

    Diagnose slow database and performance issues. USE THIS FIRST when users report slow queries, high CPU, or performance problems. Collects pre-correlated metrics by diagnostic group: core_health (CPU, memory, connections, storage), saturation (I/O pressure, disk, cache performance), throughput (transactions, tuples, workload volume), lock_contention (blocking sessions, deadlocks, lock waits). For Azure servers, includes Azure Monitor metrics automatically. Call pgsql_get_server_capabilities first to see available groups. Max 5 groups per request, max 7 days for historical data.

  • pgsql_query

    Run a formatted SQL query against a database. For performance diagnostics, prefer pgsql_get_metrics_group instead. Requires a connection_id from the return value of pgsql_connect. This query must not modify the database at all. Can include SELECT, SHOW, EXPLAIN etc. Do not include additional statements, e.g. SET search_path, in this query. It must only be a single, spacious, well formatted query with line breaks and tabs. The statement will be presented to the user, so focus on readability. Returns the results of the query. You MUST include a validation query to check the validity of EVERY literal value used in the SQL query. Do NOT skip this step. This tool is strictly read-only and executes a single statement only. Use EXPLAIN for performance or optimization analysis and include execution plan details. On error, return clear error messages to the user.

  • pgsql_modify

    Modify the database and/or schema by executing SQL statements including DDL (CREATE, ALTER, DROP) and DML (INSERT, UPDATE, DELETE). Useful when designing schemas or inserting data. It must only be a single, spacious, well formatted query with line breaks and tabs. The statement will be presented to the user, so focus on readability. Returns the results of the statement execution, if any. Note: Always fetch up-to-date database schema context using the pgsql_db_context tool before proposing or executing modifications to avoid duplicates or conflicts. Ensure explicit user confirmation. On error, return clear and descriptive error messages to the user. NOTE: Use this tool when working with PostgreSQL databases INSTEAD of asking the user to run the psql CLI tool, unless otherwise explicitly asked to.

  • pgsql_add_connection

    Add a new PostgreSQL connection profile. The profile will be stored in ~/.postgres-mcp/connections.yaml. IMPORTANT: This tool does NOT accept passwords for security reasons. After adding the connection, the user must run: postgres-mcp connection set-password <profile_name> to securely set the password via the OS keyring. For Docker/CI environments, use the PGSQL_MCP_CONNECTION_STRING environment variable instead. Optionally set 'access_mode' to 'ro' (read-only) to block write tools (pgsql_modify, pgsql_bulk_load_csv) against this profile. Defaults to 'rw' (read-write) when omitted.

  • pgsql_remove_connection

    Remove a PostgreSQL connection profile. This removes the profile from ~/.postgres-mcp/connections.yaml and deletes its password from the OS keyring. Use pgsql_list_connection_profiles to see available profiles.

Usa el MCP de Postgres MCP Server con varios modelos de IA

TypingMind conecta las herramientas MCP a nivel del espacio de trabajo, por lo que, una vez conectado Postgres MCP Server, puedes usarlo con distintos modelos de IA en TypingMind sin tener que configurarlo por separado para cada modelo. Esta integración MCP se ejecuta localmente en tu dispositivo a través del conector MCP de TypingMind.

Guía de configuración para usar el conector local

Usa esta opción si el servidor MCP necesita acceder a archivos locales, aplicaciones o recursos privados de tu ordenador.

1

Abre los ajustes de MCP

En TypingMind, ve a Ajustes, luego a Ajustes avanzados y a Model Context Protocol, y elige Configurar conector.

  1. Abre TypingMind en tu navegador.
  2. Haz clic en el icono de Ajustes.
  3. Ve a Ajustes avanzados.
  4. Abre la sección Model Context Protocol.
  5. Haz clic en Configurar conector y elige Este dispositivo.
Pantalla de configuración del conector MCP de TypingMind con «Este dispositivo» seleccionado
2

Ejecuta el comando del conector

Elige Este dispositivo, copia el comando de TypingMind y ejecútalo en Terminal. Mantén el proceso en ejecución mientras uses MCP.

  1. Copia el comando de configuración que muestra TypingMind.
  2. Abre Terminal en macOS o Windows Terminal en Windows.
  3. Pega y ejecuta el comando.
  4. Acepta la instalación del paquete si Terminal te pide confirmación para continuar.
  5. Mantén el proceso en ejecución en la ventana de Terminal mientras uses las herramientas MCP.
3

Añade Postgres MCP Server como servidor

Cuando el estado del conector sea «Listo», haz clic en «Edita servidores» y pega la configuración del servidor MCP.

  1. Espera hasta que el estado del conector indique «Listo».
  2. Haz clic en Edita servidores.
  3. Pega la configuración del servidor MCP de Postgres MCP Server.
  4. Guarda la lista de servidores.
  5. Actualiza para comprobar que el conector sigue listo.
Ajustes de MCP de TypingMind con un servidor activo y el botón «Edita servidores»
{
  "mcpServers": {
    "postgres-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@microsoft/postgres-mcp"
      ]
    }
  }
}
4

Úsala con distintos modelos

Guarda la lista de servidores, abre Plugins, activa las herramientas MCP de Postgres MCP Server y selecciona cualquier modelo de IA compatible en TypingMind para usar las herramientas en el chat o asignárselas a un agente de IA.

  1. Abre la página Plugins en TypingMind.
  2. Activa las herramientas MCP de Postgres MCP Server.
  3. Inicia un chat y elige el modelo de IA que quieras usar.
  4. Usa las herramientas MCP en el chat o asígnalas a un agente de IA.
  5. Cambia a otro modelo de IA cuando lo necesites sin volver a conectar MCP.
Chat de TypingMind que usa herramientas MCP activadas con un modelo de IA seleccionado
¿Puedes usar Postgres MCP Server para ayudarme con esta tarea?
Postgres MCP Server
Claro. Lo he leído.
Esto he encontrado usando Postgres MCP Server.

Preguntas frecuentes

¿Para qué sirve el servidor MCP Postgres MCP Server?

Postgres MCP Server es un servidor MCP que permite a los clientes de IA compatibles conectarse a herramientas y contexto externos. En TypingMind, basta con añadir este servidor MCP una vez para que sus herramientas estén disponibles en tu espacio de trabajo de IA.

¿Puedo usar el servidor MCP Postgres MCP Server con varios modelos de IA en TypingMind?

Sí. TypingMind conecta las herramientas MCP a nivel del espacio de trabajo, por lo que puedes usar Postgres MCP Server con distintos modelos de IA, como Claude, ChatGPT, Gemini u otros que hayas configurado en TypingMind, sin configurar el servidor MCP por separado para cada modelo.

¿Por qué usar el conector MCP de Postgres MCP Server con TypingMind?

TypingMind es una de las mejores interfaces de chat con LLM porque reúne varios modelos de IA, prompts, plugins, agentes de IA, claves de API y herramientas MCP en un solo espacio de trabajo. Con Postgres MCP Server conectado, puedes usar sus herramientas MCP con tus modelos preferidos y mantener organizado tu flujo de trabajo de chat en TypingMind.

¿Cómo conecto el servidor MCP Postgres MCP Server a TypingMind?

Postgres MCP Server funciona a través del conector MCP local de TypingMind. Es la mejor opción cuando el servidor MCP necesita acceder a archivos locales, aplicaciones de escritorio, herramientas de línea de comandos o recursos privados de tu ordenador.

¿Qué herramientas ofrece el servidor MCP Postgres MCP Server en TypingMind?

Postgres MCP Server ofrece 13 herramientas MCP que puedes activar desde la página Plugins de TypingMind y usar en el chat o asignar a agentes de IA.

¿Tengo que compartir mis claves de API con TypingMind para usar el servidor MCP Postgres MCP Server?

No. TypingMind prioriza el funcionamiento local y te permite mantener el control de tus proveedores de modelos, claves de API, prompts y configuración MCP. Si Postgres MCP Server requiere autenticación, añade las cabeceras, los ajustes de OAuth o la configuración local necesarios para ese servidor MCP al crear la conexión.

Servidores MCP relacionados

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇