Skip to main content
Glama
Kenza-21

SQL MCP Server

by Kenza-21

SQL MCP Server

Model Context Protocol 서버로, Postgres 데이터베이스를 여섯 가지 읽기 전용 도구를 통해 LLM 에이전트(Claude Desktop, Claude Code 또는 모든 MCP 클라이언트)에 노출합니다. 에이전트를 이 서버에 연결한 다음 "지난달에 주문을 다섯 건 이상 넣은 고객은 누구인가요?" 같은 질문을 던져 보세요. 에이전트는 아래의 도구를 통해 스키마를 탐색하고 데이터를 직접 질의합니다.

도구

도구

설명

list_tables()

전체 테이블 개요: 이름, 설명, 크기, 열 수

describe_table(table)

한 테이블의 열, 유형, 외래 키 관계

search_schema(keyword)

이름이 키워드와 일치하는 테이블/열 검색

sample_rows(table, limit)

실제 행 미리 보기(기본 5개)

count_rows(table)

테이블의 행 수

execute_select(sql)

임의의 읽기 전용 SELECT / WITH ... SELECT 쿼리 실행

Related MCP server: mcp-data-gateway

왜 이것은 "psycopg2를 감싼 단순한 래퍼"가 아닌가

Text-to-SQL 데모는 흔합니다. 실제로 어려운 부분 — 이 프로젝트가 노력을 쏟는 부분 — 은 임의의 SQL을 생성할 LLM에 execute_select를 안전하게 넘겨주는 것입니다:

  1. 읽기 전용 Postgres 역할. 서버는 SELECT 권한만 부여된 mcp_readonly 역할로 연결합니다(scripts/init_schema.sql 참조). 아래의 애플리케이션 수준 검사에 버그가 있더라도 쓰기를 유발할 수 없습니다.

  2. 세션 수준 읽기 전용 강제. 모든 연결은 SET TRANSACTION READ ONLY를 실행합니다(db.py).

  3. 명령문 검증(security.py): 하나의 SELECT/WITH 문만 허용됩니다. 다중 문장 적층(; DROP TABLE ...)은 허용되지 않으며, SQL 주석(주석 기반 문장 밀반입을 차단)도 허용되지 않습니다. 키워드 블록리스트는 INSERT/UPDATE/DELETE/DDL/GRANT/등을 포함하고, 조용히 테이블을 생성하는 SELECT ... INTO도 포함합니다.

  4. 식별자 검증. describe_table, sample_rows, count_rows는 테이블 이름을 매개변수로 받습니다. SQL 식별자는 플레이스홀더로 매개변수화할 수 없으므로, 테이블 이름은 문자열 이스케이프만 하는 대신 엄격한 정규식 information_schema에서 가져온 실시간 허용 목록으로 검사됩니다.

  5. 리소스 한도. Postgres statement_timeout이 통제 불능 쿼리를 방지하고, 서버 측 행 상한이 모든 쿼리 결과에 적용됩니다. LLM의 쿼리가 LIMIT을 지정하지 않았더라도 마찬가지입니다.

빠른 시작

git clone <this-repo>
cd sql-mcp-server
pip install -r requirements.txt

# 1. Start Postgres with the sample schema
docker compose up -d

# 2. Generate sample e-commerce data (uses the postgres superuser, not mcp_readonly)
PGUSER=postgres PGPASSWORD=postgres python scripts/generate_sample_data.py

# 3. Configure the server to use the read-only role
cp .env.example .env
# edit .env if you changed the default mcp_readonly password

# 4. Run the tests
pytest

# 5. Run the server (stdio transport, for use with an MCP client)
python -m sql_mcp_server.server

Claude Desktop에 연결하기

Claude Desktop MCP 설정(claude_desktop_config.json)에 추가하세요:

{
  "mcpServers": {
    "sql-explorer": {
      "command": "python",
      "args": ["-m", "sql_mcp_server.server"],
      "cwd": "/absolute/path/to/sql-mcp-server",
      "env": {
        "PGHOST": "localhost",
        "PGPORT": "5432",
        "PGDATABASE": "sales",
        "PGUSER": "mcp_readonly",
        "PGPASSWORD": "change_me"
      }
    }
  }
}

Claude Desktop을 다시 시작한 다음 "어떤 테이블을 사용할 수 있고, 어떤 제품 카테고리의 총 매출이 가장 높나요?" 같은 질문을 해 보세요.

샘플 스키마

ordersorder_itemsproductscategories, 그리고 customers가 있습니다. 주문 매출 = sum(order_items.quantity * order_items.unit_price)입니다. 생성기는 ~600명의 고객, ~3,500건의 주문, 그리고 몇 가지 의도적인 데이터 특이점(누락된 이메일, 소수의 대량 주문 이상치)을 심어, 쿼리가 실제 데이터를 다루는 것처럼 보이게 합니다.

테스트

tests/test_security.pytests/test_tools.py는 데이터베이스 없이 실행됩니다. 검증 계층을 직접 테스트하고, DB 계층을 목(mock) 처리한 상태에서 도구 함수를 테스트합니다. 이것이 CI가 실행하는 내용입니다. db.py 자체(psycopg2 계층)는 실제로 Docker Postgres 인스턴스에 서버를 실행하여 테스트됩니다. 위의 빠른 시작을 참조하세요.

프로젝트 구조

sql_mcp_server/
  config.py    Environment-based settings
  security.py  SQL/identifier validation (the core safety logic)
  db.py        psycopg2 access layer
  server.py    MCP tool definitions
scripts/
  init_schema.sql            Schema + read-only role setup
  generate_sample_data.py    Faker-based sample data
tests/
  test_security.py  Validation logic (18+ cases: injection, stacked
                     statements, comment smuggling, DDL/DML blocking, etc.)
  test_tools.py     Tool functions with mocked DB
F
license - not found
Not graded
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables interaction with PostgreSQL databases through MCP, allowing users to explore database structures, inspect table schemas, and execute read-only SQL queries.
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables AI agents to query a PostgreSQL database through a small set of controlled, read-only tools for schema inspection, row lookup, and aggregate statistics.
    1
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    A read-only natural-language database agent that exposes PostgreSQL schema-discovery and SELECT tools via MCP, enabling users to query databases in plain English.
    MIT

View all related MCP servers

Related MCP Connectors

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Kenza-21/MCP-SQL-Server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server