Shop Analytics MCP Server
Shop Analytics MCP Server
一个通过 stdio 运行的只读 MCP 服务器,让 AI 智能体能够回答关于在线商店 SQLite 数据库(customers、products、orders、order_items)的分析性问题——而它永远无法修改该数据库。
完整的设计依据(决策日志、schema、安全模型、测试策略)见 SPEC.md。
环境要求
Node.js >= 24.10.0(
node:sqlite的setAuthorizer需要此版本,用于实现下文的只读保证)。运行node --version检查。除
npm ci安装的内容外,没有其他运行时依赖。
Related MCP server: Read-Only SQLite Shop Database MCP Server
安装 → 配置 → 运行 → 连接
npm ci
npm run build
SHOP_DB_PATH=./shop.db npm startshop.db已随仓库提供,开箱即用。如果需要从 schema 确定性重建它,请运行npm run seed(见下文 数据库)。SHOP_DB_PATH是可选的;默认值是当前工作目录下的shop.db。源码中没有任何位置硬编码绝对路径。服务器仅通过 stdio 执行 MCP 通信——没有 HTTP 服务器,也没有其他需要运行的东西。
连接 AI 智能体
两个客户端的配置示例见 config/:
config/claude-code.mcp.json——将其复制到项目的.mcp.json中,或使用其中的shop-analytics条目运行claude mcp add-json。请先为args/env填入绝对路径。config/codex.mcp.toml——将[mcp_servers.shop-analytics]表复制到~/.codex/config.toml(或项目级的.codex/config.toml),或使用该文件头部注释里的codex mcp add命令。
如果不想特定依赖某个具体的智能体,而想手动试验这个服务器,可以使用不依赖特定工具的 MCP Inspector:
SHOP_DB_PATH=$(pwd)/shop.db npx @modelcontextprotocol/inspector node dist/src/index.js工具
服务器恰好暴露 8 个专门的只读工具——没有任何工具接受或执行任意 SQL。每个成功响应都是 { "data": [...], "meta": {...} };每个错误都是一个简单、安全、人类可读的消息(不含 SQL、文件路径或堆栈跟踪),并以 isError: true 标记。
工具 | 可回答的问题 | 关键参数 |
| “显示所有表格和它们包含的内容。” | (无) |
| “有多少顾客来自德国?” |
|
| “哪个国家的顾客最多?” |
|
| “谁花的钱最多?” |
|
| “销量最高的前 5 个产品是什么?” |
|
| “按营收排名前 3 的类别是什么?” |
|
| “我们 2025 年产生了多少营收?” |
|
| “哪个顾客下的订单最多?” |
|
from/to 采用 YYYY-MM-DD 格式,定义了一个半开 UTC 区间 [from, to);from 必须严格早于 to。所有财务和计数指标都会排除状态为 cancelled 的订单。每个工具的完整契约(确切的响应结构、并列规则)见 SPEC.md §4。
安全
三层独立、纵深防御的机制保证数据库永远不会被修改,即使面对一个对抗性提示词,例如 “删除所有已取消的订单”:
SQLite 连接通过
readOnly: true打开。打开后立即设置
PRAGMA query_only = ON。有一个 SQLite
authorizer明确拒绝对所有写/DDL 操作,例如(INSERT、UPDATE、DELETE、DROP、ALTER、CREATE、ATTACH、DETACH、事务等,并有显式拒绝事务的机制)。
此外,没有任何工具接受原始 SQL、表名或列名,所有查询都是固定的预编译语句,所有输入都经过 zod 校验,并作为绑定参数传入,从不做字符串插值。
数据库
shop.db 由 database/schema.sql 通过一个确定性的 seed 脚本生成,每次重新运行都会产生逐字节一致的数据(固定 PRNG 种子,不依赖墙钟时间):
npm run seed # builds, then (re)writes ./shop.db from schema.sql + the seed scriptseed 脚本还会在生成时断言数据集没有歧义的排行榜(例如唯一的最佳国家、唯一的最大消费者),并且 2025 年的营收不为零——见 SPEC.md §3。
开发
npm run build # tsc + copy database/schema.sql into dist/
npm run test:unit # business logic, in isolation, against fixture databases
npm run test:integration # spawns the built server over stdio via the MCP SDK client
npm test # both本项目以 TDD 方式构建:对每个模块,先编写失败的测试,再是工具逐项实现。集成测试套件端到端覆盖了全部 8 个验收场景、SQL 注入形态的输入、无效参数组合,并断言每次运行后数据库文件的 SHA-256 哈希值不变。
项目结构
database/ schema.sql + the deterministic seed generator
src/
db.ts read-only SQLite connection (see Safety above)
errors.ts error taxonomy, safe error formatting
validation.ts zod schemas shared across tools (dates, limits, periods)
period.ts half-open period SQL clause builder
tools/ one module per tool: pure query function + types
server.ts registers all 8 tools on the MCP server
index.ts stdio entrypoint
test/
unit/ one file per module/tool, fixture-based
integration/ spawns dist/src/index.js over stdio via the MCP SDK client
config/ example client configuration (Claude Code, Codex CLI)Available Tools
8 toolsget_customers_by_countryGet customer count for a countryA
Returns how many customers are registered in a given country (case-insensitive match, e.g. 'germany' matches 'Germany'). An unknown country is a successful result with count 0, not an error. Use this to answer questions like 'how many customers are from Germany?'.
Inputs: country (required).
get_database_schemaGet database schemaA
Lists every business table (customers, products, orders, order_items), their columns (name, SQLite type, nullability, primary key) and foreign key relationships. Use this first to understand what data is available before calling the other tools. Takes no parameters.
Inputs: no named parameters.
get_revenue_for_periodGet total revenue for a periodA
Sums revenue (quantity * unit_price) across all orders in the requested period, or the whole dataset if no bounds are given. Orders with status 'cancelled' are always excluded from this metric. A period with no matching orders is a successful zero-revenue result, not an error. Optional half-open UTC interval [from, to). Both are 'YYYY-MM-DD'. Omitting a bound leaves that side open (e.g. only 'to' means "everything before to"). 'from' must be strictly earlier than 'to' or the call is rejected. Use this to answer 'how much revenue did we generate in 2025?' (pass from='2025-01-01', to='2026-01-01').
Inputs: to, from.
get_top_categories_by_revenueGet top product categories by revenueA
Ranks product categories by revenue (sum of quantity * unit_price for their products), descending (ties broken by category name ascending). Orders with status 'cancelled' are always excluded from this metric. Defaults to the top 3 categories. Optional half-open UTC interval [from, to). Both are 'YYYY-MM-DD'. Omitting a bound leaves that side open (e.g. only 'to' means "everything before to"). 'from' must be strictly earlier than 'to' or the call is rejected. Use this to answer 'what are the top 3 product categories by revenue?'.
Inputs: to, from, limit.
get_top_countries_by_customersGet top countries by customer countA
Ranks countries by number of registered customers, descending (ties broken by country name ascending). Defaults to the single top country; pass a higher 'limit' for a top-N leaderboard. Use this to answer 'which country has the most customers?'.
Inputs: limit.
get_top_customers_by_ordersGet top customers by number of ordersA
Ranks customers by how many orders they placed, descending (ties broken by customer id ascending). Orders with status 'cancelled' are always excluded from this metric. Defaults to the single top customer; pass a higher 'limit' for a top-N leaderboard. Optional half-open UTC interval [from, to). Both are 'YYYY-MM-DD'. Omitting a bound leaves that side open (e.g. only 'to' means "everything before to"). 'from' must be strictly earlier than 'to' or the call is rejected. Use this to answer 'which customer placed the most orders?'.
Inputs: to, from, limit.
get_top_customers_by_spendGet top customers by total spendA
Ranks customers by total money spent (sum of quantity * unit_price across their orders), descending. Orders with status 'cancelled' are always excluded from this metric. Ties broken by customer id ascending. Defaults to the single top spender; pass a higher 'limit' for a top-N leaderboard. Optional half-open UTC interval [from, to). Both are 'YYYY-MM-DD'. Omitting a bound leaves that side open (e.g. only 'to' means "everything before to"). 'from' must be strictly earlier than 'to' or the call is rejected. Use this to answer 'who is the customer who spent the most money?'.
Inputs: to, from, limit.
get_top_selling_productsGet top-selling productsA
Ranks products by units sold, descending (ties broken by revenue descending, then product id ascending). Orders with status 'cancelled' are always excluded from this metric. Defaults to the top 5 products. Optional half-open UTC interval [from, to). Both are 'YYYY-MM-DD'. Omitting a bound leaves that side open (e.g. only 'to' means "everything before to"). 'from' must be strictly earlier than 'to' or the call is rejected. Use this to answer 'what are the top 5 best-selling products?'.
Inputs: to, from, limit.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Each tool targets a distinct analytics query—schema, country customer counts, leaderboards for customers, products, categories, and revenue periods. There is no overlap; an agent can unambiguously pick the right tool for a given question.
All tool names follow the same pattern: 'get_' followed by a descriptive phrase in snake_case (e.g., get_top_selling_products, get_revenue_for_period). The naming is perfectly consistent and immediately conveys the operation and focus.
With 8 tools, the server is well-scoped for a shop analytics domain. Each tool covers a distinct business question without redundancy, and the count is in the ideal range for usability and clarity.
The set covers core analytics needs: customer demographics, top customers by spend and orders, top products and categories, revenue totals, and schema discovery. Minor gaps exist (e.g., no per-product revenue breakdown or filtering by specific customers), but the surface is largely complete for typical analytics queries.
Related MCP Connectors
Read-only analytics for all your apps: users, AI traffic, revenue, with the SQL behind every number.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Related MCP Servers
- FlicenseAqualityDmaintenanceEnables AI agents to safely interact with a SQLite shop database through schema discovery, read-only SQL queries, and pre-built analytics reports like top customers, top products, and revenue summaries.6-
- FlicenseAqualityDmaintenanceEnables 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-
- FlicenseAqualityDmaintenanceEnables 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-
- FlicenseAqualityDmaintenanceGives 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-