SQLite Shop MCP Server
SQLite Shop MCP Server 🛍️
安全で高性能な**MCP(Model Context Protocol)**サーバー。Python製で、AIエージェント(Claude Desktop、Cursor、Antigravity、Gemini CLI)をオンラインショップのリレーショナルデータベース(shop.db)に接続します。
サーバーは標準入出力(stdio)を介してローカルで動作し、**二重の変更保護(厳格なRead-Only)**を実装しています。自動ページネーション、エージェントの自己修正を可能にするわかりやすいエラー処理をサポートし、テストカバレッジ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):
Pythonの「生の」スタックトレースを外部に公開しません。
存在しないカラムへのアクセスエラーが発生すると、サーバーはテーブル内の利用可能なカラムのリストを提示し、モデルが即座に自己修正できるようにします。
移植性:
ハードコードされた絶対パスはありません。パスはプロジェクトからの相対パスとして自動的に決定されるか、環境変数
SHOP_DB_PATHで指定します。
テストとDocker:
51件の
pytest自動テスト(セキュリティ、データベース、統合、仕様書の全8タスク)。完成済みの
Dockerfileとdocker-compose.yml。
Related MCP server: shop-db
🏗️ アーキテクチャ
[ 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): 1ページあたりの行数。
レスポンス形式:
{ "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 | Show me all available tables and explain what information each table contains. |
| 4つのテーブル: |
2 | How many customers are from Germany? |
| 0人。(テーブルに |
3 | Which country has the most customers? |
| ロシア(+7) — 150人(データベースの100%)。 |
4 | Who is the customer who spent the most money? |
| Дмитрий Харитонов( |
5 | What are the top 5 best-selling products? |
| 1. ショルダーエキスパンダー(93個、110 670ルーブル)2. 加湿器 AirFresh(92個、394 680ルーブル)3. ハンドブレンダー800W(84個、267 960ルーブル)4. 革ブーツ(83個、704 670ルーブル)5. プロ用ヘアドライヤー(83個、455 670ルーブル) |
6 | What are the top 3 product categories by revenue? |
| 1. エレクトロニクス — 17 060 760ルーブル2. 家電 — 5 506 570ルーブル3. 衣料品・靴 — 3 085 470ルーブル |
7 | How much revenue did we generate in 2025? |
| 0.00ルーブル(店舗のすべての注文は2026年に作成されています: 2026年2月17日から2026年8月22日まで)。 |
8 | Which customer placed the most orders? |
| София Яковлев( |
セキュリティチェック (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 deployed
Maintenance
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.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Related MCP Servers
- 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.-
- FlicenseAqualityBmaintenanceGives AI agents read-only analytical access to an e-commerce SQLite database (customers, orders, order_items, products) via SQL queries, table listing, and schema inspection.3-