Skip to main content
Glama
harutlc

SQL MCP Server

by harutlc

SQL MCP Server

Un servidor Model Context Protocol (MCP) con IA que te permite consultar y analizar una base de datos SQLite de comercio electrónico usando lenguaje natural.

Haz preguntas como:

  • "¿Quiénes son nuestros 5 mejores clientes por gasto total?"

  • "Muestra todos los productos de la categoría Electrónica con stock inferior a 50"

  • "¿Cuál fue nuestro ingreso total por pedidos completados en 2026?"

Cuatro herramientas, tres de las cuales no necesitan ninguna clave API. Solo lectura en dos niveles independientes, resultados paginados, el texto de error propio de SQLite se devuelve al llamador, y 74 pruebas automatizadas.

Contenido — Inicio rápido · Configurar un proveedor · Herramientas · Paginación · Errores · Pruebas · Docker · Clientes MCP · Configuración · Seguridad · Salida de datos · Estructura del proyecto


🚀 Inicio rápido

1. Requisitos previos

  • Node.js: v22.5.0 o superior (para el módulo integrado node:sqlite); se recomienda v24

  • npm: v11.0.0 o superior

2. Instalación

Clona este repositorio e instala las dependencias:

npm install
cp .env.example .env
npm run build

Eso es suficiente para conectar el servidor a un cliente y usar list_tables, describe_table y execute_sql. Solo se necesita un proveedor para la herramienta de lenguaje natural — ver más abajo.


Related MCP server: shop-db MCP Server

🔑 Configura tu proveedor de IA

Abre el archivo .env y configura tu modelo de IA preferido. El servidor detecta automáticamente tu proveedor según las variables que establezcas:

Opción A: Anthropic Claude (Recomendado)

ANTHROPIC_API_KEY=sk-ant-api03-...
ANTHROPIC_MODEL=claude-opus-5

Opción B: Ollama local (Gratis y sin conexión)

OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=llama3.2

Nota: Asegúrate de que Ollama esté en ejecución (ollama serve) y de haber descargado el modelo (ollama pull llama3.2).

Opción C: OpenAI

OPENAI_API_KEY=sk-proj-...
OPENAI_MODEL=gpt-4o-mini

Opción D: Personalizado / Terceros (Groq, DeepSeek, OpenRouter)

OPENAI_API_KEY=your_api_key
OPENAI_BASE_URL=https://api.groq.com/openai/v1
OPENAI_MODEL=llama-3.3-70b-versatile

🛠 Herramientas disponibles

Tres de las cuatro hablan directamente con SQLite — sin clave API, sin costo, al instante:

Herramienta

Qué hace

Necesita un proveedor

list_tables

Cada tabla con una explicación en lenguaje sencillo de qué contiene, su número de filas y columnas, además de las relaciones entre tablas y la convención de ingresos que usa esta base de datos.

No

describe_table

Una tabla completa: columnas con tipos, claves y descripciones, claves foráneas, la sentencia CREATE TABLE, advertencias y el rango de fechas que realmente cubren las columnas de fecha.

No

execute_sql

Cualquier SELECT de solo lectura, devolviendo filas JSON estructuradas y nombres de columnas. Admite paginación con limit / offset. Esta es la herramienta a usar para trabajo analítico que quieras controlar tú mismo.

No

query_database

Toma una pregunta en lenguaje natural, genera y ejecuta el SQL apropiado, y devuelve una respuesta escrita con información.

Sí

La descripción de cada herramienta le dice al agente llamador no solo qué hace, sino cuándo no usarla — query_database indica que devuelve prosa en lugar de valores, cuesta dinero y hace dos llamadas a la LLM, y señala a execute_sql para cualquier cosa que el agente pretenda calcular. Ambas herramientas indican el límite de filas y la convención de ingresos en línea, para que el agente no tenga que descubrirlos por prueba y error.

Ejemplo: describe_table

