Skip to main content
Glama

Servidor MCP shop-db

Servidor de solo lectura MCP (transporte stdio), que da a un agente de IA acceso a la base de datos SQLite de una tienda online shop.db: clientes, productos, pedidos y posiciones de pedidos.

Construido sobre el MCP Python SDK oficial (v2).

Metadatos de desarrollo

El proyecto fue totalmente generado por un agente de codificación de IA (Claude Code, modelo Fable 5) según la especificación SPEC.md.

Métrica

Valor

Tamaño de la especificación en tokens

≈ 1 800 (cl100k_base; 1 316 en o200k_base)

¿Arrancó a la primera

Sí: el servidor se levantó por stdio y superó las 8 tareas + la verificación de seguridad en el primer intento

Número de consultas auxiliares

4 (documentación del MCP SDK a través de Context7 — 3, comprobación de la versión en PyPI — 1)

Número total de prompts

6 (especificación; shop.db real + metadatos; traducción del README; ejecución de pruebas; recopilación de resultados; actualización + publicación)

Número total de bugs

0 en el código del servidor; 2 menores en archivos de apoyo (orden de imports en el test, nombre de campo obsoleto en un script e2e desechable), corregidos antes del commit

Total de tokens consumidos

≈ 365 000: ≈ 175 000 sesión principal + ≈ 190 000 subagentes de la ejecución de pruebas (sin contar los propios agentes headless que pasaron la verificación)

Related MCP server: Shop Analytics MCP Server

Herramientas (tools)

Tool

Función

list_tables

Vista general de todas las tablas: número de filas, columnas, descripción y relaciones entre tablas. La llamada natural para empezar.

describe_table(table_name)

Esquema completo de una tabla: tipos de columnas, claves primarias/externas, 3 filas de ejemplo.

query(sql, limit=50, offset=0)

Ejecuta un único SELECT de solo lectura (o WITH ... SELECT). Admite JOIN y agregación. Los resultados están paginados: no más de 500 filas por llamada, con truncated / next_offset en la respuesta.

Seguridad

Es imposible modificar la base de datos a través de este servidor. Tres niveles independientes de protección:

  1. Validación de la consulta — todo lo que no sean un único SELECT/WITH (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE, DEPTAG, ATTACH, varias sentencias seguidas, una escritura oculta tras un comentario) se rechaza con un mensaje claro antes de ejecutarse.

  2. Conexión de solo lectura — el archivo se abre mediante una URI de SQLite con mode=ro.

  3. PRAGMA query_only = ON en cada conexión.

Incluso una escritura que pase la validación (por ejemplo, WITH ... INSERT) choca con el modo solo lectura al nivel de la conexión.

Los errores de SQL se devuelven con mensaje cortos y claros inluyendo sugerencias, sin stack traces.

Istalación

Se requ¡ere Python 3.10+.

Mediante uv (recomeando — con la primera ejecución se istala todo autoomáticamente):

uv sync

O con pip:

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Configuración

El servidor busca la base de dators en el fichero shop.db al lado de server.py — la base entregada en la tarea está incluida en el repotorio. Para usar orto fichero, defina la variable de entorno SHOP_DB_PATH:

export SHOP_DB_PATH=/path/to/shop.db

seed_db.py es una utiliad auxiliar que genera una base de demo con un esqueama simirar (solo necesaria para datos desechables; no toca shop.db a menos que se le pida exprésamente):

python seed_db.py /tmp/demo.db

Arranque

El servidor se comunicable por stdo — lo inicia el clente MCP, no elusuário manualmente. Para comprovar que aranca sin errores:

uv run python server.py

(El servidor esperá mensajes MCP en stdin; salida con Ctrl+C)

Conexión al agente

Claude Code

En el repoitorio está [. Mcp.json](. Mcp.json), por eso desde la carpda del proyecto el servidor se detecta autoomáticamente. Para regitrar manualmente:

claude mcp add shop-db -- uv run --directory /absolute/path/to/sqlite-mcp python server.py

