db-query-mcp
A read-mostly MCP server for running SQL against your registered MySQL/MariaDB/PostgreSQL connections, with credentials hidden from the AI and destructive statements gated behind user approval.
List connections — see registered DB connections (number + alias) so you can pick one; host/password stay hidden.
Run read-only queries — execute SELECT/SHOW/DESC/EXPLAIN and get results back; anything that modifies data is rejected.
Run write queries — execute INSERT/UPDATE/DELETE/DDL (requires your approval first, and is hard-blocked on connections marked read-only).
Test a connection — verify a connection number actually works (SELECT 1) without exposing credentials or data.
Get recent queries — retrieve the last 10 executed queries (select/write) in newest-first order, without results or connection details.
Get management commands — receive the exact terminal commands for tasks the AI can't do itself (add connection, edit credentials, rename alias, delete connection).
In short: it lets you query and modify databases through Claude while keeping connection secrets out of the model's reach and forcing explicit consent for any data-changing statement.
Provides tools for executing SQL queries (SELECT, SHOW, DESC, EXPLAIN, DML, DDL) on MariaDB databases, with security features like connection info hiding, read-only connections, and query logging.
Provides tools for executing SQL queries (SELECT, SHOW, DESC, EXPLAIN, DML, DDL) on MySQL databases, with security features like connection info hiding, read-only connections, and query logging.
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., "@db-query-mcp List tables in the development 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.
db-query-mcp
Claude Code(또는 다른 AI)에서 사용하는 자체 제작 DB 쿼리 실행 MCP 서버 (MySQL / MariaDB / PostgreSQL).
설계 원칙 (보안)
host·port·password는 AI에게 절대 노출되지 않는다.
db-connection-env는 MCP 서버 프로세스 내부에서만 읽는다.AI가 볼 수 있는 것은 번호 + 별칭 + DB 종류 + DB 사용자명(user) + 읽기 전용 여부뿐이다. 어떤 연결로 실행했는지 사용자가 확인할 수 있도록 쿼리 결과 맨 앞에 아래 헤더가 붙는다.
[연결] 1. 로컬 개발 DB (MySQL, user: devuser) [연결] 2. 운영 DB (PostgreSQL, user: readonly_user) [읽기 전용]
수정 권한을 AI와 사용자로 나눈다.
항목
사용자(터미널)
AI(MCP 도구)
연결 추가, DB 종류·host·port·database·ssl·readonly
setup✗
user, password
edit✗
별칭
edit/renamerename_connection번호
editrenumber_connection접속 정보를 만들거나 바꾸는 기능은 MCP 도구로 노출하지 않는다.
번호를 바꿀 때 새 번호가 이미 쓰이고 있으면, 사용자가 허용한 경우에만 기존 연결을 맨 뒤 번호로 옮긴다.
DML/DDL은 사용자 승인 후에만 실행된다.
읽기 쿼리(
run_select_query)와 변경 쿼리(run_write_query)를 별도 도구로 분리.Claude Code 권한 설정에서
run_write_query를ask로 두면 실행 직전 화면에서 직접 승인.
다중 문장 실행 차단(
SELECT 1; DROP ...불가), 결과 최대 50행, SELECT 타임아웃 90/120/150초(최대 3회 재시도)·WRITE 150초(단일 시도).읽기 쿼리는 이중으로 막는다.
1차: 쿼리 판정(
src/sqlguard.ts). 주석을 지우고 문자열 내용을 비운 뒤 판정하므로, 문자열 속--나 주석으로 뒤쪽 SQL을 숨길 수 없다.MySQL:
SELECT ... INTO OUTFILE/DUMPFILE(DB 서버에 파일 쓰기)은 읽기가 아니다.PostgreSQL:
SELECT ... INTO 새테이블(테이블 생성),COPY는 읽기가 아니다.공통:
WITH·EXPLAIN에 변경 키워드가 섞이면 읽기가 아니다(EXPLAIN ANALYZE DELETE ...는 실제로 실행되므로).
2차: 읽기로 판정된 쿼리는 읽기 전용 트랜잭션(
START TRANSACTION READ ONLY/BEGIN READ ONLY) 안에서 실행하고 ROLLBACK한다. 판정을 빠져나간 변경(nextval(),SELECT ... FOR UPDATE등)도 DB가 거부한다.readonly차단은 도구가 아니라 실행 계층에서 강제되어 어떤 경로로도 우회되지 않는다.
Related MCP server: DB Agent MCP Server
설정 파일 (~/.db-query-mcp/)
# db-connection-list (번호=별칭)
1=로컬 개발 DB
2=운영 DB
# db-connection-env (번호.key=value)
1.type=mysql # mysql(MariaDB 포함) / postgres. 생략하면 mysql (예전 설정 그대로 동작)
1.host=localhost
1.port=3306
1.user=devuser
1.password=****
1.database=mg_service
# 선택 옵션
2.type=postgres # port 생략 시 5432 (mysql은 3306)
2.host=10.0.0.5
2.user=readonly_user
2.password=****
2.ssl=true # true=인증서 검증, skip-verify=자체서명 허용, 생략=TLS 미사용
2.readonly=true # true면 변경 쿼리(run_write_query)를 서버가 강제 차단
type·ssl·readonly는setup실행 시 질문으로 입력받아 자동 기록된다. DB 종류는 번호로 고른다:1) MySQL / MariaDB(기본),2) PostgreSQL. 고른 종류에 맞춰 port 기본값(3306 / 5432)이 바뀐다. 파일을 직접 고칠 때type은postgresql·pg·mariadb도 받는다. 모르는 값이면 해당 연결은 쓰지 않고 에러를 낸다.
설치 (Windows / macOS 공통)
GitHub에서 설치 (가장 간단)
이 저장소가 곧 Claude Code 플러그인 마켓플레이스입니다. 실행에 필요한 번들(dist/*.mjs)이 저장소에 포함되어 있어 clone·npm install·빌드 없이 바로 설치됩니다.
1단계 — 마켓플레이스를 등록합니다. Claude Code 세션에서:
/plugin marketplace add mark3lim/db_query_mcp2단계 — 플러그인을 설치합니다.
/plugin install db-query@db-query-marketplace설치 범위(user / project / local)를 물어보면 선택합니다. 범위별 차이는 아래 방법 B의 표와 같습니다.
3단계 — 세션을 새로 시작합니다. stdio MCP 서버의 도구는 세션 시작 시 인식됩니다.
4단계 — 확인합니다.
/mcp # db-query 가 connected 인지, 도구가 보이는지 확인5단계 — DB 접속 정보를 등록합니다. 플러그인 설치는 MCP 도구 등록까지만 합니다. 접속 정보(ID/PW)는 보안상 AI가 만들지 않으므로 터미널에서 직접 한 번 실행해야 합니다.
# 저장소를 받아 setup 실행 (npm install 불필요 — 번들이 포함되어 있음)
git clone https://github.com/mark3lim/db_query_mcp.git
node db_query_mcp/dist/setup.mjs접속 정보는 ~/.db-query-mcp/(홈)에 저장되므로, setup을 실행한 폴더 위치는 상관없습니다. 등록만 끝나면 clone한 폴더는 지워도 플러그인은 정상 동작합니다. user·password·별칭·번호를 바꾸려면 같은 방식으로 node db_query_mcp/dist/edit.mjs 를 실행하세요. (별칭·번호는 AI에게 요청해도 됩니다)
업데이트 / 제거
/plugin update db-query@db-query-marketplace
/plugin uninstall db-query@db-query-marketplace/plugin으로 설치 — 로컬 파일만 사용 (클라우드/깃 불필요)
이 폴더 자체가 Claude Code 플러그인입니다. 의존성을 단일 파일(dist/bundle.mjs)로 번들해 두어 npm install/빌드 없이 바로 동작합니다. 아래 두 방법 모두 로컬 폴더만 쓰며, 외부에 올릴 필요가 없습니다.
방법 A — skills 폴더에 넣기 (설치 명령조차 없음, 가장 간단)
압축 푼 폴더를 통째로 아래 위치에 두기만 하면 됩니다. 마켓플레이스 등록도, 설치 명령도 필요 없고, 그 자리에서 그대로 로드됩니다(캐시 복사 안 함).
~/.claude/skills/db-query/이 폴더 안에 .claude-plugin/plugin.json 과 .mcp.json 이 있으면 됩니다(압축에 포함되어 있음). 폴더를 넣은 뒤:
Claude Code를 재시작(또는 새 세션 시작)합니다.
/mcp로db-query서버가 connected 인지, 도구(list_connections등)가 보이는지 확인합니다.DB 접속 정보를 한 번 등록합니다(아래 "접속 정보 등록" 참고).
이 방식은 항상
~/.claude/skills/에 둔 그 폴더를 직접 실행합니다. 폴더를 옮기거나 지우면 동작이 멈춥니다.
방법 B — /plugin install (로컬 마켓플레이스 등록)
/plugin install을 쓰고 싶다면, 깃 없이 로컬 폴더 경로로 마켓플레이스를 등록하면 됩니다.
1단계 — 폴더를 고정 위치에 둡니다. 예: ~/tools/db-query. (마켓플레이스 등록·업데이트의 출처가 되므로 옮기거나 지우지 마세요.)
2단계 — 로컬 경로로 마켓플레이스를 등록합니다. git URL이 아니라 폴더 절대경로를 줍니다.
/plugin marketplace add /절대경로/db-query대화형으로 하려면
/plugin→Marketplaces탭 →+ Add Marketplace에서 로컬 폴더 경로를 입력해도 됩니다.
3단계 — 플러그인을 설치합니다. (마켓플레이스 이름 db-query-marketplace, 플러그인 이름 db-query)
/plugin install db-query@db-query-marketplace4단계 — 설치 범위를 선택합니다. 설치 시 Claude Code가 범위를 물어봅니다.
범위 | 적용 대상 | 저장 위치 |
user | 내 모든 프로젝트 |
|
project | 이 프로젝트(레포로 공유) |
|
local | 이 프로젝트의 나만(gitignore) |
|
5단계 — 세션을 새로 시작합니다. stdio MCP 서버의 도구는 세션 시작 시 인식됩니다. 세션 도중 설치했다면 재시작(또는 /reload-plugins)하세요.
6단계 — 확인합니다.
/plugin # Installed 탭에서 db-query 가 enabled 인지 확인
/mcp # db-query 서버가 connected 인지, 도구가 보이는지 확인도구가 0개로 나오면 5단계(세션 재시작)를 다시 하세요.
참고:
/plugin install로 설치하면 플러그인이~/.claude/plugins/cache/로 복사되어 실행됩니다. 번들이 폴더 안에 self-contained 라 복사돼도 정상 동작합니다. 다만 업데이트(/plugin update)를 위해 원본 폴더는 그대로 두는 게 좋습니다. 복사가 싫고 "그 자리 실행"을 원하면 방법 A를 쓰세요.
관리 명령(참고)
/plugin list # 설치된 플러그인 목록
/plugin update db-query@db-query-marketplace # 업데이트
/plugin uninstall db-query@db-query-marketplace # 제거
/plugin marketplace remove db-query-marketplace # 마켓플레이스 제거접속 정보 등록 (두 방법 공통, 한 번만)
플러그인 설치는 MCP 도구 등록까지만 합니다. DB 접속 정보(ID/PW)는 보안상 AI가 만들지 않으므로, 터미널에서 한 번 직접 등록하세요. setup.js는 외부 라이브러리 없이 Node 기본 기능만 쓰므로 npm install 없이 바로 실행됩니다. 접속 정보는 ~/.db-query-mcp/ (홈)에 저장되어 폴더 위치와 무관합니다.
# 방법 A(skills 폴더)
node ~/.claude/skills/db-query/dist/setup.mjs
# 방법 B(고정 위치)
node /절대경로/db-query/dist/setup.mjsuser·password·별칭·번호를 바꾸려면 같은 폴더에서 node dist/edit.mjs 를 실행하세요.
압축을 푼 폴더에서 아래를 실행하면 라이브러리 설치 + 빌드가 자동으로 끝나고, 다음 단계 명령이 화면에 안내됩니다.
# macOS / Linux
bash install.sh
# Windows: 탐색기에서 install.bat 더블클릭, 또는
install.bat실행하면 등록 범위(user / project / local)를 물어보고, 선택한 범위로 claude mcp add까지 자동 실행합니다(claude CLI가 PATH에 있을 때). project/local은 실행한 폴더 기준으로 등록되니, 본인 프로젝트 폴더에서 실행하세요.
수동 설치 (단계별)
# 1. 의존성 설치 및 빌드
cd db-query-mcp
npm install
npm run build
# 2. DB 연결 등록 (대화형 — 반드시 사용자가 직접 실행)
npm run setup
# 3. Claude Code에 등록 (절대 경로 사용, --scope로 범위 선택)
# --scope user : 모든 프로젝트 (기본)
# --scope project : 이 프로젝트만 (.mcp.json, 팀 공유)
# --scope local : 이 프로젝트 개인용 (gitignore)
# macOS/Linux
claude mcp add --scope user --transport stdio db-query -- node /절대경로/db-query-mcp/dist/index.js
# Windows (PowerShell)
claude mcp add --scope user --transport stdio db-query -- node C:\절대경로\db-query-mcp\dist\index.js
# 4. 등록 확인
claude mcp list권한 설정 (DML/DDL 사용자 확인)
~/.claude/settings.json 또는 프로젝트의 .claude/settings.json:
{
"permissions": {
"allow": [
"mcp__db-query__list_connections",
"mcp__db-query__run_select_query"
],
"ask": [
"mcp__db-query__run_write_query",
"mcp__db-query__rename_connection",
"mcp__db-query__renumber_connection"
]
}
}SELECT 계열은 자동 실행 → 생산성 확보
INSERT/UPDATE/DELETE/DDL은 매번 화면에서 사용자가 직접 승인 → 안전성 확보
별칭·번호 변경도 설정 파일을 바꾸므로
ask를 권장
제공 도구
도구 | 설명 |
| 번호+별칭+DB 사용자명+읽기 전용 여부 목록 조회 (host/password 비노출) |
| 읽기 쿼리(SELECT/SHOW/EXPLAIN/TABLE/VALUES, MySQL은 DESC 포함, |
| DML/DDL 실행. read-only 연결은 서버가 차단, 그 외에도 권한 설정(ask)으로 화면 승인 권장 |
| 접속 가능 여부만 확인(SELECT 1). 데이터·host·password 비노출 |
| 최근 실행 쿼리(select/write) 최대 10개를 최신순으로 반환 |
| 별칭 변경. 접속 정보는 건드리지 않음 |
| 번호 변경. 새 번호가 이미 있으면 바꾸지 않고 |
| AI가 직접 못 하는 관리 작업(연결 추가·삭제, user/password 등 변경)의 실행 명령어를 정확한 경로와 함께 안내 |
run_select_query·run_write_query·test_connection의 결과는 항상[연결] 번호. 별칭 (user: …)헤더로 시작한다.
get_management_commands는 사용자가 "DB 추가해줘", "비밀번호 바꿔줘"처럼 AI가 보안상 수행할 수 없는 작업을 요청할 때, AI가 호출해서 실제 프로젝트 경로가 들어간 명령어를 사용자에게 안내하는 용도입니다. 직접 작업을 수행하지는 않습니다.
보안·안정성 처리
에러 마스킹: DB 에러 메시지의 host/port/user는
***로 가려진다. (DB 사용자명은 결과 헤더에만 표기된다)read-only 연결:
N.readonly=true인 연결은 권한 설정과 무관하게 서버가 변경 쿼리를 차단한다.대용량 SELECT: MySQL은 스트리밍, PostgreSQL은 커서로 최대 51행만 읽어 OOM을 방지한다.
SELECT 타임아웃·재시도: 90초 → 120초 → 150초로 최대 3번 시도한다. 시간 초과일 때만 더 긴 타임아웃으로 재시도하며(SQL 에러는 즉시 반환), 3번 모두 초과하면 사용자에게 알린다. PostgreSQL은 트랜잭션 안에서
SET LOCAL statement_timeout으로 서버가 쿼리를 취소하고, 서버가 끊지 못하면 제한시간 + 2초 뒤 클라이언트가 연결을 끊는다. (statement_timeout을 접속 파라미터로 보내지 않아 PgBouncer를 거쳐도 동작한다)WRITE 타임아웃: 단일 시도(150초). 타임아웃 후 자동 재시도는 중복 적용(이중 INSERT/UPDATE) 위험이 있어 하지 않는다. PostgreSQL에서 클라이언트가 연결을 끊은 경우에는 반영 여부를 알 수 없으니 SELECT로 먼저 확인하라고 안내한다.
PostgreSQL RETURNING:
UPDATE ... RETURNING등으로 돌아온 행은 최대 50행까지 결과에 함께 표시한다.타입 직렬화: BIGINT·int8·numeric은 문자열로, BLOB·bytea는
<BLOB n bytes>로, 날짜·시간은 DB가 준 문자열 그대로(UTC 변환 없이) 표기한다.TLS:
N.ssl=true(검증) /skip-verify(자체서명 허용)로 원격 DB 암호화 연결을 지원한다.쿼리 로그: 최근 10개(시각·연결번호·종류·성공여부·쿼리문)를
~/.db-query-mcp/query-log.json(권한 600)에 보관한다. 쿼리 결과와 접속 정보는 저장하지 않는다.
사용자: notification 테이블 최근 10건 조회해줘
AI: list_connections 호출 → "1. 로컬 개발 DB (MySQL, user: devuser) / 2. 운영 DB (PostgreSQL, user: readonly_user) [읽기 전용] 중 어디에 연결할까요?"
사용자: 1번
AI: run_select_query("1", "SELECT * FROM notification ORDER BY id DESC LIMIT 10")
→ "[연결] 1. 로컬 개발 DB (MySQL, user: devuser)" 헤더와 함께 결과 표시연결 추가/수정
작업 | 누가 | 방법 |
연결 추가, DB 종류·host·port·database·ssl·readonly 변경 | 사용자 |
|
user·password 변경 | 사용자 |
|
별칭 변경 | 사용자 또는 AI |
|
번호 변경 | 사용자 또는 AI |
|
삭제 | 사용자 | 두 파일에서 해당 번호 줄을 직접 지운다 |
번호 변경 규칙
접속 정보(
db-connection-env)의N.접두어도 함께 바뀌어, 연결 정보가 새 번호로 그대로 옮겨진다.새 번호가 비어 있으면 바로 바뀐다. 이전 번호는 비게 된다.
새 번호가 이미 쓰이고 있으면 먼저 사용자에게 묻는다. 허용하면 기존 연결을 맨 뒤 번호로 옮긴 뒤 바꾸고, 거절하면 아무것도 바꾸지 않는다.
맨 뒤 번호 = 이전 번호를 비운 뒤 남는 번호(새 번호 포함) 중 최댓값 + 1
예)
1, 2, 3에서 3→1: 기존 1은 3번이 된다 →1(기존3), 2, 3(기존1)예)
1, 2, 3에서 1→3: 기존 3은 4번이 된다 →2, 3(기존1), 4(기존3)
AI는
renumber_connection을 먼저 확인 없이 호출하고,[확인 필요]를 받으면 사용자에게 물어본 뒤 허용받았을 때만move_existing_to_end=true로 다시 호출한다.
user·password를 바꾸는
setup·edit는 터미널에서 사용자가 직접 실행하며 MCP 도구로 노출되지 않는다. 따라서 비밀번호가 AI/서버 통신 경로에 오르지 않는다.
Available Tools
6 toolsget_management_commandsA
사용자가 DB 연결을 추가/삭제하거나, 접속 정보(ID·PW·host 등)를 변경하거나, 별칭을 수정하려고 할 때 호출한다. 이런 작업은 보안상 AI(MCP)가 직접 수행할 수 없고 사용자가 터미널에서 직접 실행해야 한다. 이 도구가 반환한 명령어를 사용자에게 그대로 안내하라. 임의로 명령어를 지어내지 말 것.
Inputs: task.
get_recent_queriesA
최근 실행한 쿼리(select/write) 최대 10개를 최신순으로 반환한다. 사용자가 '방금/최근에 무슨 쿼리 실행했어?'처럼 물으면 호출한다. 쿼리 결과나 접속 정보는 보관/반환하지 않는다.
Inputs: no named parameters.
list_connectionsA
등록된 DB 연결 목록(번호와 별칭)을 조회한다. 어떤 DB를 쓸지 모호하면 이 목록을 사용자에게 보여주고 번호를 선택받는다.
Inputs: no named parameters.
run_select_queryA
읽기 전용 쿼리(SELECT, SHOW, DESC, EXPLAIN)를 실행하고 결과를 반환한다. 데이터를 변경하는 쿼리는 거부된다.
Inputs: query (required), connection_no (required).
run_write_queryA
데이터를 변경하는 쿼리(INSERT/UPDATE/DELETE/DDL 등)를 실행한다. 반드시 실행 전에 사용자에게 쿼리 내용을 보여주고 승인을 받아야 하며, Claude Code 권한 설정(ask)에 의해 실행 직전 화면에서 한 번 더 확인된다. 읽기 전용(read-only)으로 등록된 연결에서는 서버가 강제로 거부한다.
Inputs: query (required), connection_no (required).
test_connectionA
지정한 번호의 DB에 실제로 접속되는지 확인한다(SELECT 1). 접속 정보나 데이터는 노출하지 않고 성공/실패만 반환한다.
Inputs: connection_no (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Each tool has a distinctly different purpose: listing connections, testing connections, running read-only queries, running write queries, fetching management commands, and retrieving recent queries. There is no meaningful overlap that would confuse an agent's tool selection.
All tool names follow a consistent snake_case verb_noun pattern (list_connections, run_select_query, test_connection, run_write_query, get_management_commands, get_recent_queries). The naming clearly signals the action and target of each tool.
Six tools is well-scoped for a DB query MCP server. Each tool covers a necessary part of the workflow—connection discovery, connectivity checks, read/write query execution, management guidance, and query history—without unnecessary bloat.
The tool surface covers the core DB interaction lifecycle: list connections, test availability, run read queries, run write queries, and review recent queries. Connection management is intentionally delegated to terminal commands, and the provided tool properly guides users through that process, so there are no obvious dead ends.
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Work with your database from AI tools: ask, export, approved changes, and scheduled jobs.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely query MySQL databases with read-only access by default, supporting table listing, structure inspection, and SQL queries with optional write operation control.13 npmMIT
- FlicenseNot gradedqualityDmaintenanceEnables secure interaction with MySQL databases through SQL queries, supporting read-only operations without approval and write operations with user confirmation.-
- AlicenseAqualityDmaintenanceEnables AI assistants to safely query MySQL databases with read-only access, featuring SQL injection protection, connection pooling, and automatic query limits for secure database exploration.4MIT
- AlicenseBqualityDmaintenanceEnables AI assistants to securely interact with MariaDB and MySQL databases using granular per-connection read/write permissions and transaction support. It allows users to manage multiple database connections, explore schemas, and execute controlled SQL queries through a standardized interface.617 npm5MIT