SQLite Shop MCP Server
SQLite Shop MCP Server 🛍️
一个安全、高性能的 MCP(Model Context Protocol) 服务器,基于 Python,用于将 AI 代理(Claude Desktop、Cursor、Antigravity、Gemini CLI)连接到在线商店的关系数据库(shop.db)。
服务器通过标准输入/输出(stdio)在本地运行,实现了两级防止修改的防护(严格只读),支持自动分页、面向代理自纠错的友好错误处理,并附带 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:安全执行任意 SQL,支持自动分页(page、page_size)、防止上下文溢出(最多 1000 行)以及执行时间测量。
友好错误处理(Self-Correction):
不会向外部暴露任何“原始”Python 堆栈跟踪。
当访问不存在的列而报错时,服务器会提示表中可用列的列表,使模型能够立即自我纠正。
可移植性:
没有任何硬编码的绝对路径。路径根据项目自动确定,或通过环境变量
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 年 2 月 17 日到 2026 年 8 月 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