Skip to main content
Glama
skvertl

SQLite Shop MCP Server

by skvertl

SQLite Shop MCP Server 🛍️

安全で高性能な**MCP(Model Context Protocol)**サーバー。Python製で、AIエージェント(Claude Desktop、Cursor、Antigravity、Gemini CLI)をオンラインショップのリレーショナルデータベース(shop.db)に接続します。

サーバーは標準入出力(stdio)を介してローカルで動作し、**二重の変更保護(厳格なRead-Only)**を実装しています。自動ページネーション、エージェントの自己修正を可能にするわかりやすいエラー処理をサポートし、テストカバレッジ100%を備えています。


🌟 主な機能

  1. 多層セキュリティ(Strict Read-Only):

    • 物理レベル(SQLite Engine): データベースはURI file:shop.db?mode=ro で開かれます。書き込みの試みはすべてSQLiteのCライブラリによって物理的にブロックされます(OperationalError: attempt to write a readonly database)。

    • 構文レベル(AST & Token Validator): クエリはデータベースに渡される前に解析されます。許可されるのは SELECTWITH(CTE)、EXPLAIN のみです。破壊的な操作(INSERTUPDATEDELETEDROPALTERCREATEATTACHPRAGMA writable)や、セミコロンによるクエリの連結は即座に拒否されます。

  2. スマートなツール設計 (4 Tools):

    • get_database_schema: すべてのテーブル、型、主キー/外部キー、行数、データの説明ヒントの完全なカタログ。

    • describe_table: 指定したテーブルの詳細なスキーマ。

    • get_sample_data: SQLを書かずにテーブルのレコードをプレビュー。

    • execute_query: 自動ページネーション(pagepage_size)、コンテキストオーバーフロー保護(最大1000行)、実行時間の測定を備えた安全な任意SQL実行。

  3. フレンドリーなエラー処理(Self-Correction):

    • Pythonの「生の」スタックトレースを外部に公開しません。

    • 存在しないカラムへのアクセスエラーが発生すると、サーバーはテーブル内の利用可能なカラムのリストを提示し、モデルが即座に自己修正できるようにします。

  4. 移植性:

    • ハードコードされた絶対パスはありません。パスはプロジェクトからの相対パスとして自動的に決定されるか、環境変数 SHOP_DB_PATH で指定します。

  5. テストとDocker:

    • 51件のpytest自動テスト(セキュリティ、データベース、統合、仕様書の全8タスク)。

    • 完成済みのDockerfiledocker-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.txt

2. 設定 (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.json

  • macOS: ~/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-shop

  • Type: command

  • Command: 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)

選択したテーブル(customersproductsordersorder_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クエリ(SELECTWITH ... SELECTEXPLAIN)。

    • 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 の実データで検証されています:

仕様書の質問

execute_query によるSQLクエリ

エージェントの回答

1

Show me all available tables and explain what information each table contains.

get_database_schema() を呼び出す

4つのテーブル: customers(顧客150件)、products(商品50件)、orders(注文750件)、order_items(注文明細1900件)。

2

How many customers are from Germany?

SELECT COUNT(*) FROM customers WHERE phone LIKE '+49%'

0人。(テーブルに country カラムはなく、すべての電話番号は +7 で始まります)。

3

Which country has the most customers?

SELECT SUBSTR(phone, 1, 2) as code, COUNT(*) as c FROM customers GROUP BY code

ロシア(+7) — 150人(データベースの100%)。

4

Who is the customer who spent the most money?

SELECT c.first_name, c.last_name, c.email, ROUND(SUM(o.total_amount), 2) as spent FROM customers c JOIN orders o ON c.id = o.customer_id WHERE o.status != 'cancelled' GROUP BY c.id ORDER BY spent DESC LIMIT 1

Дмитрий Харитоновdmitriy.kharitonov845@mail.ru)— 701 780.00ルーブル

5

What are the top 5 best-selling products?

SELECT p.name, SUM(oi.quantity) as qty, ROUND(SUM(oi.quantity * oi.unit_price), 2) as rev FROM products p JOIN order_items oi ON p.id = oi.product_id JOIN orders o ON o.id = oi.order_id WHERE o.status != 'cancelled' GROUP BY p.id ORDER BY qty DESC LIMIT 5

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?

SELECT p.category, ROUND(SUM(oi.quantity * oi.unit_price), 2) as rev FROM products p JOIN order_items oi ON p.id = oi.product_id JOIN orders o ON o.id = oi.order_id WHERE o.status != 'cancelled' GROUP BY p.category ORDER BY rev DESC LIMIT 3

1. エレクトロニクス — 17 060 760ルーブル2. 家電 — 5 506 570ルーブル3. 衣料品・靴 — 3 085 470ルーブル

7

How much revenue did we generate in 2025?

SELECT COALESCE(ROUND(SUM(total_amount), 2), 0.0) FROM orders WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01' AND status != 'cancelled'

0.00ルーブル(店舗のすべての注文は2026年に作成されています: 2026年2月17日から2026年8月22日まで)。

8

Which customer placed the most orders?

SELECT c.first_name, c.last_name, c.email, COUNT(o.id) as cnt FROM customers c JOIN orders o ON c.id = o.customer_id GROUP BY c.id ORDER BY cnt DESC LIMIT 1

София Яковлевsofiya.yakovlev284@yandex.ru)— 16件の注文

セキュリティチェック (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.

Maintenance

ActivityMaintained
ResponsivenessSyncing

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

Related MCP Servers

  • F
    license
    Not graded
    quality
    C
    maintenance
    Provides AI agents read-only analytical access to a SQLite database over stdio, with tools for listing tables, describing schemas, and running paginated SQL queries.
  • F
    license
    A
    quality
    C
    maintenance
    Enables 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
  • F
    license
    A
    quality
    C
    maintenance
    Enables 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
  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to read-only analyze a SQLite e-commerce database, exploring schema and running analytical SQL queries over stdio.

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/skvertl/New_MCP'

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