Logo de Postgres MCP Server

Postgres MCP Server

Organização
microsoft

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

Publicado pormicrosoft
Repositóriopostgres-mcp
Forks
1
Estrelas
26
Ferramentas disponíveis
13
Tipo de transportestdio
Categorias
LicençaMIT
Links
  • Conecte ferramentas a fluxos de trabalho de IA

    Postgres MCP Server disponibiliza recursos MCP que podem ser usados por clientes e agentes de IA compatíveis.

  • 13 ferramentas disponíveis

    Confira abaixo as ações que podem ser chamadas, incluindo nomes e descrições quando fornecidos pelo servidor.

  • Configuração pronta para copiar

    Use os exemplos de instalação para configurar este servidor no seu cliente MCP preferido.

  • Indicadores da comunidade de código aberto

    26 estrelas e 1 forks no repositório vinculado.

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.

Instalação

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

Ferramentas disponíveis

  • 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.

Use o MCP de Postgres MCP Server com vários modelos de IA

O TypingMind conecta as ferramentas MCP no nível do espaço de trabalho. Assim, após conectar Postgres MCP Server, é possível usá-lo com diferentes modelos de IA no TypingMind, em vez de configurá-lo separadamente para cada modelo. Este MCP é executado localmente no seu dispositivo por meio do conector MCP do TypingMind.

Guia de configuração para usar o conector local

Use esta opção quando o servidor MCP precisar acessar arquivos locais, aplicativos ou recursos privados no seu computador.

1

Abra as configurações de MCP

No TypingMind, vá até Configurações, Configurações avançadas e depois Model Context Protocol e selecione Configurar conector.

  1. Abra o TypingMind no navegador.
  2. Clique no ícone de Ajustes.
  3. Acesse Configurações avançadas.
  4. Abra a seção Model Context Protocol.
  5. Clique em Configurar conector e selecione Este dispositivo.
Tela de configuração do conector MCP do TypingMind com a opção Este dispositivo selecionada
2

Execute o comando do conector

Selecione Este dispositivo, copie o comando do TypingMind e execute-o no Terminal. Mantenha o processo em execução enquanto usa o MCP.

  1. Copie o comando de configuração exibido pelo TypingMind.
  2. Abra o Terminal no macOS ou o Windows Terminal no Windows.
  3. Cole e execute o comando.
  4. Autorize a instalação do pacote se o Terminal pedir confirmação para continuar.
  5. Mantenha o processo em execução na janela do Terminal enquanto usa as ferramentas MCP.
3

Adicione Postgres MCP Server como servidor

Quando o status do conector for Pronto, clique em Editar e cole a configuração do servidor MCP.

  1. Aguarde até que o status do conector mostre Pronto.
  2. Clique em Editar.
  3. Cole a configuração do servidor MCP de Postgres MCP Server.
  4. Salve a lista de servidores.
  5. Atualize para confirmar se o conector ainda está pronto para uso.
Configurações de MCP do TypingMind mostrando um servidor ativo e o botão Editar
{
  "mcpServers": {
    "postgres-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@microsoft/postgres-mcp"
      ]
    }
  }
}
4

Use a conexão com diferentes modelos

Salve a lista de servidores, abra Plugins, ative as ferramentas MCP de Postgres MCP Server, selecione qualquer modelo de IA compatível no TypingMind e use as ferramentas no chat ou atribua-as a um agente de IA.

  1. Abra a página Plugins no TypingMind.
  2. Ative as ferramentas MCP de Postgres MCP Server.
  3. Inicie um chat e escolha o modelo de IA que deseja usar.
  4. Use as ferramentas MCP no chat ou atribua-as a um agente de IA.
  5. Mude para outro modelo de IA sempre que necessário, sem reconectar o MCP.
Chat do TypingMind usando ferramentas MCP ativadas com um modelo de IA selecionado
Pode usar Postgres MCP Server para me ajudar nesta tarefa?
Postgres MCP Server
Claro. Já li.
Veja o que encontrei usando Postgres MCP Server.

Perguntas frequentes

Para que serve o servidor MCP Postgres MCP Server?

Postgres MCP Server é um servidor MCP que permite que aplicativos de IA compatíveis se conectem a ferramentas externas e informações de contexto. No TypingMind, basta adicionar esse servidor MCP uma vez para disponibilizar suas ferramentas no seu espaço de trabalho com IA.

Posso usar o MCP Postgres MCP Server com vários modelos de IA no TypingMind?

Sim. O TypingMind conecta as ferramentas MCP no nível do espaço de trabalho, permitindo usar Postgres MCP Server com diferentes modelos de IA, como Claude, ChatGPT, Gemini ou outros modelos configurados no TypingMind, sem configurar o servidor MCP separadamente para cada modelo.

Por que usar o MCP Postgres MCP Server com o TypingMind?

O TypingMind é uma das melhores interfaces de chat com LLMs porque reúne vários modelos de IA, prompts, plugins, agentes de IA, chaves de API e ferramentas MCP em um só espaço de trabalho. Com Postgres MCP Server conectado, é possível usar suas ferramentas MCP nos seus modelos preferidos e manter seu fluxo de trabalho de chat organizado no TypingMind.

Como conecto o MCP Postgres MCP Server ao TypingMind?

Postgres MCP Server funciona por meio do conector MCP local do TypingMind. Essa é a melhor opção quando o servidor MCP precisa acessar arquivos locais, apps de desktop, ferramentas de linha de comando ou recursos privados no seu computador.

Quais ferramentas o MCP Postgres MCP Server oferece no TypingMind?

Postgres MCP Server disponibiliza 13 ferramentas MCP que podem ser ativadas na página Plugins do TypingMind e usadas no chat ou atribuídas a agentes de IA.

Preciso compartilhar minhas chaves de API com o TypingMind para usar o MCP Postgres MCP Server?

Não. O TypingMind prioriza o uso local e permite manter seus provedores de modelos, chaves de API, prompts e configuração MCP sob seu controle. Se Postgres MCP Server exigir autenticação, adicione os cabeçalhos, as configurações OAuth ou a configuração local exigidos por esse servidor MCP ao criar a conexão.

Servidores MCP relacionados

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