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)在本地运行,实现了两级防止修改的防护(严格只读),支持自动分页、面向代理自纠错的友好错误处理,并附带 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:安全执行任意 SQL,支持自动分页(pagepage_size)、防止上下文溢出(最多 1000 行)以及执行时间测量。

  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

  • Namesqlite-shop

  • Typecommand

  • Commandpython 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):每页行数。

  • 响应格式:

    {
      "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

显示所有可用表,并解释每张表包含哪些信息。

调用 get_database_schema()

4 张表:customers(150 名客户)、products(50 件商品)、orders(750 个订单)、order_items(1900 个订单项)。

2

有多少客户来自德国?

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

0 名客户。(表中没有 country 列,所有电话号码均以 +7 开头。)

3

哪个国家的客户最多?

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

俄罗斯(+7) — 150 名客户(占数据库 100%)。

4

哪位客户消费金额最高?

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

销量最高的 5 种产品是什么?

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

按收入排名前 3 的产品类别是什么?

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

我们在 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

哪位客户下的订单最多?

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