// describe_table { "table_name": "orders" } — abridged
{
  "table": "orders",
  "purpose": "Order headers — one row per order placed by a customer, carrying its date, lifecycle status and total.",
  "rowCount": 750,
  "columns": [
    { "name": "status", "type": "TEXT", "primaryKey": false, "notNull": true, "default": null,
      "description": "Lifecycle stage, one of: new, processing, shipped, completed, cancelled. Determines whether the order counts as revenue." }
  ],
  "foreignKeys": [
    { "column": "customer_id", "referencesTable": "customers", "referencesColumn": "id", "onDelete": "CASCADE" }
  ],
  "notes": ["Revenue convention: count every order whose status is not 'cancelled' …"],
  "dataCoverage": { "order_date": { "min": "2026-02-17 18:53:30", "max": "2026-08-22 17:06:30" } },
  "createStatement": "CREATE TABLE orders ( … )"
}

dataCoverage está ahí para que un agente pueda distinguir un resultado vacío de una pregunta fuera de rango: preguntar por 2025 devuelve "los datos van de … a …" en lugar de un cero desnudo que parezca un error.


📄 Paginación de resultados grandes

Cada resultado está limitado — a DATABASE_MAX_ROWS (por defecto 100), o a un limit menor que pases. Un limit mayor se ajusta en lugar de rechazarse, por lo que un llamador siempre recibe filas.

execute_sql acepta limit y offset y te dice si hay más:

// execute_sql { "sql": "SELECT id, name FROM products ORDER BY id", "limit": 2, "offset": 2 }
{
  "columns": ["id", "name"],
  "rows": [
    { "id": 3, "name": "Ноутбук UltraBook 15" },
    { "id": 4, "name": "Умные часы FitWatch" }
  ],
  "rowCount": 2,
  "offset": 2,
  "hasMore": true,
  "nextOffset": 4,
  "note": "More rows matched than were returned. Call again with offset=4 for the next page.",
  "executionTimeMs": 0.09
}

Sigue llamando con offset: nextOffset hasta que hasMore sea false. Cuando un resultado cabe en una página, hasMore es false y totalAvailableRows informa el total real.

El límite se aplica mientras se recorre la sentencia, no recortando un resultado terminado: el servidor se detiene una fila después del límite y nunca materializa el resto. El SQL es generado por el modelo, por lo que una unión cruzada accidental podría traer millones de filas a la memoria antes de descartar alguna. La paginación también se realiza durante la iteración en lugar de añadir LIMIT/OFFSET al SQL, lo que tendría que sobrevivir a lo que ya termine la sentencia generada.

query_database comparte el límite de filas pero no pagina — resume en prosa, donde un número de página no tiene a qué adjuntarse. Usa execute_sql para cualquier cosa mayor que una página.


🚦 Cómo se ve un error

Los fallos vuelven como resultados normales de herramientas MCP con isError: true y un mensaje sobre el que el agente llamador puede actuar, en lugar de fallos a nivel de transporte.

Lo que envías

Lo que recibes

SELECT nope FROM products

Query execution failed: no such column: nope

DELETE FROM orders

Only read-only queries are permitted. A statement must begin with SELECT, WITH or VALUES, but this one begins with "DELETE".

SELECT 1; SELECT 2

Only a single SQL statement may be executed. Multiple statements were provided.

describe_table {"table_name": "custmers"}

No table named "custmers". Available tables: customers, order_items, orders, products.

Una solicitud en lenguaje natural para borrar datos

This request asks to modify the database, which is not permitted … No changes were made. You can still ask about the same records: …

Dos reglas gobiernan ese texto:

  • El mensaje propio de SQLite se conserva. "no such column: nope" es lo más útil que se le puede decir a un agente, porque es suficiente para reescribir la consulta y reintentar. Nunca se aplana a "consulta fallida".

  • El detalle del host nunca escapa. Los errores no reconocidos — que pueden llevar un seguimiento de pila — se colapsan a una línea genérica, y todo lo que sale se limpia de la ruta de la base de datos, la raíz del proyecto y el directorio personal. El detalle completo permanece en los registros del servidor. Esto está cubierto por su propio archivo de prueba.


