Skip to main content
Glama
ErPepinoMarino

typescript-mcp-sqlite-mini-lab

typescript-mcp-sqlite-lab

Pequeño lab de aprendizaje para explorar el Model Context Protocol (MCP) implementando un MCP Server SQLite desde cero en TypeScript.

¿Qué es esto?

Básicamente es un MCP Server local que permite explorar y manipular una pequeña base de datos SQLite. El flujo es:

MCP Client
    ↓
MCP Server
    ↓
SQLite Database

Related MCP server: SQLite-MCP

¿Qué hace?

Actualmente expone cinco Tools via el protocolo MCP:

  • db.list_tables — Lista todas las tablas de la base de datos SQLite

  • db.describe_table — Describe el esquema de una tabla concreta (columnas, tipos, restricciones, claves)

  • db.query — Ejecuta una consulta de solo lectura (SELECT)

  • db.insert — Inserta una fila en una tabla de forma controlada

  • db.export_csv — Exporta los datos de una tabla a formato CSV

Además de las Tools, el servidor expone Resources (contenido accesible por URI):

  • db://schema — Resource estático con el esquema completo de la base de datos (CREATE TABLE)

  • db://table/{tableName} — Resource dinámico mediante ResourceTemplate que devuelve el contenido de una tabla concreta como CSV

db://schema          → CREATE TABLE de todas las tablas
db://table/users     → datos de la tabla users
db://table/products  → datos de la tabla products

Esto es gracioso. En la teoria una Tool ejecuta una acción (callTool); y un Resource se lee como contenido (readResource). Pero por debajo vienen a ser lo mismo.

Cómo se usa

Se conecta a un MCP Client compatible (como Claude Desktop o un cliente custom). El cliente:

  1. Inicia el handshake initialize con el servidor

  2. Descubre las capabilities y tools disponibles via listTools()

  3. Invoca tools via callTool({ name, arguments })

Arquitectura MCP

Flujo general

┌─────────────────┐
│    MCP Client   │
└────────┬────────┘
         │ MCP
         ↓
┌─────────────────┐
│    MCP Server   │
├─────────────────┤
│   Tools         │  ← db.list_tables
│                 │  ← db.describe_table
│                 │  ← db.query
│                 │  ← db.insert
│                 │  ← db.export_csv
│   Resources     │  ← db://schema
│                 │  ← db://table/{tableName}
└────────┬────────┘
         │
         ↓
┌─────────────────┐
│ SQLite Database │
└─────────────────┘

Tool call

Client
 ↓
tools/call { name, arguments }
 ↓
MCP Server
 ↓
valida contra schema (Zod)
 ↓
ejecuta en SQLite
 ↓
devuelve CallToolResult con content blocks

Resource read

Client
 ↓
resources/read { uri }
 ↓
MCP Server
 ↓
devuelve Resource content

Demo interactivo

