database-mcp
database-mcp is an MCP server that lets AI models run SQL against PostgreSQL databases with true server-side result paging, runtime-managed connection profiles, SSH tunneling, and a wide set of schema/query introspection tools.
Query with paging:
queryreturns the first page as compact JSON;fetchcontinues from a held server-side cursor without re-execution;closefrees cursors early.Run multi-statement scripts:
scriptexecutes several SQL statements in one transaction and returns all result sets.Explore schemas:
tables,describe,overview,search_objects,relations, andjoin_pathfind tables, columns, comments, foreign keys, and join paths.Analyze performance:
explainshows query plans (optionally withanalyze),countgives quick row estimates or exact counts,profileexposes column statistics frompg_statswithout scanning tables.Get sample data:
sampleusesTABLESAMPLEfor genuinely random rows.Export data:
exportstreams full result sets to local CSV/JSONL files with zero context cost.Manage connections at runtime:
profiles,profile_add,profile_remove, andprofile_testlet the AI add/update/remove/test named connection profiles without restarting.Connect via SSH: profiles can tunnel through SSH to databases only reachable on a remote host.
Monitor the server:
statusshows profiles, pools, open cursors, and limits;logsinspects the query log.
Provides tools for interacting with PostgreSQL databases, including executing SQL queries with server-side paging, managing connection profiles, exploring schema (tables, columns, indexes), generating query plans, and more.
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., "@database-mcp give me an overview of the database schema"
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.
database-mcp
SQL database MCP server with true server-side result paging — the feature no established database MCP server has (DBHub caps rows, Google's MCP Toolbox returns everything, mcp-alchemy truncates at 4000 chars).
PostgreSQL reference implementation.
Why
Every existing SQL MCP server either truncates large results or dumps them
whole into the model's context. The MCP spec only paginates list operations
(tools/list), not tool results. database-mcp closes that gap:
A query runs once as a PostgreSQL server-side cursor (
DECLARE/FETCH FORWARD) inside a held transaction.Each
fetch(cursor)continues exactly where the last page ended — no re-execution, noOFFSETre-scan, and the MVCC snapshot keeps the result stable even under concurrent writes.Pages are bounded by rows (
page_size) and rendered bytes (max_page_bytes); oversized cells are truncated with an explicit marker.Held cursors are bounded: max N concurrent (LRU eviction), TTL idle eviction, plus
idle_in_transaction_session_timeoutas a server-side backstop. Exhausted cursors auto-close.
Related MCP server: pgsql-mcp
Connection profiles — managed by the AI at runtime
Connections are named profiles, persisted in
~/.config/database-mcp/profiles.json (chmod 600). The AI can add, change,
test, and remove them on the fly via tools — no server restart:
profile_add(name, dsn, allow_writes=false, description, make_default, test=true)profile_remove(name)·profile_test(name)·profiles()every query tool takes an optional
profileparameter; the default profile is used when omitted.
Profiles are write-enabled by default. For production databases create
the profile with allow_writes=false — that enforces read-only at the
session level (default_transaction_read_only), so no statement can write
regardless of what the model sends. The CLI --dsn profile follows the same
default; pass --read-only to register it read-only.
SSH bridging
A profile can reach a database that is only accessible via SSH (the classic "Postgres listens on localhost of a remote host" setup):
profile_add(name="prod", dsn="postgresql://app@dbhost:5432/app",
ssh_host="dbhost")The tunnel is a system-
sshsubprocess (-N -L, BatchMode, keepalives) — your~/.ssh/config, keys, and agent apply unchanged. Auth must work non-interactively.ssh_remote_host/ssh_remote_portdefault to the DSN's host/port as seen from the SSH host; if the DSN host equals the SSH host it defaults to127.0.0.1(the usual case).Tunnels start lazily, are health-checked on every use, and are rebuilt automatically. If a tunnel dies mid-pagination, its cursors are invalidated with a clear error and the next query reconnects.
Multiplexing (
ControlMaster) is explicitly disabled for tunnel connections so the tunnel's lifetime is exactly the subprocess's lifetime.
Tools
Tool | Purpose |
| Execute SQL, get first page + |
| Next page from a held cursor — no re-execution |
| Close one/all cursors early |
| List tables/views with row estimates and sizes |
| Columns, constraints, indexes of one table |
| Query plan (optionally |
| Multi-statement SQL in one transaction — every result set back, labeled by preceding comments |
| Stream a full result set to a local csv/jsonl file via server-side cursor — any size, zero context cost |
| Orientation card: every table + row estimate + column names in one call |
| Find tables/columns/functions by name or comment |
| Column statistics from |
| Foreign keys of a table, both directions |
| Shortest FK path between two tables as a ready JOIN chain |
| Instant planner estimate (optional |
| Genuinely random rows via |
| Runtime connection management |
| Profiles, pools, open cursors, limits |
Results are compact JSON — columns once, rows as arrays — roughly half the
tokens of the row-dict format other servers emit. query also returns
estimated_rows (planner estimate via EXPLAIN) so the model knows what it
is paging into.
Install & run
uv pip install -e .
database-mcp --dsn postgresql://user@host:5432/db # registers profile "default"
database-mcp # start empty, add profiles at runtimeClaude Code registration:
claude mcp add database -- database-mcp --dsn postgresql://user@host:5432/dbOptions: --profiles FILE, --allow-writes, --page-size 50,
--max-page-size 500, --max-page-bytes 32000, --max-cell 400,
--cursor-ttl 300, --max-cursors 4, --statement-timeout 30,
--keepalive 120, --connect-timeout 5.
Env: DATABASE_MCP_DSN / DATABASE_URL, DATABASE_MCP_PROFILES.
Staleness handling
Dead connections are detected fast at every layer instead of hanging:
SSH tunnels:
ServerAliveInterval=--keepalive(default 2 min) withServerAliveCountMax=1— one missed probe ends the tunnel process, which the engine manager detects on next use and rebuilds lazily.DB connections: TCP keepalives (
keepalives_idle=--keepalive, probes every 10 s, 3 misses) catch dead peers in ~30 s — including pinned cursor connections outside the pool.Pool checkout check: every connection handed out is validated with a cheap round-trip; a stale one is discarded and replaced transparently — the caller never sees the error. Idle pooled connections are recycled after
--keepaliveseconds; connection attempts fail after--connect-timeout(default 5 s) instead of the ~2 min TCP default.
Multi-session: the HTTP bridge
By default the server speaks stdio (one process per MCP client). For several concurrent Claude sessions run it as a shared bridge daemon instead:
database-mcp --http --port 4270 # one daemon serves ALL sessions
claude mcp add --transport http database http://127.0.0.1:4270/mcp -s userOne process means genuinely shared state: profiles added in one session are
instantly visible in every other, connection pools and SSH tunnels exist
once instead of per session, held cursors survive a client reconnect (within
TTL), and the query log has a single writer. On macOS a LaunchAgent with
KeepAlive makes the bridge permanent.
stdio mode stays multi-session aware on a smaller scale: the profiles file is watched (mtime) and reloaded when another session changes it — but pools, tunnels, and cursors remain per-process there.
Query log
Every tool call is logged as one JSON line to a daily file
(~/.local/state/database-mcp/log/query-YYYYMMDD.jsonl): timestamp, tool,
profile, duration in ms, row counts, truncated SQL (2000 chars),
error/sqlstate. Profile DSNs are never logged. Inspect recent entries with
the logs tool (filter by tool/profile/since); for bigger analyses point
duckdb/jq/pandas at the files:
-- duckdb: p95 query time per profile, last 14 days
select profile, count(*) n, round(quantile_cont(ms, 0.95)) p95_ms
from read_json_auto('~/.local/state/database-mcp/log/query-*.jsonl')
where tool in ('query','fetch','script') group by 1 order by p95_ms desc;Retention is bounded by design: daily rotation, files older than
--log-days (default 14) are deleted at startup and on every rollover;
--log-days 0 disables logging, --log-dir moves it.
Tests
uv pip install -e '.[dev]'
pytest # needs a local PostgreSQL (DBMCP_TEST_DSN to override)License
MIT
Available Tools
18 toolscloseA
Close an open cursor (or all cursors when no token is given) to free its connection early.
Inputs: cursor. Returns: result
countA
Row count, estimate-first: instant planner estimate (no scan), optionally with a WHERE clause; exact=true runs a real count(*) under the statement timeout. Prefer the estimate.
Inputs: table (required), exact, where, profile. Returns: result
describeA
Describe one table: columns with types/nullability/defaults, constraints (PK/FK/unique/check), and indexes.
Inputs: table (required), profile. Returns: result
explainA
Show the query plan (EXPLAIN). Set analyze=true to actually run the statement and get real timings.
Inputs: sql (required), params, analyze, profile. Returns: result
fetchA
Fetch the next page from an open cursor returned by query. No re-execution: rows continue exactly where the last page ended. The cursor auto-closes when exhausted (has_more=false).
Inputs: cursor (required), page_size. Returns: result
join_pathB
Shortest foreign-key path between two tables, rendered as a ready-to-use JOIN chain (up to 3 equally short paths). Use this instead of guessing joins on unfamiliar schemas.
Inputs: to_table (required), from_table (required), profile, max_hops. Returns: result
overviewA
Orientation card for an unknown database: every table with row estimate and its column names in ONE compact call — use this before tables/describe round-trips. Optional table-name filter.
Inputs: filter, profile. Returns: result
profileA
Column statistics from pg_stats WITHOUT touching the table: null fraction, distinct count (negative = fraction of rows, -1 = unique), most common values with frequencies, histogram bounds, physical correlation. Replaces exploratory SELECT DISTINCT / GROUP BY scans.
Inputs: table (required), profile. Returns: result
profile_addA
Add or update a named connection profile at runtime and persist it. Tests the connection first (set test=false to skip). Profiles are read-only unless allow_writes=true. make_default=true switches the default profile. For a database only reachable via SSH, set ssh_host (an ssh destination or ~/.ssh/config alias; BatchMode, so keys/agent must work non-interactively) — a tunnel is opened automatically and kept alive; ssh_remote_host/ssh_remote_port default to the DSN's host/port as seen FROM the ssh host (usually 127.0.0.1:5432).
Inputs: dsn (required), name (required), test, ssh_host, +5 more. Returns: result
profile_removeB
Remove a connection profile (open cursors on it are closed).
Inputs: name (required). Returns: result
profilesA
List all connection profiles (DSNs password-redacted) and which one is the default.
Inputs: no named parameters. Returns: result
profile_testA
Test connectivity of a profile (default profile when omitted): server version and connect latency.
Inputs: name. Returns: result
queryA
Execute SQL on a profile (default profile when omitted). Returns the first page as compact {"columns":[...],"rows":[[...],...],"page":{"returned","has_more","estimated_rows","cursor"}}. When has_more is true, pass page.cursor to the fetch tool — the query is NOT re-executed; a server-side cursor is held open (stable snapshot). Placeholders: %s positional with the params array.
Inputs: sql (required), params, profile, page_size. Returns: result
relationsA
Foreign keys of one table, both directions: what it references and what references it.
Inputs: table (required), profile. Returns: result
sampleA
A few genuinely random rows from a table (TABLESAMPLE on big tables — no scan, no physically-adjacent LIMIT bias).
Inputs: table (required), n, profile. Returns: result
search_objectsB
Find tables, columns, and functions by name OR by comment (pg_description — often the only documentation a schema has). Answers 'where is the customer email?' in one call.
Inputs: term (required), limit, profile. Returns: result
statusA
Server status: profiles with pool statistics, open cursors, configured limits, profiles file location.
Inputs: no named parameters. Returns: result
tablesA
List tables/views/matviews with estimated row counts and sizes (system schemas excluded). Optional name filter.
Inputs: filter, profile. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 18 tools
Each tool targets a distinct concern: cursor-paginated queries (query/fetch/close), schema exploration (tables/describe/overview/search_objects), statistical analysis (profile/count/sample/relations/join_path), explain plans, and connection profile management (profiles/profile_add/profile_remove/profile_test). No overlapping responsibilities that would cause an agent to misselect.
Tool names are mostly snake_case verbs or nouns that clearly map to actions (query, fetch, describe, count) or objects (tables, profiles). The profile_add/profile_remove/profile_test trio uses a consistent prefix. The only minor inconsistency is mixing singular nouns like 'profile' with plural 'profiles' and standalone verbs, but this does not impair predictability.
At 18 tools, the set is slightly heavy but each tool earns its place—covering query execution, pagination, schema discovery, row sampling, join pathing, explain, column statistics, and connection management. It leans toward the upper bound of reasonable scope for a database MCP server, but avoids bloat.
The tool surface covers the full read-side lifecycle: discover schema (overview, tables, describe, search_objects), analyze data (profile, count, sample, relations, join_path), execute and paginate queries (query, fetch, close), inspect performance (explain), and manage connections (profiles, profile_add/remove/test, status). No critical operations are missing for the intended read/diagnostics purpose.
Maintenance
Related MCP Connectors
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Connect to PlanetScale databases, branches, schema, query insights, and execute SQL
Managed Postgres MCP: projects, SQL, docs search, and storage buckets via OAuth.
Related MCP Servers
- AlicenseBqualityDmaintenanceEnables comprehensive PostgreSQL database management including index tuning, query plan analysis, health monitoring, schema-aware SQL generation, and safe SQL execution with configurable access control for both development and production environments.9MIT
- AlicenseBqualityDmaintenanceEnables interaction with PostgreSQL databases through comprehensive database management tools including index tuning, query execution plans, health checks, schema intelligence, and safe SQL execution with configurable read-only mode for production use.35MIT
- FlicenseNot gradedqualityDmaintenanceEnables querying PostgreSQL databases via MCP, with multi-database routing, credential isolation, and truncated results plus full CSV export.-
- FlicenseNot gradedqualityDmaintenanceEnables secure, direct access to PostgreSQL databases for queries, modifications, and schema exploration.-