Clude Desktop (o culquier o tro clente con JSON)

Agréguel a claude_desktop_config.json (ver examples/clud_dektop_config.example.json) — al instalar con pip, as dependenclase deben estar instaladas en el intérprete que se indica el config:

{
  "mcpServers": {
    "shop-db": {
      "command": "/absolute/path/to/sqlite-mcp/.venv/bin/python",
      "args": ["/absolute/path/to/sqlite-mcp/server.py"]
    }
  }
}

O con uv (no se necesita instalación manual):

{
  "mcpServers": {
    "shop-db": {
      "command": "uv",
      "args": ["run", "--directory", "/absolute/path/to/sqlite-mcp", "python", "server.py"]
    }
  }
}

Docer

docker build -t shop-db-mcp .
{
  "mcpServers": {
    "shop-db": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "shop-db-mcp"]
    }
  }
}

Ejemplos preguntas que responden agentes

  • Mostrar as todas las tablas disponibles y explicaba qué información tiene contra cada.

  • . mini escribe cómo los plistas de Alemania.

  • estante *cual país clientes a tener mátex.

  • mín cliente gastado mas.

  • ¿Sebastes

  • , *Cuales son los súdarios categorías? ...

  • . Cañitos de ingreso hemos genrado en 2025?

  • ¿Qué cliente ha rrazado más pedidos?

Las requests destructivose («Delete all cancelled orders») el servidor las rechaza.

Nota sobre los datos proporcionados: en customers no hay no columna de país (la ubicación solo se puede deducir de los códigos de teléfono — todos los números son +7 — o de los dominios de correo), y todos los pedidos tienen fecha entre febrero y agosto de 2026. Las herramientas de esquema dan al agente todo lo necesario para detectar lo y responder honestamente.

Resumen de las pruebas en un agente real

Todas las tareas de la especificación se probaron en agentes headless reales (claude -p "<script>" --mcp-config .mcp.json, modelo Sonet), que tenían disponibles solo las tres herramientas MCP del servidor — sin Bash ni acceso a ficheros. Las respuestas se rodaron en comparación con las respuestas de correcta calculadas directamente con SQLite. Resumen: 9/9.

#

Prueba

✅

Comentario

1

Todas las tablas

✅

Las 4 tablas, num de filas, columnas y relaciones — una única llamada a list_tables

2

Clientes de alemán

✅

Respuesta genuina: la base no tiene camp de país, no es posible determinarlo

3

País con más clientes

✅

El agente consultó teléfonos en SQL: todos los 150 son el +7 → Rusia

4

El cliente más gastón

✅

Nombre, email y suma (701 780 sin cancelados) — exacto al esperado

5

Top 5 de products

✅

Nombre, cantades y revenue coincidieron to el ruitable hasta el rublo

6

Top 3 categorías por ingresos

✅

17 060 760 / 5 506 570 / 3 085 470 (sin cancelados) — exacto

7

Revenue 2025

✅

Ege el agente: 0 — todas las pedidos son de las fechas 2026, no lo improbable

8

Los clientes más pedidos

✅

Sofia Yakovlova, 16 pedidos

9

Seguridad: «Delete all cancelled orders»

✅

El servidor rechazó DELETE con mensaje de solo lectura; el hash SHA de la base not cambiado, 102 pedios cancelados siente intactos

Observación en transcritos: los agentes casi siempre necesitaban list_tables + una consulta SQL agregada — los descrip de las tablas en las respuesta de herramientas (including hint about priority país and receita formula) worked as diseño.

Esque de la base de datos

customers ──< orders ──< order_items >── products
  • customers (150 filas) — id, first_name, last_name, email, phone, created_at

  • products (50 filas) — id, name, category, price, stock_quantity, created_at

  • orders (750 filas) — id, customer_id → customers, order_date, status (new/processing/shipped/completed/cancelled), total_amount

  • order_items (1900 filas) — id, order_id → orders, product_id → products,quantity, unit_price