🧪 Pruebas automatizadas

npm test          # 74 tests across 4 files, runs in well under a second
npm run test:watch
npm run typecheck

node --test simple con tsx — sin dependencia de framework de pruebas. Las suites se ejecutan contra la base de datos real db/shop.db, no un simulacro, por lo que fallan si el esquema y la documentación se separan.

Archivo

Cubre

tests/sql-guard.test.ts

Cada forma en que una escritura podría colarse más allá del guardián de solo lectura: comentarios iniciales, WITH x AS (…) DELETE, sentencias apiladas, DML encerrado en bloques de código Markdown. Además lo contrario — que replace(), una palabra clave dentro de un literal de cadena y un identificador entre comillas nombrado como una palabra clave no se rechacen.

tests/database.test.ts

Límite de filas, paginación con offset, un offset más allá del final, una unión cruzada descontrolada que no debe materializarse, nombres de columnas en un resultado vacío, escrituras rechazadas que dejan la base de datos sin cambios, el mensaje de SQLite sobreviviendo.

tests/errors.test.ts

Lo que un llamador puede ver: los mensajes accionables pasan, los errores desconocidos se colapsan, y la ruta de la base de datos / raíz del proyecto / directorio personal se redactan de ambos.

tests/schema-metadata.test.ts

Que cada tabla y columna en la base de datos en vivo tenga una descripción escrita, que ninguna descripción se refiera a una tabla que ya no existe, y que la convención de ingresos esté declarada.

La suite del guardián es la más importante: es el límite que hace que "solo lectura" sea verdadero en lugar de meramente intencionado, y uno de sus casos es un falso positivo real que detectó durante el desarrollo.


🐳 Docker

docker build -t sql-mcp .

La imagen incluye la base de datos, por lo que no necesita montar un volumen. Como este es un servidor stdio, debe ejecutarse con -i y sin TTY — la entrada y salida estándar del contenedor transportan el flujo JSON-RPC:

docker run -i --rm -e ANTHROPIC_API_KEY sql-mcp

Conéctalo a un cliente con examples/claude_desktop_config.docker.json. Elimina el -e ANTHROPIC_API_KEY para ejecutarlo sin credenciales — list_tables, describe_table y execute_sql funcionan sin proveedor.

La construcción es de múltiples etapas: TypeScript se compila en un constructor node:24-alpine, y solo dist/, db/ y las dependencias de producción se copian a la imagen de ejecución. Se ejecuta como el usuario no privilegiado node, nunca se copia ningún .env (las credenciales vienen de -e), y no hay complementos nativos que compilar porque SQLite viene dentro del propio Node.


🔌 Conexión a clientes MCP

Los archivos de configuración listos para usar están en examples/ — copia el que coincida con tu cliente y reemplaza la ruta. examples/claude_desktop_config.no-api-key.json ejecuta el servidor sin credenciales en absoluto, lo que es suficiente para list_tables, describe_table y execute_sql.

Configuración de Claude Desktop

Añade este servidor a tu archivo de configuración de Claude Desktop (claude_desktop_config.json):

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

(Asegúrate de ejecutar npm run build una vez antes de conectar)

Ejemplo 1: Anthropic Claude (Predeterminado)

{
  "mcpServers": {
    "sql-mcp": {
      "command": "node",
      "args": ["/absolute/path/to/sql-mcp/dist/index.js"],
      "env": {
        "ANTHROPIC_API_KEY": "sk-ant-api03-your-key-here",
        "ANTHROPIC_MODEL": "claude-opus-5"
      }
    }
  }
}

Ejemplo 2: Ollama local (Gratis y sin conexión)