El proyecto incluye un cliente MCP interactivo (src/demo.ts) que arranca StdioClientTransport y muestra un menú para probar varias opciones, a saber:

  1. Descubrir Tools (listTools)

  2. Listar tablas (db.list_tables)

  3. Describir una tabla (db.describe_table)

  4. Ejecutar query SELECT (db.query)

  5. Insertar registro (db.insert)

  6. Exportar tabla a CSV (db.export_csv)

  7. Descubrir Resources (listResources)

  8. Leer schema (db://schema)

  9. Leer Resource de una tabla (db://table/{tableName})

  10. Salir

Cada opción indica el tipo de operación MCP (Tool Call o Resource Read/Discovery).

Stack

  • TypeScript + Node.js v24 (ESM nativo)

  • @modelcontextprotocol/sdk v1.30.0 (McpServer + StdioServerTransport)

  • better-sqlite3 — base de datos SQLite síncrona

  • zod — validación de schemas para Tools

  • Vitest — framework de tests

  • ESLint v10 (flat config) + Prettier — calidad de código

Estructura del proyecto

src/
├── index.ts                  → Entry point del servidor MCP (McpServer)
├── client.ts                 → Cliente MCP local de prueba directo
├── demo.ts                   → Cliente/demo interactivo (menú didáctico)
└── db/
    ├── connection.ts         → Singleton de conexión SQLite (getDB, getReadOnlyDB)
    ├── operations.ts         → Lógica pura de tools/resources (recibe la conexión por parámetro)
    ├── init.ts               → Inicialización: schema + datos seed (createSchema, seed)
    ├── validate.ts           → Validación de identificadores (isValidIdentifier)
    └── verify.ts             → Verificación manual de la base de datos
tests/
├── helpers.ts                → Construcción de una BD SQLite en memoria para tests
├── smoke.test.ts             → Prueba mínima del entorno
├── db.tools.test.ts          → Tests de las 5 Tools
├── db.resources.test.ts      → Tests de los 2 Resources
└── validate.test.ts          → Tests de isValidIdentifier
dist/                         → Código compilado (generado por tsc)
database.sqlite               → Base de datos SQLite (en .gitignore)

Testing

Los tests, que ha implementado en un 99% el agente, usan Vitest y se ejecutan con npm test. Están diseñados para ser deterministas y rápidos:

  • Aislamiento: se construye una BD SQLite en memoria (:memory:) en cada test reutilizando createSchema()/seed() de src/db/init.ts. No dependen del archivo database.sqlite, ni de servicios externos, ni de un MCP Client real, ni de APIs de OpenAI.

  • Cobertura de comportamiento:

    • db.tools.test.tslist_tables, describe_table (válida / no existe / id inválido), query (SELECT válido + escritura rechazada), insert (válido / columnas inválidas / id inválido), export_csv (válido / no existe).

    • db.resources.test.tsdb://schema y db://table/{tableName} (leer válido / listar recursos / id inválido / no existe).

    • validate.test.tsisValidIdentifier (casos válidos e inválidos).

Setup

npm install
npm run build
npm test
npm start          → ejecuta el servidor MCP
npm run client     → ejecuta el cliente local de prueba
npm run demo       → ejecuta el cliente/demo interactivo

Scripts

Comando

Descripción

npm start

Ejecuta el servidor MCP (node dist/index.js)

npm run client

Ejecuta el cliente local de prueba

npm run demo

Ejecuta el cliente/demo interactivo

npm test

Ejecuta los tests con Vitest

npm run build

Compila TypeScript

npm run lint

Lint con ESLint

npm run format

Formatea con Prettier

Available Tools

2 tools
db.describe_tableA

Describe the schema of a specific table

ParametersJSON Schema
NameRequiredDescriptionDefault
tableNameYes

TDQS

A3.5/5.0
Behavior3/5

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

No annotations are present, and the description uses the verb 'describe,' which reasonably implies a read-only operation. However, it does not disclose potential side effects, error conditions, or whether the table must exist, leaving some behavioral aspects unstated.

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 a single, clear sentence with no redundant words or extraneous details, making it highly concise and easy to parse.

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

Completeness3/5

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

For a simple describe operation, the description is adequate but minimal. It does not specify the output format, what fields the schema includes, or how errors like missing tables are handled, which could leave an agent uncertain in edge cases.

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 parameter 'tableName' is self-explanatory by name and constrained to a non-empty string, but the description adds no additional meaning about expected format, case sensitivity, or identifier rules beyond the basic schema.

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

Purpose4/5

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

The description clearly states the action ('describe') and the resource ('schema of a specific table'), making the primary purpose obvious. It does not explicitly distinguish itself from the sibling tool db.list_tables, but the focus on a specific table rather than all tables provides implicit contrast.

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

Usage Guidelines3/5

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

The description implies usage when a schema for one specific table is needed, but it does not explicitly state when to prefer this tool over db.list_tables or provide any contextual guidance or prerequisites.

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

db.list_tablesA

List all tables in the SQLite database

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A3.9/5.0
Behavior2/5

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

No annotations are provided, and the description does not disclose any behavioral traits such as read-only status, side effects, or performance implications. While listing is inherently non-destructive, this is not stated explicitly, so transparency is lacking beyond the obvious action.

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 a single, clear sentence with no redundant information. It is optimal in length and structure for the task.

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 simple listing operation with no parameters and no output schema, the description is complete. It tells the agent exactly what the tool does without needing additional context.

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, and the schema has no properties. Per the rubric, this yields a baseline of 4. The description correctly implies no parameters are needed, and there is nothing to add.

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 'List all tables in the SQLite database' uses a specific verb (List) and names the exact resource (all tables in the SQLite database). It clearly distinguishes this tool from the sibling 'db.describe_table', which focuses on describing 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 Guidelines3/5

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

The description implies usage for retrieving the full table list but does not explicitly state when to use this versus the sibling tool, nor does it mention any exclusions or alternatives. The guidance is left to inference.

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. 2 tool updatesv1.0.0
    • First observeddb.describe_table
    • First observeddb.list_tables

TDQS

A3.5/5.0

Scored across 2 tools

Disambiguation5/5

The two tools, db.list_tables and db.describe_table, have clearly distinct purposes with no functional overlap.

Naming Consistency5/5

Both tools follow a consistent 'db.' prefix and snake_case naming pattern, making them predictable.

Tool Count2/5

With only 2 tools, the server feels under-scoped for a database interface, falling well below the typical 3-15 range.

Completeness1/5

The toolset only supports listing tables and describing schemas, missing essential operations like querying or modifying data, leaving the surface severely incomplete.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers