SQLite Shop MCP Server
SQLite Shop MCP Server 🛍️
Python 기반의 안전하고 고성능 MCP(Model Context Protocol) 서버로, AI 에이전트(Claude Desktop, Cursor, Antigravity, Gemini CLI)를 인터넷 쇼핑몰의 관계형 데이터베이스(shop.db)에 연결합니다.
서버는 표준 입출력(stdio)을 통해 로컬에서 실행되며, **2단계 변경 방지(엄격한 읽기 전용)**을 구현하고, 자동 페이지네이션, 에이전트의 자가 수정을 돕는 명확한 오류 처리를 지원하며, 100% 테스트 커버리지를 갖추고 있습니다.
🌟 주요 기능
다중 계층 보안(Strict Read-Only):
물리적 계층(SQLite Engine): 데이터베이스는 URI
file:shop.db?mode=ro로 열립니다. 모든 쓰기 시도는 SQLite C 라이브러리에 의해 물리적으로 차단됩니다(OperationalError: attempt to write a readonly database).어휘적 계층(AST & Token Validator): 쿼리는 데이터베이스에 전달되기 전에 분석됩니다.
SELECT,WITH(CTE),EXPLAIN만 허용됩니다. 모든 파괴적 작업(INSERT,UPDATE,DELETE,DROP,ALTER,CREATE,ATTACH,PRAGMA writable)과 세미콜론을 통한 쿼리 체인은 즉시 거부됩니다.
지능적인 도구 설계(4 Tools):
get_database_schema: 모든 테이블, 유형, 기본/외래 키, 행 수 및 주제별 힌트의 전체 카탈로그.describe_table: 특정 테이블의 상세 스키마.get_sample_data: SQL을 작성하지 않고 테이블 레코드 미리보기.execute_query: 자동 페이지네이션(page,page_size), 컨텍스트 오버플로 방지(최대 1000행), 실행 시간 측정을 지원하는 안전한 임의 SQL 실행.
친화적인 오류 처리(Self-Correction):
외부로 노출되는 "날것 그대로의" 파이썬 스택 트레이스 없음.
존재하지 않는 컬럼에 대한 오류가 발생하면 서버는 테이블에서 사용 가능한 컬럼 목록을 제안하여 모델이 즉시 스스로 수정할 수 있게 합니다.
이식성:
하드코딩된 절대 경로 없음. 경로는 프로젝트 기준으로 자동 결정되거나 환경 변수
SHOP_DB_PATH로 지정됩니다.
테스트 및 Docker:
51개의
pytest자동 테스트(보안, 데이터베이스, 통합, 명세서의 8개 태스크 모두).준비된
Dockerfile및docker-compose.yml.
Related MCP server: Read-Only SQLite Shop Database MCP Server
🏗️ 아키텍처
[ AI Agent: Claude / Cursor / Antigravity ]
│ (stdio JSON-RPC)
▼
[ server.py ] (MCPServer stdio transport)
│
┌─────────────┴─────────────┐
▼ ▼
[ src/security.py ] [ src/db.py ]
(Валидация SQL, (Подключение в mode=ro,
защита от инъекций) пагинация, сбор метрик)
│
▼
[ shop.db (mode=ro) ]shop.db 데이터베이스 스키마
customers (150 строк)
│
└──< orders (750 строк)
│
└──< order_items (1900 строк) >── products (50 строк)🚀 빠른 시작
1. 의존성 설치 (Install)
Python 3.10+ 필요:
# Клонируйте репозиторий или перейдите в папку проекта
cd HW_MCP
# Установите зависимости
pip install -r requirements.txt2. 구성 (Configure)
기본적으로 서버는 프로젝트 루트에서 shop.db 파일을 찾습니다. 필요한 경우 환경 변수로 경로를 재정의할 수 있습니다:
# Windows (PowerShell)
$env:SHOP_DB_PATH = "C:\path\to\shop.db"
# Linux / macOS
export SHOP_DB_PATH="/path/to/shop.db"3. 서버 실행 (Run)
서버는 stdio 모드로 실행됩니다:
python server.py🤖 AI 에이전트에 연결 (Connect to Agent)
Claude Desktop
Claude Desktop 설정 파일에 구성을 추가하세요:
Windows:
%APPDATA%\Claude\claude_desktop_config.jsonmacOS:
~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"sqlite-shop": {
"command": "python",
"args": [
"C:\\Users\\user\\OneDrive\\BackToTheFuture\\HW_MCP\\server.py"
],
"env": {
"PYTHONUNBUFFERED": "1"
}
}
}
}Cursor
Cursor에서 Settings > Features > MCP > Add New MCP Server로 이동하세요:
Name:
sqlite-shopType:
commandCommand:
python C:\Users\user\OneDrive\BackToTheFuture\HW_MCP\server.py
또는 프로젝트 워크스페이스 루트에 .cursor/mcp.json 파일을 생성하세요:
{
"mcpServers": {
"sqlite-shop": {
"command": "python",
"args": ["server.py"]
}
}
}Antigravity / Gemini CLI
mcp_config.json에 섹션을 추가하세요:
{
"mcpServers": {
"sqlite-shop": {
"command": "python",
"args": ["server.py"]
}
}
}🛠️ 도구 설명 (MCP Tools)
1. get_database_schema
모든 테이블의 전체 구조, 컬럼 데이터 유형, 기본 및 외래 키, 행 수, 데이터에 대한 설명 메모를 반환합니다.
2. describe_table(table_name: str)
선택한 테이블(customers, products, orders, order_items)의 컬럼 및 제약 조건에 대한 상세 스키마를 반환합니다.
3. get_sample_data(table_name: str, limit: int = 10)
데이터 형식 사전 분석을 위해 테이블에서 샘플 행을 반환합니다.
4. execute_query(query: str, page: int = 1, page_size: int = 50)
안전한 읽기 전용 SQL 쿼리를 실행합니다.
매개변수:
query(string, 필수): SQL 쿼리 (SELECT,WITH ... SELECT,EXPLAIN).page(int, 기본값: 1): 페이지 번호.page_size(int, 기본값: 50, 최대: 1000): 페이지당 행 수.
응답 형식:
{ "rows": [ { "id": 1, "first_name": "Арина", "email": "..." } ], "page": 1, "page_size": 50, "total_rows_in_page": 50, "has_more": true, "execution_time_ms": 1.24 }
📊 명세서의 8개 제어 태스크 해결
모든 쿼리는 실제 shop.db 데이터로 검증되었습니다:
№ | 명세서의 질문 |
| 에이전트의 답변 |
1 | 사용 가능한 모든 테이블을 보여 주고 각 테이블에 포함된 정보를 설명하세요. |
| 테이블 4개: |
2 | 독일에서 온 고객은 몇 명인가요? |
| 고객 0명. (테이블에 |
3 | 어느 나라에 고객이 가장 많나요? |
| 러시아 (+7) — 고객 150명 (데이터베이스의 100%). |
4 | 가장 많은 돈을 지출한 고객은 누구인가요? |
| 드미트리 하리토노프 ( |
5 | 가장 많이 팔린 상위 5개 제품은 무엇인가요? |
| 1. 어깨 완력기 (93개, 110 670루블)2. AirFresh 가습기 (92개, 394 680루블)3. 핸드 블렌더 800W (84개, 267 960루블)4. 가죽 부츠 (83개, 704 670루블)5. 전문가용 헤어드라이어 (83개, 455 670루블) |
6 | 매출 기준 상위 3개 제품 카테고리는 무엇인가요? |
| 1. 전자제품 — 17 060 760루블2. 가전제품 — 5 506 570루블3. 의류 및 신발 — 3 085 470루블 |
7 | 2025년에 발생한 매출은 얼마인가요? |
| 0.00루블 (매장의 모든 주문은 2026년에 생성되었습니다: 2026.02.17부터 2026.08.22까지). |
8 | 주문을 가장 많이 한 고객은 누구인가요? |
| 소피야 야코블레프 ( |
보안 확인 (Safety Requirement)
에이전트 요청:
취소된 모든 주문을 삭제하세요.
MCP 서버 응답:
{
"error": true,
"error_type": "PermissionDenied",
"message": "PermissionDenied: Modifying or destructive operations are not permitted (read-only server). Statement starts with 'DELETE'."
}데이터베이스는 완전히 보존됩니다.
🧪 자동 테스트 실행
프로젝트에는 pytest 기반의 전체 테스트 세트가 구현되어 있습니다:
tests/test_security.py— 파괴적 표현, SQL 인젝션 및 쿼리 체인 차단 확인.tests/test_db.py— 물리적mode=ro, 스키마, 페이지네이션 및 오류 시 힌트 확인.tests/test_server.py— 도구 호출 통합 테스트 및 과제의 8개 태스크 모두 검증.
pytest tests/ -v결과:
============================= 51 passed in 0.87s ==============================🐳 Docker에서 실행
컨테이너 빌드 및 실행:
# Сборка образа
docker build -t sqlite-shop-mcp .
# Запуск с монтированием базы
docker run -i --rm -v $(pwd)/shop.db:/app/shop.db:ro sqlite-shop-mcp또는 docker-compose 사용:
docker-compose run --rm sqlite-shop-mcp📁 저장소 구조
HW_MCP/
├── .agent/ # Интеграция с OpenSpec агентами
├── openspec/ # Спецификация требований (OpenSpec living specs & changes)
├── src/
│ ├── __init__.py
│ ├── config.py # Разрешение путей и настроек SQLite URI
│ ├── security.py # Валидатор SQL-запросов (Read-Only enforcement)
│ └── db.py # Слой SQLite (mode=ro, пагинация, сбор схем)
├── tests/
│ ├── test_security.py # Тесты безопасности SQL
│ ├── test_db.py # Тесты слоя БД и пагинации
│ └── test_server.py # Интеграционные тесты 8 аналитических задач
├── Dockerfile # Контейнеризация сервиса
├── docker-compose.yml
├── mcp_config_example.json # Примеры конфигов для Claude Desktop, Cursor, Antigravity
├── requirements.txt # Зависимости Python
├── server.py # Главная точка входа MCP-сервера
├── shop.db # База данных SQLite интернет-магазина
└── README.md # Полная документация проекта📜 라이선스
MIT License.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Explore, query, and inspect SQLite databases with ease. List tables, preview results, and view det…
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Related MCP Servers
- FlicenseNot gradedqualityCmaintenanceProvides AI agents read-only analytical access to a SQLite database over stdio, with tools for listing tables, describing schemas, and running paginated SQL queries.
- FlicenseAqualityCmaintenanceEnables AI agents to safely inspect and query an SQLite e-commerce database with tools for listing tables, describing schemas, and running read-only SQL queries while blocking destructive operations.4
- FlicenseAqualityCmaintenanceEnables AI agents to read-only query an online store's SQLite database, listing tables, inspecting schemas, and running SELECT queries over customers, products, orders, and order items.3
- FlicenseNot gradedqualityCmaintenanceEnables AI agents to read-only analyze a SQLite e-commerce database, exploring schema and running analytical SQL queries over stdio.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
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/skvertl/New_MCP'
If you have feedback or need assistance with the MCP directory API, please join our Discord server