{
  "mcpServers": {
    "sql-mcp": {
      "command": "node",
      "args": ["/absolute/path/to/sql-mcp/dist/index.js"],
      "env": {
        "OLLAMA_BASE_URL": "http://localhost:11434",
        "OLLAMA_MODEL": "llama3.2"
      }
    }
  }
}

Ejemplo 3: OpenAI

{
  "mcpServers": {
    "sql-mcp": {
      "command": "node",
      "args": ["/absolute/path/to/sql-mcp/dist/index.js"],
      "env": {
        "OPENAI_API_KEY": "sk-proj-your-key-here",
        "OPENAI_MODEL": "gpt-4o-mini"
      }
    }
  }
}

Ejemplo 4: Personalizado / Groq / OpenRouter / DeepSeek

{
  "mcpServers": {
    "sql-mcp": {
      "command": "node",
      "args": ["/absolute/path/to/sql-mcp/dist/index.js"],
      "env": {
        "OPENAI_API_KEY": "gsk_your_groq_api_key",
        "OPENAI_BASE_URL": "https://api.groq.com/openai/v1",
        "OPENAI_MODEL": "llama-3.3-70b-versatile"
      }
    }
  }
}

El servidor resuelve db/shop.db relativo a su propia ubicación, por lo que DATABASE_PATH no es necesario en ninguno de estos — los clientes MCP lanzan servidores desde un directorio de trabajo de su elección, y el servidor no depende de él.


🔎 Probarlo localmente

Prueba instantánea en terminal

Puedes probar preguntas en lenguaje natural directamente en tu terminal:

npm run query -- "Show top 3 products by price"

Inspector web visual

Prueba las herramientas de forma interactiva en tu navegador usando el Inspector MCP oficial:

