shop-mcp
shop-mcp
仅读 Model Context Protocol 服务器,用于通过互联网商店的 shop.db SQLite 数据库(客户、产品、订单、订单项目)暴露分析工具。它设计为连接到 AI 助手,使助手能够回答关于数据的分析性问题,而永远不会修改数据。
服务器通过 stdio 实现 MCP,以 只读 模式打开数据库,并暴露一个小型但 专用、参数化的工具集,其描述中编码了领域规则(哪些订单状态计入收入、客户的国家如何得出、钱来自何处)。这里没有通用 SQL 工具,也没有写入工具——因此,像“删除所有已取消的订单”这样的破坏性提示无法被执行。
本仓库中的 MCP 服务器代码由 AI 编码代理 (Cursor) 生成,这符合作业约束:不能手工编写服务器。
环境要求
Python 3.11 或更新版本
shop.dbSQLite 数据库(存储于database/shop.db)uv(推荐)——在隔离的项目环境中运行服务器,无需全局安装。可通过brew install uv(macOS) 或curl -LsSf https://astral.sh/uv/install.sh | sh安装。
Related MCP server: mcp-data-analyst
安装
推荐使用 uv ——无需手动创建 venv 或使用 pip,uv 会在首次运行时从 pyproject.toml 解析项目及其依赖:
uv sync # create / refresh the project's .venv from pyproject.toml如果不使用 uv —— 手动创建 virtualenv 并安装包:
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e .这将导入 mcp SDK 和 shop-mcp 包(该包提供 python -m shop_mcp 入口点以及 shop-mcp 控制台命令)。
配置
服务器相对于当前进程工作目录(ProjectRoot)打开 database/shop.db 数据库。无需任何环境变量。
当通过 uv run --directory <project> 启动时(见下面的客户端配置),uv 会将工作目录设置为项目根目录,因此会自动找到已提交的数据库。
如果 database/shop.db 缺失,服务器会在启动时以明确的配置错误退出,并包含当前工作目录(无堆栈跟踪,无静默回退)。请确保你的 MCP 客户端配置将 cwd 设置为仓库根目录。
运行
uv run python -m shop_mcp或,在已激活的 venv 中安装该包后:
python -m shop_mcp或等效地:
shop-mcp服务器通过 stdin 读取 JSON-RPC,并写入 stdout。你通常不需要直接运行它——你的 AI 代理会为你启动它(见下文)。
连接代理
成品 MCP 客户端配置已提交在 examples/mcp/ 下,且只需安装 uv 即可运行,无需其他配置:
客户端 | 配置文件 |
Cursor |
|
Claude Desktop |
|
Generic 标准io |
|
规范/默认 |
|
Docker |
|
每个配置如下所示(将 --directory 路径替换为本仓库在你机器上的绝对路径):
{
"mcpServers": {
"shop": {
"command": "uv",
"args": ["run", "--directory", "/path/to/internet-shop-mcp", "python", "-m", "shop_mcp"]
}
}
}uv run --directory <project> 将工作目录设置为项目根目录并使用项目的 .venv,因此服务器会自动找到 database/shop.db。同一配置可在机器之间移植(仅 --directory 路径变化)。
如果你不想使用 uv,可以自行将包安装到 venv 中(见 安装),使用 command: "python",并在 MCP 客户端配置中将 cwd 设置为仓库根目录。
Cursor:打开 Settings → MCP → Add MCP Server,粘贴
examples/mcp/cursor.json的内容(或使用 Project MCP 作用域并提交)。Claude Desktop:将
examples/mcp/claude_desktop.json的内容复制到claude_desktop_config.json(macOS:~/Library/Application Support/Claude/claude_desktop_config.json)。Generic stdio: 对于任何支持通过 stdio 使用 MCP 的客户端,使用
examples/mcp/generic_stdio.json。
连接后,代理将看到八个工具:list_tables、describe_table、count_customers_by_country、rank_countries_by_customers、top_customers、top_products、revenue_by_category、revenue_by_year。
工具
工具 | 解决的问题 |
| 任务 1 — 列出表及各自内容 |
| 单个表的模式 |
| 任务 2 — 查找某个国家的客户 |
| 任务 3 — 客户最多的国家 |
| 任务 4 和 8 — 顶尖消费客户 / 最多订单 |
| Task 5 — 最佳畅销产品 |
| 任务 6 — 按收入划分的顶级分类 |
| 任务 7 — 某年的收入 |
工具描述中内置了领域规则(完整原理见 CONTEXT.md 和 docs/adr/):
国家 / 地区 从客户手机号码前缀(E.164)推出。没有
country列。+49→ 德国,+7→ 俄罗斯。无法识别的前缀映射到unknown。换个措辞,接受完整名称(“Germany”)或 ISO alpha-2 代码(“DE”),并返回两者对应的国家。经常性收入 / 支出 仅计算
completed和shipped的订单。最多订单 统计除
cancelled以外的所有订单状态。最畅销 按已售数量排序;收入是次要字段。
收入金额来源 来自
orders.total_amount(订单/客户/年汇总)和SUM(order_items.quantity * order_items.unit_price)(产品/类别汇总,即实际销售价,而非当前products.price)。限制 默认 100,最高 1000,
offset用于分页。错误 以短小纯文本消息返回给代理(如
Invalid year: must be a 4-digit integer);堆栈跟踪仅打印到 stderr。
安全性
数据库在构造上即可写:
SQLite 以
file:<path>?mode=ro(uri=True) 模式打开,因此任何写操作都会抛出sqlite3.OperationalError: attempt to write a readonly database。设置
PRAGMA query_only = 1作为防御纵深。不提供写操作或通用 SQL 工具。只有上面列出的八个只读分析工具。
测试(tests/test_safety.py)断言写操作会抛出异常,不会提供写工具,并且运行每个工具后数据库文件逐字节不变。
端到端验证
以下 8 个作业任务已在连接的 AI 代理上验证。在已提交数据上得到的预期结果(150 个客户,全部使用 +7 号码;750 个订单,全部日期为 2026):
列出所有表 —
list_tables返回customers、products、orders、order_items,并附有描述。有多少客户来自德国? —
count_customers_by_country("Germany")→0(诚实的零;没有客户有+49号码)。哪个国家客户最多? —
rank_countries_by_customers→ 俄罗斯(RU),150 个客户。谁消费最多? —
top_customers(by="spend", limit=1)→ Полина Козлов,polina.kozlov340@icloud.com,总消费 531810.0。最佳畅销产品 Top 5 —
top_products(limit=5)→ 按销量排名(如 Эспандер плечевой、Планшет Tab 10,……)并附有收入。按收入排名 Top 3 分类 —
revenue_by_category(limit=3)→ Электроника, Бытовая техника, Одежда и обувь。2025 年的营收 —
revenue_by_year(2025)→0,并带有备注no orders in 2025(无年份替换;所有订单均为 2026)。订单量最高 —
top_customers(by="order_count", limit=1)→ София Яковлев,sofiya.yakovlev284@yandex.ru,15 个订单。
会拒绝破坏性提示 “删除所有已取消的订单”:没有能接受提示的工具,且只读连接在 SQLite 层面拒绝所有写操作。
测试
uv run --extra dev pytest
# or, with the package installed in an active venv:
pip install -e ".[dev]"
python -m pytest该测试套件覆盖:冒烟测试(服务器在 stdio 上启动并响应握手/list_tools),所有工具的正常路径,领域规则(收入排除未获得状态,订单计数排除已取消,商品按销量排序),边界情况(中国 → 0,2025 → 0 并备注,未知国家,无效年份/指标/分类,限额截断,分页),以及安全性(写操作抛出,无写工具,文件不允许为空)。
Docker(加分)
有关容器化运行,请参见下方“Docker”部分。
项目布局
internet-shop-mcp/
├── database/
│ └── shop.db # the read-only database
├── pyproject.toml # package + dependency declaration
├── README.md
├── CONTEXT.md # domain glossary
├── docs/adr/ # ADR-0001..0005
├── src/shop_mcp/
│ ├── __main__.py # `python -m shop_mcp`
│ ├── main.py # server wiring + tool registration
│ ├── config.py # database/shop.db resolution
│ ├── db.py # read-only SQLite connection
│ ├── country.py # phone-prefix → country mapping
│ └── tools.py # tool implementations
├── tests/ # pytest suite mirroring src
├── examples/mcp/ # agent connection configs
├── Dockerfile
└── .dockerignoreDocker
在容器中构建并运行服务器。数据库会复制到容器镜像中的 /app/database/shop.db(与本地环境采用同一映射方式)。
docker build -t shop-mcp .
docker run --rm -i shop-mcp一个适配 Docker 的 MCP 客户端配置:
{
"mcpServers": {
"shop": {
"command": "docker",
"args": ["run", "--rm", "-i", "shop-mcp"]
}
}
}要挂载自己的数据库,而不使用构建打包的数据库:
docker run --rm -i -v "$PWD/database:/app/database:ro" shop-mcp容器内仍保留只读保证:连接使用 mode=ro 和 query_only=1,破坏性提示仍然会被拒绝。
Available Tools
8 toolscount_customers_by_countryA
Count customers by country. The country is NOT a column — it is derived from the customer's phone-number prefix (E.164), so do not look for a country column. With no argument, returns counts per country as a list of {country_code, country_name, customer_count}. With a country argument (either a full name like 'Germany' or an ISO alpha-2 code like 'DE'), returns the count for that country only — an honest 0 if there are no customers there. An unknown country name returns an error.
Inputs: country.
describe_tableA
Describe the schema of one table: columns (name, type, not_null, default, primary_key) and foreign keys. Use this before building any mental model of how tables relate. Returns {table, columns, foreign_keys}. Pass the table name (one of: customers, products, orders, order_items).
Inputs: table (required).
list_tablesA
List every table in the shop database with a short description of what each table holds. Use this first to understand what entities are available. Returns a list of {name, description}.
Inputs: no named parameters.
rank_countries_by_customersA
Rank countries by number of customers, highest first. The country is derived from each customer's phone-number prefix (there is no country column). Returns a list of {country_code, country_name, customer_count}. limit defaults to 100 and is clamped to a maximum of 1000.
Inputs: limit.
revenue_by_categoryA
Rank product categories by revenue, joining orders -> order_items -> products. Only 'completed' and 'shipped' orders count. Revenue is SUM(order_items.quantity * order_items.unit_price) using the actual sale price. Returns a list of {category, revenue}. limit defaults to 100 (max 1000); offset paginates.
Inputs: limit, offset.
revenue_by_yearA
Return total revenue for a single year (a 4-digit integer, e.g. 2025). Revenue is SUM(orders.total_amount) over orders whose order_date falls in that year and whose status is 'completed' or 'shipped'. A year with no qualifying orders returns revenue 0 with a 'no orders in ' note — it does not substitute a different year. An invalid year returns an error.
Inputs: year (required).
top_customersA
Rank customers either by total spend or by number of placed orders.
by='spend': sums orders.total_amount over orders with status 'completed' or 'shipped' only (new, processing, cancelled do not count as earned). Returns first_name, last_name, email, total_spend.
by='order_count': counts orders whose status is NOT 'cancelled'. Returns first_name, last_name, email, order_count. Customer names are returned as separate first_name and last_name fields.
limitdefaults to 100 (max 1000);offsetpaginates.
Inputs: by, limit, offset.
top_productsA
Rank products by units sold (metric='units', default) or by revenue (metric='revenue'). Only 'completed' and 'shipped' orders count. Money is computed from order_items.unit_price (the actual sale price), not the current products.price. Returns a list of {name, units_sold, revenue}. When metric='units', ranking is by units_sold and revenue is a secondary field. limit defaults to 100 (max 1000); offset paginates.
Inputs: limit, metric, offset.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Most tools are clearly distinct, but count_customers_by_country and rank_countries_by_customers return the same country-level customer counts with only ordering/filtering differences. The other tools, such as top_customers and top_products, are well separated by their selection criteria.
Namess are mostly predictable and use snake_case with clear intent, like list_tables and describe_table. The main inconsistency is that some tools follow imperative verb names while others use noun phrases like top_customers or revenue_by_category, but the pattern remains readable.
Eight tools is well-suited for a read-only analytics server covering schema inspection and common shop metrics. Each tool has a clear role, and the count does not feel excessive or thin.
The toolset covers the main analytics surface: customer geography, top customers, top products, category revenue, and annual revenue. It lacks order-level or product-level detail queries and finer time-based filters, but the visible analytical workflows are complete enough for most shop insight requests.
Maintenance
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
MerchantFlow is a hosted, read-only ecommerce analytics MCP server for Shopify and WooCommerce. It gives AI assistants tenant-scoped access to revenue, profit and loss, product and SKU profitability, COGS coverage, fulfillment costs, advertising spend, ROAS, marketing performance, cohorts, LTV, and business valuation across connected commerce and marketing platforms. Connect with OAuth over Streamable HTTP. No local server installation is required.
Read-only Google Analytics 4 MCP server for AI assistants.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA secure MCP server that exposes a SQLite database to AI agents with Role-Based Access Control, supporting authentication, customer/order/user management, and audit logging.-
- AlicenseNot gradedqualityDmaintenanceA natural-language data analyst MCP server that lets users query SQLite sales datasets via MCP tools (list_tables, aggregate, time_series, run_sql) with read-only SQL safety guards, returning results through a FastAPI dashboard.MIT
- FlicenseNot gradedqualityDmaintenanceEnables safe, read-only analysis of an online store's SQLite database, providing schema introspection, restricted SELECT queries, and specialized analytics tools through MCP.-
- FlicenseNot gradedqualityDmaintenanceThis MCP server lets an AI agent securely connect to a read-only SQLite store database, inspect its tables and schema, and run analytical SQL queries without modifying any data.-