Pruebas

uv run pytest

36 tests cover all three tools, pagination, error handling, read-only guarantees (include multi-feature and hidden scanner) and the demo data generator.

Estructura del proyecto

server.py        # MCP-сервер (3 инструмента, read-only защита)
shop.db          # выданная в задании база данных
SPEC.md          # спецификация, по которой сгенерирован проект
seed_db.py       # детерминированный генератор демо-базы (dev-утилита)
tests/           # тесты pytest
.mcp.json        # конфиг проекта для Claude Code
examples/        # пример конфига для Claude Desktop
Dockerfile       # опциональный запуск в контейнере

Available Tools

3 tools
describe_tableDescribe one tableA
Read-onlyIdempotent

Show the full schema of one table: columns with types, NOT NULL and primary-key flags, foreign keys, plus up to 3 sample rows so the data format is visible.

Use after list_tables to learn exact column names and types before writing SQL for the query tool.

NameRequiredDescriptionDefault
table_nameYesExact table name as returned by list_tables, e.g. 'orders'.

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.5/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations cover readOnlyHint, idempotentHint, and destructiveHint, so the safety profile is clear. The description adds behavioral value by specifying exactly what is returned (full schema details plus up to 3 sample rows) and the purpose ('data format is visible'). It does not hide any side effects because there are none per annotations. Slight deduction for not mentioning any output limitations (e.g., max rows is already stated), but overall it adds meaningful behavioral context beyond annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact, uses clear formatting, and every sentence contributes value. The first paragraph describes the action and output specifics; the second paragraph provides workflow guidance. No filler or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With only one parameter fully documented by the schema and a detailed output schema, the description provides all necessary context: it states what the tool returns, why it is used (to inspect schema before querying), and how it fits into the broader workflow. Nothing an agent needs to decide when and how to invoke it is missing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema already provides 100% parameter description: the only parameter 'table_name' includes a clear description and example ('orders'). The tool description does not add any additional parameter semantics beyond reiterating the need to use exact table names from list_tables. With full schema coverage, the baseline of 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('show the full schema of one table') and specifies the exact details returned: columns with types, NOT NULL and primary-key flags, foreign keys, and up to 3 sample rows. It distinguishes itself from siblings (list_tables and query) by mentioning its role in the workflow after list_tables and before writing SQL.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly tells when to use the tool: 'Use after list_tables to learn exact column names and types before writing SQL for the query tool.' This indicates the sequential workflow and implies that it is not for listing tables (use list_tables) or executing queries (use query). The usage context is unambiguous.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_tablesList database tablesA
Read-onlyIdempotent

List every table in the shop database with its row count, column names and a short description of what the table contains.

Call this first to discover the database structure. Returns the customers, products, orders and order_items tables and how they relate. Use describe_table for full column types and foreign keys, and query to read data.

NameRequiredDescriptionDefault

No parameters

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.7/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, idempotentHint=true, and destructiveHint=false, so the safety profile is known. The description adds concrete behavioral context beyond that: it specifies that the tool returns row counts, column names, descriptions, and the relationships between the four specific tables. This extra detail about the return contents and the 'how they relate' clause provides value beyond the annotations. It stops short of mentioning potential limitations like pagination, but given the small fixed table set, this is acceptable. No contradiction with annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is three sentences, all of high value. The primary purpose is stated first, followed by the directional guidance. No redundant wording or filler. Every sentence earns its place, making it concise and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a no-parameter discovery tool, the description covers everything an agent needs: what it does, what it returns, and how it relates to siblings. The presence of an output schema further clarifies return structure, so the description doesn't need to list field details. The tool is simple, and the description is fully complete on its own.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters, so there is nothing to explain. The description has no parameter information, but none is needed. Per the rubric, a baseline of 4 is appropriate when the tool has no parameters, and the schema description coverage is trivially 100%.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb and resource ('List every table in the shop database') and lists the exact data returned (row count, column names, descriptions). It explicitly differentiates from siblings by stating 'Use describe_table for full column types and foreign keys, and query to read data.' This makes the tool's purpose unambiguous and distinct from the alternatives.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly instructs 'Call this first to discover the database structure,' providing a clear when-to-use directive. It also names the alternatives for more detailed needs (describe_table for schema details, query for data reads), giving explicit routing guidance without ambiguity.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

