Permite que assistentes de IA descubram bancos de dados PostgreSQL, inspecionem esquemas, executem SQL e analisem planos de consulta ou a saúde do banco de dados.
Também conhecido como codegiveness/postgresql-sharp-mcp, @codegiveness/postgresql-sharp-mcp
- Stars
- 1
- Ferramentas
- 13
- Downloads, 30 dias
- 485
- Versão mais recente
- —
- Último commit
- 13 de nov. de 2026
- Licença
- MIT
O que é o MCP postgresql-sharp?
postgresql-sharp é um MCP server. Permite que assistentes de IA descubram bancos de dados PostgreSQL, inspecionem esquemas, executem SQL e analisem planos de consulta ou a saúde do banco de dados. Ele expõe 13 ferramentas, como macOS, tls_unavailable, list_databases.
Resumo gerado a partir do README do projeto
Sobre o MCP server de postgresql-sharp
Este servidor permite conectar assistentes de IA a bancos de dados PostgreSQL para inspeção de esquema e análise de consultas. Ele oferece a desenvolvedores, DBAs e engenheiros de dados uma maneira de permitir que agentes de codificação descubram bancos de dados, listem objetos e executem comandos SQL. O servidor roda localmente via stdio e pode ser instalado usando npx, como uma ferramenta .NET ou via arquivos independentes para Windows, macOS e Linux.
Os usuários interagem com o servidor fornecendo uma connection string para seu cliente compatível com MCP. Embora a execução de SQL seja apenas de leitura por padrão, o servidor permite gravações explícitas se configurado. Ele inclui ferramentas especializadas como explain_query para analisar planos de consulta, analyze_indexes para verificar a saúde de índices e analyze_db_health para monitorar o status do banco de dados. Também suporta a recuperação das principais consultas quando o pg_stat_statements está disponível. Todos os resultados são retornados em páginas limitadas para garantir que o assistente possa lidar com grandes conjuntos de dados por meio de paginação.
O que você pode fazer com ele
- 1Inspecionar estruturas de banco de dadosPeça ao seu assistente para mostrar as colunas e índices de uma tabela específica em um banco de dados.
- 2Otimizar consultas lentasUse o assistente para determinar por que uma instrução SQL específica está com desempenho ruim e se novos índices são necessários.
- 3Monitorar a saúde do banco de dadosSolicite um resumo da saúde do banco de dados e do uso de índices para identificar índices não utilizados ou duplicados.
- 4Executar consultas de dadosPeça ao assistente de IA para executar consultas SQL para recuperar informações específicas de suas tabelas.
Escrito a partir do README do projeto. Cada caso de uso é verificado com uma citação dele.
Como instalar o MCP postgresql-sharp
Formatos verificados em 10 nov 2026Adicionar ao CursorAdicionar ao GooseInstalar o MCP postgresql-sharp no Claude Code
$ claude mcp add postgresql-sharp-mcp -- npx -y @codegiveness/postgresql-sharp-mcpInstalar o MCP postgresql-sharp no Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"postgresql-sharp-mcp": {
"command": "npx",
"args": [
"-y",
"@codegiveness/postgresql-sharp-mcp"
]
}
}
}Instalar o MCP postgresql-sharp no VS Code
.vscode/mcp.json
{
"servers": {
"postgresql-sharp-mcp": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@codegiveness/postgresql-sharp-mcp"
]
}
}
}Instalar o MCP postgresql-sharp no VS Code CLI
$ code --add-mcp '{"name":"postgresql-sharp-mcp","type":"stdio","command":"npx","args":["-y","@codegiveness/postgresql-sharp-mcp"]}'Instalar o MCP postgresql-sharp no Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"postgresql-sharp-mcp": {
"command": "npx",
"args": [
"-y",
"@codegiveness/postgresql-sharp-mcp"
]
}
}
}Instalar o MCP postgresql-sharp no Codex
$ codex mcp add postgresql-sharp-mcp -- npx -y @codegiveness/postgresql-sharp-mcpInstalar o MCP postgresql-sharp no Codex config.toml
~/.codex/config.toml
[mcp_servers.postgresql-sharp-mcp] command = "npx" args = ["-y", "@codegiveness/postgresql-sharp-mcp"]
Instalar o MCP postgresql-sharp no Gemini CLI
$ gemini mcp add -s user postgresql-sharp-mcp npx -- -y @codegiveness/postgresql-sharp-mcpInstalar o MCP postgresql-sharp no Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"postgresql-sharp-mcp": {
"command": "npx",
"args": [
"-y",
"@codegiveness/postgresql-sharp-mcp"
]
}
}
}Ferramentas do MCP postgresql-sharp 13
Detectadas a partir do READMEmacOStls_unavailablelist_databaseslist_schemaslist_objectsget_object_detailsexecute_sqlexplain_queryanalyze_indexesget_top_queriesanalyze_db_healthadvisory
| macOS | — | |
| tls_unavailable | — | |
| list_databases | — | |
| list_schemas | — | |
| list_objects | — | |
| get_object_details | — | |
| execute_sql | — | |
| explain_query | — | |
| analyze_indexes | — | |
| get_top_queries | — | |
| analyze_db_health | — | |
| advisory | — |
Mostrar todas as 13 ferramentasMostrar menos ferramentas
pg_stat_statements
| pg_stat_statements | — |
Configuração
POSTGRES_ACCESS_MODEPOSTGRES_DATABASESPOSTGRES_DATABASE_LOCK_MODEPOSTGRES_REQUIRE_DATABASE_LOCK
| Nome | Descrição | Tipo |
|---|---|---|
| POSTGRES_ACCESS_MODE | — | |
| POSTGRES_DATABASES | — | |
| POSTGRES_DATABASE_LOCK_MODE | — | |
| POSTGRES_REQUIRE_DATABASE_LOCK | — |
Verificações automatizadas
Executado em 13 de nov. de 2026Relatório completo →Passou em nossas verificações automatizadas. Isso não é uma auditoria de segurança: leia o código e dê ao servidor o acesso mais restrito de que ele precisa. Como as verificações funcionam
- Repositório de origem vinculado e acessívelPassou
- Licença de código aberto (OSI)Passou
- Commit ou release no último anoPassou
- Nome do pacote não é próximo a um pacote popularPassou
- O endpoint remoto usa HTTPSNão verificado
- Ferramentas destrutivas estão rotuladasNão verificado
- Sem instruções ocultas para o modeloPassou
- Nenhum aviso crítico no pacote ou em suas dependênciasNão verificado
README
Ver no GitHubpostgresql-sharp-mcp — PostgreSQL tools for your AI assistant
Let your AI assistant connect to PostgreSQL, list the databases you can access, inspect tables and run SQL, with query plans, index analysis and database health checks built in.
Who it is for: developers, DBAs and data engineers who have a PostgreSQL login and use an MCP-compatible AI assistant or coding agent that starts local (stdio) servers. This app is a Model Context Protocol server written in C# with Npgsql. Your MCP client starts the app when needed; it does not create a PostgreSQL database for you.
SQL calls are read-only by default, but the server's default access mode permits explicitly requested writes. A least-privileged database login is recommended, but any login that can connect works for a first run, including a superuser such as postgres; --validate then prints advisory [warning] lines. Before you use real or shared data, follow Hardening for advanced users. Keep an existing explicit restricted setting; access boundaries explain how to refuse writes entirely.
Fastest start: Node.js 22+ and npm are enough, because npm installs the .NET runtime with the server. This downloads and runs version 0.7.1:
npx -y --allow-scripts=@codegiveness/postgresql-sharp-mcp @codegiveness/postgresql-sharp-mcp@0.7.1 --version
It should print postgresql-sharp-mcp 0.7.1.0. Then register it with your MCP client and enter your connection string: the quick start has three steps. Prefer a .NET tool or a standalone archive for Linux, macOS or Windows? See step 1. To build and run a container image from the Dockerfile, see CONTRIBUTING.md.
Upgrading from 0.6.0 or earlier? Since 0.7.0, two 0.6.0 defaults are looser so that a plain connection string works (0.7.1 itself adds no behavior change): a connection string without
SSL Modenow usesPrefer(TLS when the server offers it, certificate not verified) instead ofVerifyFull, and the database lock is now advisory by default (the server's tools still enforce the list, but PostgreSQL grant findings are warnings) instead of refusing startup. To keep the 0.6.0 behavior, putSSL Mode=VerifyFullin the connection string and setPOSTGRES_DATABASE_LOCK_MODE=strict; a string withRoot Certificateand noSSL ModekeepsVerifyFullunchanged. Run--validatebefore reconnecting, and read the upgrade note, which also covers upgrades from 0.5.0 or earlier.
What you can ask once it is connected:
| You ask your assistant | Tools it calls |
|---|---|
| "Which databases can I access on this server?" | list_databases |
"Show the columns and indexes of public.orders in app_db." |
list_objects, get_object_details |
| "How many orders were placed yesterday?" | execute_sql, read-only by default |
"Why is this query slow? Would an index on customer help?" |
explain_query, optionally with hypothetical HypoPG indexes |
| "Are any indexes unused or duplicated? Is vacuum keeping up?" | analyze_indexes, analyze_db_health |
| "Which statements take the most total time?" | get_top_queries, with pg_stat_statements |
Every result is a row- and byte-bounded page that the assistant can continue with next_offset (result format). The tool reference lists all nine tools and their options.
Quick start
For one PostgreSQL server, you need one connection string—not a targets file or an entry for every database. You also need access to an existing database and an installed MCP client. The walkthrough below uses OMP. It stores only the executable path and nonsensitive options in OMP's configuration; you enter credentials privately each session.
Already installed and registered? Skip to step 2. Switching from a targets file? Open Advanced setup, troubleshooting and legacy profiles below first. Keep your existing file.
1. Install or run
Choose npx for on-demand execution or a .NET tool for a persistent command. Starting with 0.3.3, npm bundles the .NET runtime: npx requires only Node.js 22+ and npm, not an installed .NET runtime or SDK. The .NET tool still requires the .NET 10 runtime, and installing it requires the .NET 10 SDK.
This guide targets 0.7.1. Registry commands require the corresponding published version; if it is unavailable, build and install the local npm artifact. npm 0.3.2 still requires .NET; installing it globally does not remove that prerequisite.
npx — run without a global install:
npx -y --allow-scripts=@codegiveness/postgresql-sharp-mcp @codegiveness/postgresql-sharp-mcp@0.7.1 --version
The package-specific --allow-scripts approves installation on npm 12. Do not use --ignore-scripts for automatic setup. npm downloads only the platform package matching your OS/CPU (about 35–39 MB; the main package is under 1 MB). Its self-contained C# installer then installs the server and runtime. Starting with 0.5.0, npm no longer downloads all five platform runtimes. The installer downloads nothing itself. The installed server command is native; it needs neither Node.js nor dotnet to run.
.NET tool — install once, then run by name:
dotnet tool install --global codegiveness.postgresql-sharp-mcp --version 0.7.1
postgresql-sharp-mcp --version
If the command is not found, add the .NET tools directory to your PATH ($HOME/.dotnet/tools on Linux/macOS; %USERPROFILE%\.dotnet\tools on Windows), or use its absolute executable path. Do not reinstall to fix PATH.
The command should report 0.7.1 (or assembly version 0.7.1.0). Continue with registration below, then prepare your connection environment in step 2. Package versions are immutable; a published release archive is an alternative if your registry is unavailable.
Download one archive and SHA256SUMS from release 0.7.1. These archives include the .NET runtime: you do not need the .NET SDK, npm, Node.js or Docker for this installation.
| Your computer | Archive |
|---|---|
| Linux, Intel/AMD 64-bit | postgresql-sharp-mcp-linux-x64.tar.gz |
| Linux, ARM64 | postgresql-sharp-mcp-linux-arm64.tar.gz |
| Mac, Apple Silicon (M-series) | postgresql-sharp-mcp-osx-arm64.tar.gz |
| Mac, Intel | postgresql-sharp-mcp-osx-x64.tar.gz |
| Windows, Intel/AMD 64-bit | postgresql-sharp-mcp-win-x64.zip |
Extract into postgresql-mcp/app inside your home folder, keeping all the extracted files together. Open the instructions for your OS below to check the download, extract it and check the version. Commands assume you saved the archive in Downloads.
Compare the hash printed by the first command with your archive's entry in the downloaded SHA256SUMS. Stop if they differ; extract only after they match. For ARM64, replace both archive filenames with postgresql-sharp-mcp-linux-arm64.tar.gz.
sha256sum "$HOME/Downloads/postgresql-sharp-mcp-linux-x64.tar.gz"
mkdir -p "$HOME/postgresql-mcp/app"
tar -xzf "$HOME/Downloads/postgresql-sharp-mcp-linux-x64.tar.gz" -C "$HOME/postgresql-mcp/app"
"$HOME/postgresql-mcp/app/PostgreSqlMcp" --version
Compare the hash printed by the first command with your archive's entry in the downloaded SHA256SUMS. Stop if they differ; extract only after they match. For an Intel Mac, replace both archive filenames with postgresql-sharp-mcp-osx-x64.tar.gz.
shasum -a 256 "$HOME/Downloads/postgresql-sharp-mcp-osx-arm64.tar.gz"
mkdir -p "$HOME/postgresql-mcp/app"
tar -xzf "$HOME/Downloads/postgresql-sharp-mcp-osx-arm64.tar.gz" -C "$HOME/postgresql-mcp/app"
"$HOME/postgresql-mcp/app/PostgreSqlMcp" --version
Compare the hash printed by the first command with your archive's entry in the downloaded SHA256SUMS (case does not matter). Stop if they differ; extract only after they match.
Get-FileHash "$HOME\Downloads\postgresql-sharp-mcp-win-x64.zip" -Algorithm SHA256
New-Item -ItemType Directory -Force "$HOME\postgresql-mcp\app" | Out-Null
Expand-Archive -Path "$HOME\Downloads\postgresql-sharp-mcp-win-x64.zip" -DestinationPath "$HOME\postgresql-mcp\app"
& "$HOME\postgresql-mcp\app\PostgreSqlMcp.exe" --version
The executable should report 0.7.1. If you already have an older installation, read upgrade notes before reusing its configuration.
Register with OMP once. Edit or create ~/.omp/agent/mcp.json on Linux/macOS, or %USERPROFILE%\.omp\agent\mcp.json on Windows (for a named OMP profile, use that profile's MCP configuration). Installing this app does not register it automatically.
For npx, use this JSON for a new file. If the file already has other servers, add only the "postgresql" entry inside its existing mcpServers object; preserve every other entry and separate adjacent entries with a comma.
{
"mcpServers": {
"postgresql": {
"type": "stdio",
"command": "npx",
"args": ["-y", "--allow-scripts=@codegiveness/postgresql-sharp-mcp", "@codegiveness/postgresql-sharp-mcp@0.7.1"]
}
}
}
For a .NET tool, replace command with "postgresql-sharp-mcp" and remove args; the client must inherit the tools directory on PATH. Alternatively, use the absolute tool path (/home/YOUR_USER/.dotnet/tools/postgresql-sharp-mcp on Linux, /Users/YOUR_USER/.dotnet/tools/postgresql-sharp-mcp on macOS, or "C:\\Users\\YOUR_USER\\.dotnet\\tools\\postgresql-sharp-mcp.exe" in Windows JSON).
For a standalone archive, remove args and use the absolute executable path, not the folder or archive:
- Linux:
/home/YOUR_USER/postgresql-mcp/app/PostgreSqlMcp - macOS:
/Users/YOUR_USER/postgresql-mcp/app/PostgreSqlMcp - Windows JSON:
"C:\\Users\\YOUR_USER\\postgresql-mcp\\app\\PostgreSqlMcp.exe"
Replace YOUR_USER with your home-folder name, or adjust the whole home prefix if yours differs. echo "$HOME" on Linux/macOS or $HOME in PowerShell shows your home path. JSON does not expand ~, $HOME or %USERPROFILE%. Do not add credentials to this file. Preserve any intentional "POSTGRES_ACCESS_MODE": "restricted" setting when updating an existing entry.
2. Prepare the connection environment
Enter one complete .NET/Npgsql key=value connection string at the hidden prompt below. Your provider's .NET/Npgsql string is accepted; a raw postgres:// or postgresql:// URL is not. Replace all <...> placeholders, including angle brackets, with your database details. This example is a format guide, not a command:
Host=<YOUR_HOST>;Port=5432;Database=<YOUR_DATABASE>;Username=<YOUR_DATABASE_USER>;Password=<YOUR_PASSWORD>
Database is an accessible starting database, such as your existing database or postgres; the same login can discover other accessible databases on that server. For special characters or a provider-supplied URL, open connection-string guidance.
Linux/macOS — paste into your current Bash or Zsh terminal. No shell change or startup-file edit is needed. Then type or paste the connection string at the hidden prompt and press Enter:
unset POSTGRES_TARGETS POSTGRES_TARGETS_FILE POSTGRES_CONNECTION_STRING
printf 'PostgreSQL connection string (hidden): ' >&2
IFS= read -r -s POSTGRES_CONNECTION_STRING && export POSTGRES_CONNECTION_STRING
printf '\n' >&2
Windows — use the built-in Windows PowerShell (5.1 or newer) in an interactive terminal:
Remove-Item Env:POSTGRES_TARGETS, Env:POSTGRES_TARGETS_FILE, Env:POSTGRES_CONNECTION_STRING -ErrorAction SilentlyContinue
$connection = Read-Host 'PostgreSQL connection string (hidden)' -AsSecureString
try {
$env:POSTGRES_CONNECTION_STRING = [System.Net.NetworkCredential]::new('', $connection).Password
} finally {
$connection.Dispose()
Remove-Variable connection
}
Keep this terminal open. Enter the secret at the prompt, never in a command, MCP JSON, chat or shell startup file. Do not print the variable to check it. Hidden entry prevents display/history exposure; the exported environment is still plaintext process memory, inherited by child processes—not encrypted storage.
3. Validate, start OMP and ask for databases
Fully quit any existing OMP process first. In the same terminal from step 2, run the command for your OS. It checks connectivity and starts a new OMP process only if validation succeeds:
Use the command for your installation method. If you use a standalone archive, replace the command with its absolute executable path followed by --validate.
npx, Linux/macOS:
npx -y --allow-scripts=@codegiveness/postgresql-sharp-mcp @codegiveness/postgresql-sharp-mcp@0.7.1 --validate && omp
.NET tool, Linux/macOS:
postgresql-sharp-mcp --validate && omp
Windows PowerShell (.NET tool):
postgresql-sharp-mcp --validate
if ($LASTEXITCODE -eq 0) {
omp
} else {
throw 'Connection validation failed; repeat step 2 or check your database details.'
}
For npx in PowerShell, replace the first line with npx -y --allow-scripts=@codegiveness/postgresql-sharp-mcp @codegiveness/postgresql-sharp-mcp@0.7.1 --validate; keep the $LASTEXITCODE check and launch block.
Validation is read-only and exits; its successful stderr output includes your database name, so keep it private. Empty input is rejected before OMP starts. Lines that start with [warning] (about TLS, a superuser login or the database lock) are advice: they do not stop validation or the server, and Hardening for advanced users explains how to act on them. If it fails, fix your connection details and repeat step 2; troubleshooting covers common failures.
In OMP, ask: “Use the PostgreSQL MCP server to list the databases I can access, then run SELECT 1 AS connection_ok in the starting database using alias primary.” You are ready when it lists real database names and the query returns 1.
The client must inherit this terminal's environment. A desktop/Start-menu launch, an already-running client, or /mcp reload cannot pick up a newly entered secret. For a later session or changed password, fully quit OMP, repeat step 2, and launch it again from that prepared terminal. You do not repeat registration or edit a file for new databases. Other MCP clients need their own configuration schema and a launcher that starts a new process with the inherited environment; GUI clients that cannot do this need the advanced file alternative.
When finished, fully quit OMP/server and clear the terminal's secret with unset POSTGRES_CONNECTION_STRING (Bash/Zsh) or Remove-Item Env:POSTGRES_CONNECTION_STRING -ErrorAction SilentlyContinue (PowerShell). This does not erase copies in children that are still running.
Optional help: Click a section title below to open it.
Connection-string quoting and TLS
Use the database host and port supplied by your provider, an accessible bootstrap database, and a PostgreSQL login role with CONNECT to the intended databases and only the object privileges it needs. The database username is not necessarily your computer's username.
At the hidden prompt, quoting has one layer: Npgsql, not JSON or shell syntax. Quote a value containing a semicolon, for example the synthetic fragment Password="sample;value". Inside a double-quoted value, double a literal double quote (Password="sample""value"). Backslashes are entered literally; do not add JSON's \" or double backslashes for JSON. Prefer a provider-generated .NET/Npgsql string over constructing one by hand.
If your provider supplies only a PostgreSQL URL, map its host, port, database, username and password to the example's fields, decode URL-escaped values, and preserve required TLS/authentication options. The URL itself cannot be entered unchanged; startup says so and names the expected Host, Port, Database, Username and Password keys.
TLS is used when the server offers it, and is not verified by default. If a connection string does not set SSL Mode, the server uses SSL Mode=Prefer for every host, loopback included: TLS when the server offers it, plaintext otherwise, and the server certificate is never verified. This works with a PostgreSQL server with or without TLS and needs no TLS setup. The trade-off: on a network you do not control, someone on the network path could force plaintext, read the traffic or impersonate the server and capture your credentials. That is acceptable on a trusted network or for local development. For a host that is not loopback or a Unix-domain socket, the server prints a [warning] at startup and in --validate. To verify the server, add SSL Mode=VerifyFull to the connection string, plus Root Certificate=<absolute-path-to-provider-CA-file> for a provider or private CA (hardening; see also Npgsql's TLS requirements). The host name you connect to must then appear in the certificate.
An explicit SSL Mode (any value) is your decision and is used unchanged. One exception to the Prefer default: a connection string with Root Certificate=<CA file> but no SSL Mode gets SSL Mode=VerifyFull, because a CA file is only useful for verification (Npgsql's Prefer would ignore it). With VerifyCA or VerifyFull, the certificate chain (and for VerifyFull the host name) is verified before any credential is sent and the connection never falls back to plaintext. A non-loopback profile whose mode is not VerifyCA/VerifyFull still works but prints the [warning]; it is advice, not an error. --validate also warns when the login is a superuser or holds server-file, signal or checkpoint roles (details), and these warnings never block startup.
Perguntas sobre o MCP postgresql-sharp
Como adiciono o MCP postgresql-sharp ao Claude Code?
Execute claude mcp add postgresql-sharp-mcp -- npx -y @codegiveness/postgresql-sharp-mcp no seu terminal. Adicione --scope user para torná-lo disponível em todos os projetos.
Como adiciono o MCP postgresql-sharp ao Cursor?
Abra ~/.cursor/mcp.json e adicione o servidor em mcpServers, usando a configuração do Cursor mostrada na seção de instalação acima.
Quais ferramentas o MCP postgresql-sharp oferece?
Ele expõe 13 ferramentas, incluindo macOS, tls_unavailable, list_databases, list_schemas, list_objects.
A execução de SQL é segura?
As chamadas SQL são apenas de leitura por padrão, embora o modo de acesso padrão do servidor permita gravações solicitadas explicitamente.
Como posso instalá-lo rapidamente?
A maneira mais rápida é usando npx com Node.js 22+ e npm, que instala automaticamente o runtime .NET necessário.