Shop Analytics MCP Server
Shop Analytics MCP Server
Un servidor MCP de solo lectura, a través de stdio, que permite a un agente de IA responder preguntas analíticas sobre la base de datos SQLite de una tienda en línea (customers, products, orders, order_items), sin que pueda modificarla en ningún caso.
Consulta SPEC.md para conocer el fundamento completo del diseño (registro de decisiones, esquema, modelo de seguridad y estrategia de pruebas).
Requisitos
Node.js >= 24.10.0 (necesario para
setAuthorizerdenode:sqlite, que se utiliza en la garantía de solo lectura que se indica más abajo). Compruébalo connode --version.Ninguna otra dependencia de ejecución aparte de las que instala
npm ci.
Related MCP server: Read-Only SQLite Shop Database MCP Server
Instalar → configurar → ejecutar → conectar
npm ci
npm run build
SHOP_DB_PATH=./shop.db npm startshop.dbse incluye en este repositorio, listo para usar. Si alguna vez necesitas regenerarlo de forma determinista a partir del esquema, ejecutanpm run seed(consulta Base de datos más abajo).SHOP_DB_PATHes opcional; su valor por defecto esshop.dben el directorio de trabajo actual. No hay ninguna ruta absoluta codificada en el código fuente.El servidor habla MCP únicamente por stdio: no hay ningún servidor HTTP ni nada más que ejecutar.
Conectar un agente de IA
Los ejemplos de configuración para dos clientes están en config/:
config/claude-code.mcp.json— cópialo en el.mcp.jsonde un proyecto, o ejecutaclaude mcp add-jsoncon su entradashop-analytics. Completa antes las rutas absolutas deargs/env.config/codex.mcp.toml— copia la tabla[mcp_servers.shop-analytics]en~/.codex/config.toml(o en un.codex/config.tomldel proyecto), o usa el comandocodex mcp addque se indica en el comentario de cabecera del archivo.
Para probar el servidor manualmente sin ningún agente concreto, usa MCP Inspector, que es independiente de la herramienta o cliente:
SHOP_DB_PATH=$(pwd)/shop.db npx @modelcontextprotocol/inspector node dist/src/index.jsHerramientas
El servidor expone exactamente 8 herramientas especializadas y de solo lectura: ninguna acepta ni ejecuta SQL arbitrario. Toda respuesta correcta tiene la forma { "data": [...], "meta": {...} }; todo error es un mensaje simple, seguro y legible por humanos (sin SQL, rutas de archivo ni trazas de pila), marcado con isError: true.
Tool | Respuestas | Parámetros clave |
| «Muéstrame todas las tablas y qué contienen». | (ninguno) |
| «¿Cuántos clientes son de Alemania?» |
|
| «¿Qué país tiene más clientes?» |
|
| «¿Quién ha gastado más dinero?» |
|
| «¿Cuáles son los 5 productos más vendidos?» |
|
| «¿Cuáles son las 3 categorías con mayores ingresos?» |
|
| «¿Cuántos ingresos generamos en 2025?» |
|
| «¿Qué cliente realizó más pedidos?» |
|
from/to se escriben como YYYY-MM-DD y definen un intervalo UTC semiabierto [from, to); from debe ser estrictamente anterior a to. Todas las métricas financieras y de recuento excluyen los pedidos con estado cancelled. Los contratos completos por herramienta (formas exactas de las respuestas, reglas de desempate) están en SPEC.md §4.
Seguridad
Tres capas independientes y de defensa en profundidad garantizan que la base de datos nunca se modifique, ni siquiera ante un prompt adversarial como «Elimina todos los pedidos cancelados»:
La conexión SQLite se abre con
readOnly: true.PRAGMA query_only = ONse establece inmediatamente después de abrir la conexión.Un
authorizerde SQLite deniega explícitamente toda acción de escritura/DDL (INSERT,UPDATE,DELETE,DROP,ALTER,CREATE,ATTACH,DETACH, transacciones, ...).
Además, ninguna herramienta acepta SQL en bruto, nombres de tablas ni nombres de columnas: cada consulta es una sentencia preparada fija, y todas las entradas se validan con zod y se pasan como parámetro enlazado, nunca mediante interpolación de cadenas.
Base de datos
shop.db se genera a partir de database/schema.sql con un script de generación de datos determinista: volver a ejecutarlo produce datos idénticos byte a byte en cada ejecución (semilla PRNG fija, sin dependencia del reloj):
npm run seed # builds, then (re)writes ./shop.db from schema.sql + the seed scriptEl script de generación también comprueba, en el momento de generar los datos, que el conjunto no tenga clasificaciones ambiguas (p. ej., un único país líder, un único mayor gastador) y que los ingresos de 2025 no sean cero — consulta SPEC.md §3.
Desarrollo
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 # bothEste proyecto se construyó con TDD: para cada módulo se escribió primero una prueba que fallaba y luego la implementación, herramienta por herramienta. La suite de integración cubre los 8 escenarios de aceptación de extremo a extremo, entradas con forma de inyección SQL, combinaciones de parámetros inválidas, y comprueba que el hash SHA-256 del archivo de la base de datos no cambia tras cada ejecución.
Estructura del proyecto
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-