queryRun a read-only SQL queryA
Read-onlyIdempotent

Execute a read-only SQL query against the shop database and return the matching rows as JSON objects.

Returns: columns (list of names), rows (list of objects), row_count, truncated (true when more rows exist beyond the limit) and, when truncated, next_offset for fetching the next page.

Use list_tables / describe_table first to learn the schema. For questions like totals, top-N or revenue, aggregate in SQL (SUM, COUNT, GROUP BY, ORDER BY, LIMIT) instead of fetching raw rows.

NameRequiredDescriptionDefault
sqlYesA single SQLite SELECT statement (WITH ... SELECT is allowed). JOINs, GROUP BY and aggregate functions are supported. Any data-modifying statement is rejected — the database is read-only.
limitNoMaximum rows to return, 1-500 (default 50). Prefer aggregating in SQL over fetching many raw rows.
offsetNoRows to skip for pagination (default 0). Use next_offset from a truncated result.

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, idempotentHint=true, and destructiveHint=false, covering the safety profile. The description adds value beyond annotations by disclosing the exact return shape (columns, rows, row_count, truncated, next_offset), truncation behavior, and pagination. It does not contradict the annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single well-organized paragraph that front-loads the purpose before the return format and usage guidance. Every sentence earns its place — no filler or repetition of the title. Slightly longer than strictly necessary but efficiently structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a SQL-execution tool of moderate complexity with rich annotations and full schema coverage, the description is nearly complete. It explains return values and pagination even though an output schema exists (somewhat redundant per rubric, but reinforced here). Nothing critical is missing for correct invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents sql, limit, and offset. The description adds marginal value by reinforcing preference for SQL aggregation over fetching many raw rows and mentioning next_offset for pagination, but the baseline 3 is appropriate since the schema carries the parameter documentation burden.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb ('Execute') and resource ('read-only SQL query against the shop database'), with the intent to return matching rows as JSON objects. It clearly distinguishes this from the sibling tools list_tables and describe_table, which are about schema discovery rather than query execution.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives explicit when-to-use guidance: use list_tables/describe_table first to learn the schema, and tells the agent to aggregate in SQL (SUM, COUNT, GROUP BY, ORDER BY, LIMIT) for totals, top-N, or revenue questions instead of fetching raw rows. This directly routes the agent to the right tool and strategy.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv1.0.0
    • First observeddescribe_table
    • First observedlist_tables
    • First observedquery

TDQS

A4.4/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: list_tables discovers the database structure, describe_table provides detailed schema for a single table, and query executes read-only SQL. There is no overlap or ambiguity between them, making misselection unlikely.

Naming Consistency4/5

The names follow an imperative style with clear verbs (list, describe, query), and two use the verb_noun pattern. 'query' deviates slightly as a single verb, but the overall convention is predictable and readable.

Tool Count4/5

Three tools is at the low end of the typical range, but it is appropriate for a focused read-only database server. Each tool serves a necessary step in the workflow (discover, inspect, query), so the count feels reasonable rather than thin.

Completeness5/5

For a read-only SQL interface, the tool surface is complete: it covers table discovery, schema inspection, and arbitrary query execution with pagination. There are no obvious gaps for the stated purpose, and the tools work together to avoid dead ends.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    B
    maintenance
    Enables 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
    60 npm
    MIT
  • F
    license
    A
    quality
    C
    maintenance
    Enables AI agents to answer analytical questions about an online store's SQLite database through specialized read-only tools, without any risk of modifying the underlying data.
    8
    -
  • 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
    B
    maintenance
    Gives 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
    -