npm run inspect:dev
  1. Abre la URL del inspector en tu navegador (por ejemplo, http://localhost:5173).

  2. Haz clic en Conectar.

  3. En Herramientas, selecciona query_database, ingresa tu pregunta y haz clic en Ejecutar herramienta.

Todos los scripts de npm

Script

Función

npm run build / npm run clean

Compilar a dist/ · eliminarlo

npm start

Ejecutar el servidor compilado sobre stdio

npm run dev

Ejecutar desde el código fuente con recarga (tsx watch)

npm test / npm run test:watch

Pruebas automatizadas

npm run typecheck

tsc --noEmit

npm run query -- "…"

Hacer una pregunta desde la terminal

npm run inspect / npm run inspect:dev

MCP Inspector contra dist/ · contra el código fuente


🔧 Referencia de configuración

Todas las variables son opcionales; los valores predeterminados son los que se usan si no configuras nada.

Variable

Valor predeterminado

Propósito

DATABASE_PATH

db/shop.db

Ubicación de la base de datos. Absoluta o relativa a la raíz del proyecto, nunca al directorio de trabajo.

DATABASE_MAX_ROWS

100

Límite máximo de filas devueltas por llamada y de filas enviadas al LLM. El limit de execute_sql solo puede reducirlo.

LLM_TIMEOUT_MS

60000

Tope por solicitud para las llamadas al LLM. Una pregunta hace dos llamadas secuenciales, así que sin esto un proveedor bloqueado cuelga la llamada a la herramienta.

LLM_PROVIDER

detección automática

anthropic | ollama | openai | custom. Normalmente se infiere de qué claves configuras.

ANTHROPIC_API_KEY / ANTHROPIC_MODEL

— / claude-opus-5

Proveedor Anthropic.

OPENAI_API_KEY / OPENAI_MODEL / OPENAI_BASE_URL

— / gpt-4o-mini / OpenAI

OpenAI y cualquier endpoint compatible con OpenAI.

OLLAMA_BASE_URL / OLLAMA_MODEL

http://localhost:11434 / llama3.2

Ollama local.

DEBUG

sin definir

sql-mcp:*, o un solo espacio de nombres: server, query-engine, database, llm, tools.

Un valor mal formado se notifica en stderr y se recurre al valor predeterminado en lugar de aceptarse en silencio: un error tipográfico en el bloque env de un cliente aparece al iniciar en lugar de comportarse como si la variable nunca se hubiera definido. Los registros de DEBUG incluyen cada pregunta formulada y cada sentencia generada, y bajo un cliente MCP terminan en los archivos de registro persistentes del cliente, así que permanecen desactivados salvo que optes por activarlos.


🔒 Seguridad

La base de datos se abre en modo solo lectura a nivel del controlador, y cada sentencia se valida antes de ejecutarse: debe ser una única sentencia SELECT/WITH/VALUES, sin ninguna palabra clave que escriba datos, altere el esquema o cambie el estado de la conexión. Ninguna de las dos comprobaciones puede desactivarse mediante configuración. Una solicitud como "eliminar todos los pedidos cancelados" se rechaza en lugar de ejecutarse.

El validador trabaja sobre una vista tokenizada de la sentencia en lugar del texto bruto, por lo que los comentarios, los literales de cadena y los identificadores entre comillas no pueden usarse para ocultar una palabra clave: /* c */ DELETE FROM orders y WITH x AS (SELECT 1) DELETE FROM orders se rechazan ambos, mientras que SELECT replace(name, 'a', 'b') no se rechaza.

El texto que este servidor no ha escrito — tu pregunta y los valores leídos de la base de datos — se delimita en los prompts con un marcador infalsificable por solicitud, de modo que un producto llamado Widget (SYSTEM: ignore prior instructions…) no pueda escapar al contexto de instrucciones. Eso importa más allá de este proceso: la respuesta viaja de vuelta al agente que llama como salida de la herramienta, un salto más allá.


🔐 Qué se envía y adónde

Este servidor responde preguntas llamando a un LLM, así que el contenido de la base de datos sale de tu máquina en cada llamada a query_database. Concretamente, cada llamada envía:

  1. El esquema de tu base de datos — nombres de tablas, nombres y tipos de columnas, y recuentos de filas — para generar el SQL.

  2. Las filas que devolvió la consulta (hasta DATABASE_MAX_ROWS, 100 por defecto) — para convertirlas en una respuesta escrita.

En la base de datos de tienda incluida, esas filas incluyen nombres de clientes, direcciones de correo electrónico y números de teléfono. Van al proveedor que configures, en el endpoint que nombre OPENAI_BASE_URL — que para Groq, OpenRouter o DeepSeek es un tercero bajo sus propios términos.

Si eso no es aceptable para tus datos:

  • Usa las otras tres herramientas. list_tables, describe_table y execute_sql no hacen ninguna llamada de red — nada sale de la máquina.

  • Usa Ollama. Se ejecuta localmente, así que nada sale de la máquina.

  • Restringe las consultas. Las preguntas agregadas ("ingresos por categoría") devuelven filas de resumen en lugar de registros de clientes.

  • Reduce DATABASE_MAX_ROWS para limitar cuántos datos de filas se envían por consulta.

El servidor nunca envía el archivo de la base de datos, y solo puede leer — consulta Seguridad.


📁 Estructura del proyecto

src/
  index.ts                  MCP server entry point (stdio transport)
  cli.ts                    Terminal harness: npm run query -- "…"
  config/                   Env parsing, provider detection, path resolution
  tools/                    The four MCP tools and their descriptions
  services/
    database.service.ts     SQLite access, row capping, paging, introspection
    sql-guard.ts            Read-only enforcement (tokenizing validator)
    errors.ts               Caller-safe messages, path redaction
    schema-metadata.ts      Human-written meaning the schema cannot record
    query-engine.service.ts NL → SQL → execute → prose pipeline
    llm/                    Anthropic / OpenAI / Ollama behind one interface
  prompts/                  SQL generation, humanization, untrusted-input framing
tests/                      node --test suites (see Automated Tests)
db/                         shop.db and its schema documentation
docs/                       Architecture and sequence diagrams
examples/                   Ready-to-paste client configurations

📚 Documentación técnica

Available Tools

4 tools
describe_tableDescribe a Database TableA

Returns everything about one table: its purpose, every column with type, nullability, primary key and a plain-language description, its foreign keys, its CREATE TABLE statement, caveats worth knowing before querying it, and — for date columns — the range the data actually covers, so you can tell an empty result from an out-of-range question. Use it before writing SQL against a table you have not queried yet. Reads SQLite directly: no LLM call, no API key. Returns JSON.

ParametersJSON Schema
NameRequiredDescriptionDefault
table_nameYesExact table name, as returned by list_tables (e.g. 'orders', 'order_items').

TDQS

A4.2/5.0
Behavior4/5

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

With no annotations provided, the description carries the full disclosure burden. It states execution mechanics ('Reads SQLite directly'), that no external dependency exists ('no LLM call, no API key'), and the return format ('Returns JSON'). It also explains a non-obvious behavior — returning real data coverage ranges for date columns so empty results can be distinguished from out-of-range questions. The 'describe' verb implies read-only; the description could state non-mutating explicitly but the disclosed details exceed the baseline for an annotation-less tool.

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?

Three sentences, each earning its place: deliverable list, when-to-use, and execution/return format. The content list is front-loaded ahead of the usage guidance. It is information-dense rather than wasteful, though the long enumerative first sentence could be tightened slightly.

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?

There is no output schema, so the description bears full responsibility for explaining return content — it enumerates all major elements including the non-obvious date-range feature. One fully-documented parameter, usage routing against siblings, execution behavior, and return format are all specified. Nothing an agent needs to call it correctly 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?

Schema description coverage is 100% for the single table_name parameter, which the schema already documents as 'Exact table name, as returned by list_tables (e.g. 'orders', 'order_items').' With full schema coverage the baseline is 3; the description adds no parameter-specific detail beyond hinting that the table must exist (it describes 'one table'). The schema does the heavy lifting, so 3 is correct.

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 names a specific verb-resource pair ('Returns everything about one table') and enumerates the exact contents delivered: columns with type/nullability/PK/plain-language, foreign keys, CREATE TABLE, caveats, and date range coverage. It clearly differentiates from siblings — it describes schema rather than querying data (query_database, execute_sql) or listing tables (list_tables).

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

Usage Guidelines4/5

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

The description gives explicit when-to-use instruction: 'Use it before writing SQL against a table you have not queried yet.' This frames it as a prerequisite step and implies the alternative is the SQL/query tools, though it does not name them explicitly or state when-not-to-use. Clear context, slightly implicit on exclusions.

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

execute_sqlRun a Read-Only SQL QueryA

Runs a single read-only SQL query against the e-commerce SQLite database and returns structured rows plus column names as JSON. Use this to answer analytical questions yourself — joins, aggregates, multi-step work — and when you need the actual values rather than a written summary. Call list_tables and describe_table first if you do not know the schema.

LIMITATIONS: SELECT only. The statement must be a single SELECT (or WITH ... SELECT, or VALUES); anything that writes data, changes schema, or alters connection state is rejected, as is more than one statement per call. SQLite dialect. Results are capped at 100 rows per call — use offset to page through more, and check hasMore in the response. No LLM is involved: no API key needed, no cost, and the result is exact.

Revenue convention: count every order whose status is not 'cancelled' (i.e. new, processing, shipped and completed all count as revenue). Cancelled orders are excluded because the sale did not complete. To count only fully delivered sales instead, filter status = 'completed' and say so in the answer.

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYesA single read-only SQL SELECT statement in SQLite dialect. Example: "SELECT p.name, SUM(oi.quantity) AS units FROM order_items oi JOIN products p ON p.id = oi.product_id JOIN orders o ON o.id = oi.order_id WHERE o.status != 'cancelled' GROUP BY p.id ORDER BY units DESC LIMIT 5"
limitNoMaximum rows to return (default and hard ceiling: 100). Larger values are clamped.
offsetNoRows to skip before returning results. Use with `limit` to page through a large result set.

TDQS

A4.4/5.0
Behavior5/5

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

With no annotations provided, the description carries the full burden. It thoroughly discloses: read-only and SELECT-only enforcement, single-statement limitation, SQLite dialect, row cap of 100 with offset/hasMore paging, no LLM involvement (no key, no cost, exact results), and the revenue convention (counting non-cancelled orders). This is exemplary transparency for a tool that executes arbitrary SQL.

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 longer than a single sentence but every section earns its place: purpose, use case, limitations, and revenue convention are separated and clearly front-loaded. It respects the reader by grouping constraints and providing a concrete example. Slightly verbose but never wasteful.

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?

No output schema exists, so the description correctly explains return format ('structured rows plus column names as JSON') and mentions hasMore. It covers all necessary operational details: single-statement rule, paging, dialect, and domain convention. For a complex SQL tool with no annotations, this is remarkably complete.

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 already documents all three parameters (sql, limit, offset). The description reinforces paging behavior ('use offset to page through more') and the revenue convention, but adds no new parameter semantics beyond what the schema provides. Baseline 3 is appropriate.

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 ('Runs') and resource ('read-only SQL query against the e-commerce SQLite database') and specifies the output shape ('structured rows plus column names as JSON'). It clearly separates itself from sibling tools by instructing to use list_tables and describe_table first when schema is unknown, implying this tool is for querying after schema discovery.

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

Usage Guidelines4/5

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

Provides clear when-to-use guidance: 'Use this to answer analytical questions yourself' mentioning joins, aggregates, and multi-step work, and when actual values are needed rather than a written summary. It also gives a prerequisite ('Call list_tables and describe_table first if you do not know the schema') and explicit limitations (SELECT only, single statement, paging). However, it does not explicitly name query_database as an alternative, so the situational contrast is slightly weaker than ideal.

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

Lists every table in the e-commerce database with a plain-language explanation of what it holds, its row count, and its column names. Also returns the relationships between tables and the convention this database uses for revenue. Use this first when you need to know what data exists, or to answer questions about the database's structure. Reads SQLite directly: no LLM call, no API key, no cost, returns immediately. Returns JSON.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.6/5.0
Behavior5/5

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

No annotations are provided, so the description carries the full burden. It discloses that it reads SQLite directly, makes no LLM call, requires no API key, costs nothing, returns immediately, and returns JSON. This is comprehensive behavioral disclosure beyond what the empty schema provides.

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 moderately lengthy but every sentence adds valuable information: primary output, use-case guidance, and technical behavior. It is front-loaded with the main purpose and remains readable without 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?

For a zero-parameter tool with no output schema, this description is entirely sufficient. It covers what the tool returns (table lists, explanations, row counts, columns, relationships, revenue convention), when to use it, and how it executes. Nothing an agent needs to decide to call it is missing.

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 the schema requires no explanation. Baseline for 0 params is 4, and the description appropriately does not invent parameter information. No additional semantics needed.

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 a specific verb and resource: lists every table in the e-commerce database, with a plain-language explanation of contents, row count, and column names. It also mentions relationships and revenue convention, distinguishing it from sibling tools like describe_table which likely focuses on a single table.

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

Usage Guidelines4/5

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

Explicitly tells the agent to use this first when needing to know what data exists or answer database structure questions. It does not name sibling tools directly or state when not to use it, but the stated context is sufficient for an agent to decide.

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

query_databaseAsk About the Online ShopA

Answers questions about the online shop in plain language: customers, products, stock, orders and sales. Ask it the way a shop owner would ask a colleague — no SQL, no table names, no technical wording needed.

USE THIS for any question about the shop or the business behind it, however casually it is phrased. For example: 'what sells best?', 'how many customers do we have?', 'which products are nearly out of stock?', 'how much did we earn last month?', 'who are our biggest spenders?', 'are any orders stuck in processing?', 'what was in order 42?', 'which category makes the most money?', 'how many orders were cancelled?'.

IT KNOWS ABOUT: customers (names, email, phone, when they signed up), products (name, category, price, stock on hand), orders (date, status — new, processing, shipped, completed, cancelled — and total), and the individual products inside each order (quantity and price paid).

RETURNS: a written answer in everyday language, with Markdown tables when a list or comparison helps. Numbers are read out of the text rather than returned as structured data.

GOOD TO KNOW: it can only look things up — it can never add, change or delete anything, and any request to do so is refused. One answer covers at most 100 rows of data. It asks a language model to write the SQL behind the scenes, so it needs an API key (or a local Ollama) configured, takes a few seconds, and may phrase the same question slightly differently between runs.

ParametersJSON Schema
NameRequiredDescriptionDefault
messageYesThe question about the shop, in plain language — pass the user's own wording where possible (e.g. 'What are our top 5 bestselling products?', 'How many orders were completed in May 2026?', 'Which customers have ordered more than 3 times?', 'What is running low on stock?')
include_sql_detailsNoWhether to show the SQL query and timing details underneath the answer. Set to false for a clean, non-technical answer (default: true)

TDQS

A4.7/5.0
Behavior5/5

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

No annotations are provided, so the description carries the full burden. It extensively discloses read-only behavior, refusal of write attempts, a 100-row limit, dependence on an LLM/API key or Ollama, variability between runs, and return format (Markdown tables, numbers read out). This goes well beyond typical disclosure.

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?

Well-structured with clear sections (USE THIS, IT KNOWS ABOUT, RETURNS, GOOD TO KNOW) front-loaded with the core purpose. While lengthy, every sentence adds value and the section headers make it easy to scan. No redundancy or filler.

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?

Comprehensive for a natural-language query tool with no annotations and no output schema. It covers scope, entity data, return format, limitations, prerequisites, and refusal behavior. An agent has all necessary information to invoke it correctly.

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?

Schema covers 100% of parameters with detailed descriptions. The description adds value by reinforcing plain-language usage and clarifying that numbers are read from text rather than returned as structured data. It also implies the message should be a natural question, which complements the schema.

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?

States that it answers questions about the online shop in plain language, covering customers, products, stock, orders, and sales. Clearly distinguishes itself from siblings by noting no SQL, table names, or technical wording are needed, implying execute_sql and schema tools are for different tasks.

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

Usage Guidelines4/5

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

Explicitly says 'USE THIS for any question about the shop or the business behind it' and provides numerous examples. However, it does not explicitly name alternative tools or give a when-not-to-use clause; the no-SQL instruction implies but does not explicitly state that execute_sql is for raw queries.

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. 4 tool updatesv0.1.0
    • First observeddescribe_table
    • First observedexecute_sql
    • First observedlist_tables
    • First observedquery_database

TDQS

A4.6/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a distinct, non-overlapping purpose: raw SQL execution, schema listing, table detail inspection, and natural-language querying. No ambiguity between them.

Naming Consistency5/5

All tools follow a consistent verb_object pattern (execute_sql, list_tables, describe_table, query_database). Naming is uniform and predictable.

Tool Count5/5

Four tools is well-scoped for a read-only SQL MCP server. Each tool adds clear value without redundancy, and the count is ideal for the domain.

Completeness5/5

The server fully covers its read-only analytics purpose: schema exploration (list, describe) and data retrieval (raw SQL and natural language). No missing operations or dead ends within its stated scope.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to read-only analyze a SQLite e-commerce database, exploring schema and running analytical SQL queries over stdio.
    -
  • 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
    -
  • F
    license
    A
    quality
    C
    maintenance
    Enables AI agents to analyze an SQLite e-commerce database via secure read-only SQL queries, providing tools for table inspection and analytical requests.
    2
    -
  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to query an SQLite e-commerce database read-only, supporting analytical questions about customers, products, orders, and revenue.
    -