pg-multi-mcp
Provides access to multiple named PostgreSQL database connections at once, allowing an AI assistant to discover connections by name or alias, list schemas and tables, execute SQL with read-only or unrestricted access modes, inspect explain plans and hypothetical indexes, run health checks, and get index recommendations and top-query analysis.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@pg-multi-mcp list the tables in the staging database"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
pg-multi-mcp
English · Português
A local MCP server that gives an AI assistant access to many named database connections at once. You say "list the tables in the staging database" and the assistant finds the right connection by name or alias, reuses an already-open pool, and closes pools that sit idle.
It supports PostgreSQL and MongoDB. The core (connection registry, name resolution, pool lifecycle, config
reload) does not depend on the engine: every connection has an engine field (inferred from the URL when omitted)
and engine-specific code lives in its own subpackage (postgres/, mongodb/).
Table of contents
Related MCP server: pg-mcp
Features
Feature | Description |
Many named connections | Declared in a JSON file, in the client's |
Pick a database per call | Every database tool takes a |
Forgiving lookup | Matches name, aliases, tags and description, ignoring case and accents, with "did you mean" suggestions |
Access mode per connection |
|
Lazy, reused pools | Opened on first use, reused afterwards, closed when idle, evicted LRU when over the limit |
Fast, real connection errors | Wrong password, DNS or closed port are reported in seconds, not as a generic timeout |
Live config reload | Edits to the config file apply on the next call; unchanged connections keep their pools |
PostgreSQL analysis tools | Explain plans (including hypothetical indexes via HypoPG), health checks, index recommendations, top queries |
MongoDB support |
|
Safe output size |
|
No secret leakage | Passwords never appear in listings or error messages |
Requirements
Python 3.12+
Network access to the databases you configure
Optional:
uvif you want to run it withuvxinstead of a local virtualenvOptional PostgreSQL extensions for some tools:
pg_stat_statements(top queries, workload analysis) andhypopg(hypothetical indexes)MongoDB 4.2+ for MongoDB connections (driver:
pymongowith its native asyncio client)
Installation
Option A — local virtualenv
git clone https://github.com/Snarloff/pg-multi-mcp.git
cd pg-multi-mcp
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e .The command is now at .venv\Scripts\pg-multi-mcp.exe (Windows) or .venv/bin/pg-multi-mcp (Linux/macOS).
Option B — uvx straight from git (no manual build)
uvx downloads, builds and caches it from the repository on first run:
uvx --from git+https://github.com/Snarloff/pg-multi-mcp pg-multi-mcp --helpThis tracks the default branch. To pin a version, append a tag or commit, e.g.
git+https://github.com/Snarloff/pg-multi-mcp@v0.1.0, so everyone runs the same code; change it to upgrade.
Quick start
Install (see above).
Create the config file at
~/.pg-multi-mcp/connections.json(Windows:C:\Users\<you>\.pg-multi-mcp\connections.json):{ "connections": { "local": { "url": "postgresql://postgres@localhost:5432/postgres", "access_mode": "unrestricted", "description": "Local development database", "aliases": ["dev"] } } }Provide the password through pgpass or an environment variable (see Passwords).
Register the server in your MCP client:
claude mcp add pg-multi-mcp --scope user -- C:\path\to\pg-multi-mcp\.venv\Scripts\pg-multi-mcp.exeRestart the client and ask: "list my database connections", then "list the schemas in dev".
Configuring connections
Connections can come from two sources, loaded in this order:
Source | Use it for | Persisted | Editable by tools |
1. Config file | Your main registry of databases | Yes | Yes ( |
2. Client config | Quick or project-specific connections | Session only | Only removed from the session |
If a name exists in both, the .mcp.json one wins for the session; the file entry stays untouched on disk and
comes back if the override is removed. If the DATABASE_URI variable is set, it becomes a session connection named
default (read-only).
1. Config file
Default location:
~/.pg-multi-mcp/connections.json.Override with
--config <path>or thePG_MULTI_MCP_CONFIGvariable.~is expanded.A missing file is fine: the server starts with no connections.
Template: connections.example.json.
{
"default": "local",
"settings": {
"idle_timeout_seconds": 600,
"max_open_connections": 10
},
"connections": {
"local": {
"engine": "postgres",
"url": "postgresql://postgres:${PG_LOCAL_PASSWORD}@localhost:5432/postgres",
"access_mode": "unrestricted",
"description": "Local development database",
"aliases": ["dev", "localhost"],
"tags": ["development"]
},
"sales_staging": {
"url": "host=staging.example.com port=5432 dbname=sales user=readonly sslmode=require",
"description": "Sales - staging (read-only)",
"aliases": ["sales staging"],
"tags": ["staging", "sales"],
"max_pool_size": 2,
"query_timeout": 30
},
"orders_mongo": {
"url": "mongodb://reader:${MONGO_ORDERS_PASSWORD}@mongo.example.com:27017/orders?authSource=admin&tls=true",
"description": "Orders - MongoDB (read-only)",
"aliases": ["orders"],
"tags": ["mongodb"]
}
}
}Top-level keys
Key | Default | Description |
|
| Connection used when a tool call does not name one (see resolution) |
|
| Close a pool after this many idle seconds ( |
|
| Maximum pools open at the same time; the least recently used idle pool is closed beyond that |
|
| Map of connection name → definition |
Connection fields
Field | Required | Default | Description |
(key) | yes | — | Connection name: letters, digits, |
| yes | — | PostgreSQL: libpq URI ( |
| no | from the URL |
|
| no |
|
|
| no |
| Free text; used by search |
| no |
| Alternative names the assistant can use to find the connection |
| no |
| Grouping/search labels such as |
| no |
| Maximum connections in this pool |
| no |
| Query/operation timeout in seconds for |
Names and aliases must be unique across all connections after normalization (case, accents and separators are
ignored), so Sales-Staging, sales_staging and Sales Staging are the same key.
2. .mcp.json (client config)
Every environment variable named PG_MULTI_MCP_CONN_<NAME> becomes a connection called <name> (lower-cased).
Its value is either a URL/DSN or a JSON object with the same fields as the file. PG_MULTI_MCP_DEFAULT sets the
default connection for the session. Template: mcp.example.json.
{
"mcpServers": {
"pg-multi-mcp": {
"command": "C:\\path\\to\\pg-multi-mcp\\.venv\\Scripts\\pg-multi-mcp.exe",
"args": ["--access-mode", "restricted"],
"env": {
"PG_PROJECT_PASSWORD": "${PG_PROJECT_PASSWORD}",
"PG_MULTI_MCP_CONN_PROJECT_DEV": "postgresql://app:${PG_PROJECT_PASSWORD}@localhost:5432/project_dev",
"PG_MULTI_MCP_CONN_PROJECT_STG": "{\"url\": \"postgresql://readonly@staging.example.com/project\", \"aliases\": [\"staging\"]}",
"PG_MULTI_MCP_DEFAULT": "project_dev"
}
}
}
}
.mcp.jsonis usually committed to the project repository. Never put a literal password in it: use${VAR}(expanded by the client from your environment) or pgpass.
Passwords and secrets
Pick one of these, from most to least recommended:
1. pgpass file (no password in any config). libpq reads it automatically when the URL has no password.
OS | Location |
Windows |
|
Linux/macOS |
|
Format: host:port:database:user:password, * is a wildcard. One line can cover many databases:
*:5432:*:readonly_user:<password>2. ${VAR} placeholder. Put ${PG_LOCAL_PASSWORD} in the URL and define the variable:
setx PG_LOCAL_PASSWORD "<password>" # then restart the MCP client so it sees the variableThe placeholder is stored as-is and only expanded when connecting. If the variable is missing, the call fails with a clear message naming it.
3. Literal password in connections.json. Works, but the file is plain text readable by anything running as
your user. add_connection warns when it is about to save a literal password.
URL encoding: in the URI form, passwords containing @ : / # ? % must be percent-encoded. The key/value DSN
form (password=...) does not need encoding as long as the password has no spaces or quotes.
Registering the server in an MCP client
Claude Code (user scope, available in every project):
claude mcp add pg-multi-mcp --scope user -- C:\path\to\pg-multi-mcp\.venv\Scripts\pg-multi-mcp.exe --access-mode restrictedClaude Code (project scope): create .mcp.json in the project root as shown in
.mcp.json (client config).
Claude Desktop: edit %APPDATA%\Claude\claude_desktop_config.json (Windows) or
~/Library/Application Support/Claude/claude_desktop_config.json (macOS) and add the same mcpServers entry.
With uvx:
"pg-multi-mcp": {
"command": "uvx",
"args": ["--from", "git+https://github.com/Snarloff/pg-multi-mcp", "pg-multi-mcp", "--access-mode", "restricted"]
}After changing the client config, restart or reconnect the server (in Claude Code: /mcp).
Command-line options
Option | Default | Description |
|
| Connections file |
| (per connection) | Global cap: forces every connection to read-only, regardless of the file |
| Same as omitting it: each connection uses its own | |
| file setting, else | Seconds before an idle pool is closed ( |
| file setting, else | Maximum open pools (LRU eviction). Overrides the file |
| off | Disables |
| off | Do not reload the config file when it changes |
|
| MCP transport |
|
| Bind address for |
|
| Port for |
|
|
|
Recommended for production databases: --access-mode restricted --lock-config.
Environment variables
Variable | Description |
| Path to the connections file (same as |
| Declares a session connection |
| Default connection for the session (takes precedence over the file's |
| Compatibility: becomes a read-only session connection named |
|
|
Any | Expanded inside connection URLs at connect time |
Tools reference
All database tools accept an optional connection (name or alias). Every database response starts with a header
line such as [conexão: local | modo: unrestricted], so you can always see where a command ran. Server messages
are in Portuguese.
Connection management
Tool | Arguments | What it does |
|
| Lists connections: engine, target (host/port/db/user, never the password), access mode, source ( |
|
| Validates the connection (opens it) and makes it the session's active connection |
|
| Opens or reuses the pool and returns database, user, server version and latency |
|
| Closes one pool or all of them. The definition is kept and reopens on next use |
|
| Adds a connection. With |
|
| Closes and removes a connection (also from the file if it came from there). Removing an env override brings back the file entry |
| — | Re-reads the file now and reports |
Database (PostgreSQL and MongoDB)
Tool | Main arguments | PostgreSQL | MongoDB |
| — | Lists schemas and classifies them as user/system | Lists the databases the user can see, with size |
|
| Lists tables, views, sequences or extensions |
|
|
| Columns, constraints and indexes of a table/view; details of a sequence or extension | Type, estimated count, indexes and the fields/types found in a sample of 100 documents (field names, types and how many documents have them — never the values) |
MongoDB
Tool | Main arguments | What it does |
|
| Reads: |
PostgreSQL only
These reject MongoDB connections with a clear message (before opening a pool).
Tool | Main arguments | What it does |
|
| Runs SQL. Read-only on |
|
| Execution plan; |
|
| Recommends indexes from the workload in |
|
| Recommends indexes for the given queries |
|
| Health checks: |
|
| Slowest or most resource-intensive queries ( |
How a connection is chosen
When connection is given, it is matched in this order:
Exact name.
Normalized name or alias: lower case, no accents, no spaces/
_/-/.. So"Relatórios","relatorios"and"RELATORIOS"are the same.Not found: the error lists close matches (
"Did you mean: ...") and partial matches.
When connection is omitted:
The active connection (set by
use_connection).The default (
PG_MULTI_MCP_DEFAULT, otherwise the file'sdefault).The only connection, if exactly one exists.
Otherwise an error asks the assistant to specify one and lists the available names. The server never guesses between several databases.
list_connections(search="...") searches names, aliases, tags and descriptions with the same normalization.
The server also gives the assistant instructions to look up connections this way and to always pass connection
explicitly when there is more than one.
Connection lifecycle
Lazy: no pool is opened at startup.
First use: a single test connection is made (fails fast with the real error), then the pool is opened.
Reuse: later calls reuse the pool.
Idle close: every 30 seconds, pools idle for longer than
idle_timeout_secondsare closed. Pools in use are never closed.LRU eviction: opening a pool beyond
max_open_connectionscloses the least recently used idle pool.Self-healing: a query error invalidates the pool; it is recreated on the next call.
Shutdown: all pools are closed when the server exits.
Sessions are visible in pg_stat_activity with application_name = 'pg-multi-mcp'. A closed pool reopens
transparently, so close_connection is about freeing server connections, not about access.
Editing the config while the server runs
There is no need to restart after editing connections.json:
Automatic: before each use the server compares the file's modification time and reloads it if it changed.
Manual:
reload_connectionsreloads now and reports what changed.Pools: unchanged connections keep their open pools; changed and removed ones are closed.
Invalid edits: if the file has invalid JSON (or a duplicate name/alias), the previous version stays in effect and
list_connectionsshowsconfig_errorwith line and column only (never file content) until you fix it.No lost edits:
add_connection/remove_connectionreload before writing, so they never overwrite manual changes, and they are blocked while the file is invalid..mcp.jsonconnections are not affected by reloads.
Changes to .mcp.json itself are only read when the client restarts the server.
Access modes and security
restricted (default)
SQL is parsed (
pglast) and checked against an allowlist of statements (essentiallySELECT,EXPLAIN,SHOWand cursors) and of functions.Everything runs inside a
READ ONLYtransaction, so PostgreSQL itself rejects any write that gets through.Queries are aborted after
query_timeoutseconds.
restricted on MongoDB — MongoDB has no read-only transaction, so the allowlist is the application's only
barrier; use a database user with the read role as the real guarantee.
Only
find,aggregate,count,distinctand a few read-only commands (ping,buildInfo,dbStats,collStats,listCollections,listIndexes,listDatabases,serverStatus,connectionStatus,hostInfo).$outand$merge(writes) and$where,$function,$accumulator(server-side JavaScript) are rejected at any depth of the filter or pipeline (including$lookup,$facet,$unionWith).Every operation is aborted after
query_timeoutseconds.
unrestricted: any SQL, including INSERT, UPDATE, DELETE, DROP; on MongoDB, also the insert, update,
replace and delete operations. Use only for databases you own.
Global cap: --access-mode restricted forces every connection to read-only, even if someone sets
unrestricted in the file or adds one from the chat. --lock-config additionally prevents adding or removing
connections.
Recommendations
The real guarantee is the database user's privileges: connect with a read-only database user.
Query results are sent to the AI model. For databases with personal data, use read-only access, prefer aggregated or anonymized queries, and make sure you have a legal basis to process that data. This tool does not solve data-protection compliance (LGPD, GDPR...).
Prefer
sslmode=require(or stricter) for remote databases.Passwords are never included in
list_connectionsoutput or error messages.The server sends data only to the MCP client that launched it; it calls no other external service.
Example prompts
You say | What the assistant does |
"Which databases do I have?" |
|
"List the tables in sales staging" |
|
"Use dev from now on" |
|
"Compare the | Two |
"Why is this query slow in staging?" |
|
"Is the staging database healthy?" |
|
"I added a database to the file" | Nothing needed (auto-reload), or |
"Close all connections" |
|
Troubleshooting
Symptom | Cause and fix |
| No password in the URL and none in pgpass. Add a pgpass line or a |
| Wrong user/password, or the password needs URL encoding in URI form |
| The URL references |
| Host or port unreachable: VPN, firewall or wrong port |
| Several connections and no default/active one: pass |
| Typo or missing alias; add an alias to the file |
| The file has invalid JSON or a duplicate name/alias; the message shows line/column |
| Two connections share a name or alias after normalization |
Restricted query rejected | The statement or a function is not on the read-only allowlist. Use a |
| The tool does not apply to that engine: on MongoDB use |
MongoDB | Wrong user/password or |
MongoDB | The URL has no default database: pass |
Edits to | The client reads it only on (re)start: restart or reconnect the server |
| The MCP client is running |
Need more detail | Run with |
Project layout and adding an engine
src/
└── pg_multi_mcp/ Python package (entry point: pg_multi_mcp:main)
├── __init__.py main(): starts the event loop (SelectorEventLoop on Windows)
├── server.py MCP tools and command-line options
├── connections.py Registry, name resolution, pools, LRU, idle reaper, reload, persistence
├── mongodb/ MongoDB-specific code: pool, driver, read-only allowlist, schema sampling
└── postgres/ PostgreSQL-specific code
├── sql/ Driver, pool, read-only SQL validation, extensions
├── explain/ Explain plans and hypothetical indexes
├── index/ Index advisor
├── database_health/ Health checks
└── top_queries/ pg_stat_statements reports
tests/
├── unit/test_connections.py Registry, reload, env, persistence
├── unit/test_server.py Tool routing and responses
├── unit/mongodb/ MongoDB module tests (read-only allowlist, driver)
└── unit/postgres/ PostgreSQL module testsAdding another engine (MongoDB followed these steps):
Add a value to
Enginein connections.py (and URL inference if it has its own scheme).Create
src/pg_multi_mcp/<engine>/with a pool (same interface asDbConnPool:pool_connect(),close(),pool,server_version), a driver and a read-only mode.Pick the pool/driver from the connection's
engineinConnectionManager._ensure_openandlease.Dispatch the generic tools (
list_schemas,list_objects, ...) bylease.engine; engine-specific tools passrequire=Engine.Xtolease, which rejects other engines before opening a pool.
Development
.\.venv\Scripts\python.exe -m pip install -e . pytest pytest-asyncio ruff==0.14.13
.\.venv\Scripts\python.exe -m pytest -q tests
.\.venv\Scripts\ruff.exe check src testsIntegration tests that create tables need PG_MULTI_MCP_TEST_DATABASE_URL pointing to a disposable database;
without it they are skipped.
License
MIT — see LICENSE.
Available Tools
17 toolsadd_connectionA
Adiciona uma conexão nomeada. A 'url' aceita URI (postgresql://... ou mongodb://, mongodb+srv://) ou DSN PostgreSQL (host=... dbname=...) e placeholders ${VAR} resolvidos de variáveis de ambiente — prefira-os a senhas literais. O 'engine' é inferido da URL quando omitido. Por padrão testa a conexão antes de salvar e grava no arquivo de configuração (persist=true).
Inputs: url (required), name (required), tags, test, +6 more. Returns: result
analyze_db_healthARead-only
Analyzes database health. Here are the available health checks:
index - checks for invalid, duplicate, and bloated indexes
connection - checks the number of connection and their utilization
vacuum - checks vacuum health for transaction id wraparound
sequence - checks sequences at risk of exceeding their maximum value
replication - checks replication health including lag and slots
buffer - checks for buffer cache hit rates for indexes and tables
constraint - checks for invalid constraints
all - runs all checks You can optionally specify a single health check or a comma-separated list of health checks. The default is 'all' checks.
Inputs: connection, health_type. Returns: result
analyze_query_indexesBRead-only
Analyze a list of (up to 10) SQL queries and recommend optimal indexes
Inputs: queries (required), connection, max_index_size_mb. Returns: result
analyze_workload_indexesBRead-only
Analyze frequently executed queries in the database and recommend optimal indexes
Inputs: connection, max_index_size_mb. Returns: result
close_connectionARead-only
Fecha o pool de uma conexão (libera as conexões no servidor). Use close_all=true para fechar todas. A configuração não é removida; a conexão reabre automaticamente no próximo uso.
Inputs: close_all, connection. Returns: result
execute_mongoADestructive
Run a MongoDB operation on the chosen connection. 'restricted' connections only accept reads (find, aggregate without $out/$merge, count, distinct, read-only commands; no server-side JavaScript; timeout); 'unrestricted' connections also accept insert/update/replace/delete.
Inputs: operation (required), skip, sort, field, +13 more. Returns: result
execute_sqlADestructive
Execute SQL on the chosen connection. Connections in 'restricted' mode only accept read-only SQL (validated, READ ONLY transaction, timeout); 'unrestricted' connections accept any SQL (DML/DDL).
Inputs: sql (required), max_rows, connection. Returns: result
explain_queryCRead-only
Explains the execution plan for a SQL query, showing how the database will execute it and provides detailed cost estimates.
Inputs: sql (required), analyze, connection, hypothetical_indexes. Returns: result
get_object_detailsARead-only
Show detailed information about a database object. MongoDB: collection type, estimated count, indexes and the fields/types inferred from a sample of documents (values are never returned).
Inputs: object_name (required), schema_name (required), connection, object_type. Returns: result
get_top_queriesARead-only
Reports the slowest or most resource-intensive queries using data from the 'pg_stat_statements' extension.
Inputs: limit, sort_by, connection. Returns: result
list_connectionsARead-only
Lista as conexões configuradas (nome, aliases, tags, descrição, destino sem senha, modo de acesso, status do pool, conexão ativa/padrão). Use 'search' para filtrar por nome, alias, tag ou descrição.
Inputs: search. Returns: result
list_objectsCRead-only
List objects in a schema (MongoDB: collections or views in a database)
Inputs: schema_name (required), connection, object_type. Returns: result
list_schemasARead-only
List all schemas in the database (MongoDB: lists the databases)
Inputs: connection. Returns: result
open_connectionBRead-only
Abre (ou reaproveita) o pool da conexão e testa: retorna banco, usuário, versão e latência.
Inputs: connection. Returns: result
reload_connectionsARead-only
Relê o arquivo de conexões agora e informa o que mudou (added/changed/removed/unchanged). Pools de conexões inalteradas continuam abertos; os de alteradas/removidas são fechados. Normalmente não é necessário: o arquivo é recarregado sozinho quando muda.
Inputs: no named parameters. Returns: result
remove_connectionADestructive
Remove uma conexão do registro (fecha o pool e, se veio do arquivo, apaga do arquivo de configuração). Conexões definidas por variável de ambiente (.mcp.json) só saem desta sessão.
Inputs: connection (required). Returns: result
use_connectionARead-only
Define a conexão ativa da sessão (usada quando 'connection' é omitido) e valida que ela abre.
Inputs: connection (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 17 tools
Most tools target clearly distinct operations: connection lifecycle, schema/object introspection, query execution, health analysis, and index recommendations. A few boundaries are slightly subtle, especially use_connection vs. open_connection and the three query/index analysis tools, but descriptions provide enough distinction.
All tool names use consistent snake_case with predictable verb_noun phrasing, such as list_connections, add_connection, execute_sql, and analyze_db_health. The pattern is stable across SQL, MongoDB, connection, and analysis tools.
Seventeen tools is slightly heavy but reasonable for a multi-database server covering connection management, introspection, query execution, health checks, and index analysis. Each tool appears to serve a meaningful role rather than duplicating another.
The surface covers the core lifecycle: add/remove/open/close/use/reload connections, list schemas and objects, inspect details, execute SQL and MongoDB operations, explain queries, analyze health, and recommend indexes. Minor gaps exist, such as no dedicated MongoDB explain or broader transaction/administration tooling, but agents can work around them.
Related MCP Connectors
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Hosted PostgreSQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Related MCP Servers
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.1-
- AlicenseAqualityCmaintenanceEnables AI assistants to query PostgreSQL databases, inspect schemas, and retrieve complete DDL with built-in read-only protection. It supports multiple database connections and allows for secure database interaction and exploration via the Model Context Protocol.524 npm1MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with PostgreSQL databases through natural language queries, schema inspection, and safe SQL execution.1ISC
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely interact with PostgreSQL databases, perform queries, inspect schemas, and analyze query performance.2ISC