database-mcp
database-mcp
SQL 데이터베이스 MCP 서버로, 진정한 서버 측 결과 페이징을 지원합니다 — 기존의 어떤 데이터베이스 MCP 서버도 갖추지 못한 기능입니다 (DBHub는 행 수를 제한하고, Google의 MCP Toolbox는 모든 것을 반환하며, mcp-alchemy는 4000자에서 잘라냅니다).
PostgreSQL 참조 구현입니다.
왜 필요한가
기존의 모든 SQL MCP 서버는 대용량 결과를 잘라내거나 전체를 모델의 컨텍스트에 던져 넣습니다. MCP 사양은 목록 연산(tools/list)만 페이징할 뿐, 도구 결과는 페이징하지 않습니다. database-mcp가 그 격차를 메웁니다:
쿼리는 보류된 트랜잭션 내에서 PostgreSQL 서버 측 커서(
DECLARE/FETCH FORWARD)로 한 번만 실행됩니다.각
fetch(cursor)는 마지막 페이지가 끝난 정확히 그 지점에서 계속됩니다 — 재실행 없음,OFFSET재스캔 없음, MVCC 스냅샷이 동시 쓰기 상황에서도 결과를 안정적으로 유지합니다.페이지는 행 수(
page_size) 그리고 렌더링된 바이트(max_page_bytes)로 제한됩니다. 크기가 큰 셀은 명시적 표시와 함께 잘립니다.보류된 커서는 제한됩니다: 최대 N개 동시( LRU 축출), TTL 유휴 축출, 그리고 서버 측 백스톱으로
idle_in_transaction_session_timeout이 있습니다. 소진된 커서는 자동으로 닫힙니다.
Related MCP server: pgsql-mcp
연결 프로필 — 런타임에 AI가 관리
연결은 명명된 프로필로, ~/.config/database-mcp/profiles.json(chmod 600)에 저장됩니다. AI는 도구를 통해 서버 재시작 없이 즉시 프로필을 추가, 변경, 테스트, 제거할 수 있습니다:
profile_add(name, dsn, allow_writes=false, description, make_default, test=true)profile_remove(name)·profile_test(name)·profiles()모든 쿼리 도구는 선택적
profile매개변수를 받습니다. 생략하면 기본 프로필이 사용됩니다.
프로필은 기본적으로 읽기 전용입니다(세션 수준 default_transaction_read_only). 쓰기에는 명시적 allow_writes=true 프로필이 필요합니다.
SSH 브리징
프로필은 SSH로만 접근 가능한 데이터베이스에 도달할 수 있습니다(전형적인 "Postgres가 원격 호스트의 localhost에서 수신 대기" 설정):
profile_add(name="prod", dsn="postgresql://app@dbhost:5432/app",
ssh_host="dbhost")터널은 시스템
ssh하위 프로세스입니다(-N -L, BatchMode, keepalives) —~/.ssh/config, 키, 에이전트가 변경 없이 적용됩니다. 인증은 비대화형으로 작동해야 합니다.ssh_remote_host/ssh_remote_port는 기본적으로 SSH 호스트 에서 본 DSN의 호스트/포트로 설정됩니다. DSN 호스트가 SSH 호스트와 같으면127.0.0.1로 기본 설정됩니다(일반적인 경우).터널은 지연 시작되며, 사용할 때마다 상태가 점검되고, 자동으로 재구축됩니다. 페이징 중에 터널이 죽으면 해당 커서는 명확한 오류와 함께 무효화되고 다음 쿼리가 재연결됩니다.
멀티플렉싱(
ControlMaster)은 터널 연결에 대해 명시적으로 비활성화되어 터널의 수명이 정확히 하위 프로세스의 수명과 일치합니다.
도구
도구 | 용도 |
| SQL 실행, 첫 페이지 + 더 많은 행이 있을 때 |
| 보류된 커서에서 다음 페이지 — 재실행 없음 |
| 하나/모든 커서를 조기 종료 |
| 행 추정치와 크기가 포함된 테이블/뷰 목록 |
| 한 테이블의 열, 제약 조건, 인덱스 |
| 쿼리 계획(선택적으로 |
| 방향 카드: 한 번의 호출로 모든 테이블 + 행 추정치 + 열 이름 |
| 이름 또는 주석으로 테이블/열/함수 찾기 |
|
|
| 테이블의 외래 키, 양방향 |
| 두 테이블 사이의 최단 FK 경로를 바로 사용 가능한 JOIN 체인으로 |
| 즉시 플래너 추정치(선택적 |
|
|
| 런타임 연결 관리 |
| 프로필, 풀, 열린 커서, 제한 |
결과는 컴팩트 JSON입니다 — 열은 한 번, 행은 배열로 — 다른 서버가 내보내는 행-딕셔너리 형식보다 토큰이 약 절반입니다. query는 또한 estimated_rows( EXPLAIN을 통한 플래너 추정치)를 반환하므로 모델이 무엇을 페이징하고 있는지 알 수 있습니다.
설치 및 실행
uv pip install -e .
database-mcp --dsn postgresql://user@host:5432/db # registers profile "default"
database-mcp # start empty, add profiles at runtimeClaude Code 등록:
claude mcp add database -- database-mcp --dsn postgresql://user@host:5432/db옵션: --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.
환경 변수: DATABASE_MCP_DSN / DATABASE_URL, DATABASE_MCP_PROFILES.
오래된 연결 처리
죽은 연결은 대기하지 않고 모든 계층에서 빠르게 감지됩니다:
SSH 터널:
ServerAliveInterval=--keepalive(기본 2분) 및ServerAliveCountMax=1— 한 번의 놓친 프로브가 터널 프로세스를 종료하고, 엔진 관리자가 다음 사용 시 이를 감지하고 지연 재구축합니다.DB 연결: TCP keepalives(
keepalives_idle=--keepalive, 10초마다 프로브, 3회 실패)가 약 30초 내에 죽은 피어를 감지합니다 — 풀 외부의 고정된 커서 연결도 포함합니다.풀 체크아웃 검사: 모든 연결은 저렴한 왕복으로 검증됩니다. 오래된 연결은 폐기되고 투명하게 교체됩니다 — 호출자는 오류를 볼 수 없습니다. 유휴 풀 연결은
--keepalive초 후 재활용됩니다. 연결 시도는 TCP 기본값 약 2분 대신--connect-timeout(기본 5초) 후 실패합니다.
테스트
uv pip install -e '.[dev]'
pytest # needs a local PostgreSQL (DBMCP_TEST_DSN to override)라이선스
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.
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.-