Skip to main content
Glama
Ivan-Madera

midd-nestjs-hexagonal-architecture-mcp

by Ivan-Madera

midd-nestjs-hexagonal-architecture-mcp

Estado: híbrido en uso. Combina midd-hexagonal-nestjs-mcp (generador determinista) con las guidelines, el flujo agéntico y el escáner de lib-midd-mcp-architecture. Las decisiones, el porqué de cada regla, lo que ya se verificó y lo que falta están en docs/DESIGN.md. Donde este README contradiga a DESIGN.md o a templates/rules.yaml, mandan esos dos. En particular: la ruta /{prefijo}/api/v{N}/{recurso}, CORS con * por defecto y restringible por CORS_ALLOWED_ORIGINS, y los tres controles de rate limit más el correlation ID, que son obligatorios. type stack protocol target version

Servidor MCP (Model Context Protocol) del área Middleware que genera y verifica microservicios NestJS con arquitectura hexagonal, contrato JSON:API y las cabeceras de seguridad obligatorias. Cualquier agente/IDE compatible (Kiro, Claude, Cursor, etc.) lo consume para crear servicios nuevos o refactorizar servicios existentes apegados al estándar del área, de forma agnóstica de dominio.

Es la migración de la skill middleware-hexagonal-nestjs + su dataset de plantillas a un servidor MCP. La fuente de verdad del estilo es el repo canónico midd-pf-enrollment.


Tabla de contenidos

  1. Descripción

  2. Arquitectura

  3. Diagramas

  4. Capacidades

  5. Stack tecnológico

  6. Instalación

  7. Variables de entorno

  8. Herramientas MCP (la "API")

  9. Documentación interna

  10. Testing

  11. DevOps

  12. Comandos

  13. Buenas prácticas

  14. Mejoras sugeridas

  15. Licencia


Related MCP server: FRD Orchestrator

Descripción

Este proyecto no es un backend HTTP: es un servidor MCP sobre stdio que escribe archivos directamente en un proyecto NestJS destino (modo A, "escribe disco"). Su "API" son 15 herramientas (tools) y 3 prompts (flujos) que un agente invoca para:

  • Crear un microservicio NestJS hexagonal nuevo (greenfield) completo y funcional.

  • Refactorizar un NestJS existente a arquitectura hexagonal, respetando su convención.

  • Generar módulos desde un spec declarativo (middleware.spec.yaml), agnóstico de dominio.

  • Verificar estándares (naming, seguridad, JSON:API) y dejar memoria por repo (inventario + auditoría).

El principio rector: agnóstico de dominio, opinado en calidad. El module/entity/use_cases los define el usuario; el MCP aporta la forma hexagonal, el naming, los puertos, el JSON:API y la seguridad, destilados del repo canónico.


Arquitectura

El MCP es un proceso Node (ESM) que registra herramientas y prompts contra el McpServer del SDK oficial y se comunica por stdio. Internamente se separa en tres capas:

Capa

Carpeta

Responsabilidad

Entrypoint

src/index.ts

Arranca el servidor, registra las 15 tools y los 3 prompts, conecta el transporte stdio.

Tools

src/tools/

Cada herramienta MCP: valida inputs (zod), orquesta la lib y devuelve un reporte de texto.

Lib (núcleo)

src/lib/

Lógica pura: sustitución de placeholders, materialización de plantillas, parcheo idempotente de módulos, parser de spec, inferencia de reglas, inventario.

Dataset

templates/

Las plantillas (capa shared, config, _domain-slice), rules.yaml y el template del spec. Se empaqueta con el servidor.

Patrón de generación: las plantillas usan placeholders case-sensitive (__Caso__, __caso__, __CASO__, __Request__, <sharedRoot>, …) que se sustituyen por los nombres de negocio. Para lo que no se puede resolver con sustitución 1:1 (p.ej. N métodos por puerto, merge de casos, wiring SP), hay enriquecedores programáticos que parchean el código generado de forma idempotente y quirúrgica (anclados a marcas estables, nunca tocan lo ajeno).

src/
├── index.ts                 # servidor MCP: registra 15 tools + 3 prompts (stdio); envuelve con withKit las que trabajan sobre un repo
├── prompts.ts               # flujos guía: start, scaffold_greenfield, refactor_to_hexagonal
├── lib/
│   ├── dataset.ts           # localiza/lee plantillas y materializa árboles en el destino
│   ├── placeholders.ts      # sustitución case-sensitive + mapa de marcadores
│   ├── adapters.ts          # tipos de adapter (typeorm | sp | http) y la llamada HTTP del adapter de API externa
│   ├── engines.ts           # motores (mssql | postgres | mysql | none): driver, puerto, opciones de TypeORM, dialecto de SP
│   ├── connections.ts       # conexiones: nombre por motor, creación completa, detección en refactor
│   ├── moduleMerge.ts       # merge del 2º/3er caso en los módulos del dominio existente
│   ├── spWiring.ts          # wiring quirúrgico del adapter SP (preserva forFeature)
│   ├── httpWiring.ts        # wiring del adapter de API externa (config, Joi, .env.example, catálogo de errores)
│   ├── portMethods.ts       # enriquece puertos inbound/outbound a N métodos + entidades
│   ├── spec.ts              # parser + validador del middleware.spec.yaml
│   ├── businessRules.ts     # materializa reglas de negocio como guardas (condición inferida + NOTA)
│   ├── dtoFields.ts         # pobla DTOs input/output y entidades request/response desde el spec
│   ├── errorCodes.ts        # códigos PREFIJO-SLUG-NNN: 001-999, secuencia por prefijo
│   ├── caseErrors.ts        # entradas de error de un caso que se suma a un dominio que ya existe
│   ├── envFile.ts           # .env.example por secciones
│   ├── env.ts               # .env.example derivado de joi-schema.ts
│   ├── apiDocs.ts           # documentación leída del código (contrato, diagramas, Postman, arquitectura)
│   ├── inventory.ts         # inventario (architecture-inventory.json) + auditoría (docs/audits)
│   ├── learnings.ts         # aprendizaje por repo (consultivo; docs/mcp-learnings.json)
│   ├── agenticKit.ts        # kit de agentes: instalación, actualización y revisión automática
│   ├── inspect.ts           # descubrimiento de solo lectura del proyecto (refactor)
│   └── schemas.ts           # inputs zod compartidos
└── tools/
    ├── scaffold.ts          # scaffold_service
    ├── addUseCase.ts        # add_use_case (vertical slice; greenfield y refactor)
    ├── generateFromSpec.ts  # generate_from_spec (un módulo desde el spec)
    ├── addAuthorization.ts  # add_authorization
    ├── apiDocs.ts           # generate_api_docs
    ├── architecture.ts      # record_architecture (inventario + auditoría)
    ├── learnings.ts         # get_learnings, record_decision
    ├── agentic.ts           # install_agentic_kit, get_flow
    ├── support.ts           # get_rules, inspect_project, verify_standards, list_templates, get_template
    └── kit.ts               # withKit: instala el kit de agentes antes de las tools que trabajan sobre un repo
templates/
├── rules.yaml                       # cerebro de calidad agnóstico (lo devuelve get_rules)
├── middleware.spec.template.yaml    # plantilla del spec declarativo
├── config/                          # base del proyecto NestJS generado + enforcement (verify-standards, eslint, Dockerfile...)
├── shared/                          # capa transversal (JSON:API, errores, logger, config, seguridad, health, utils)
├── database/                        # módulo y opciones de TypeORM por motor
├── authorization/                   # autorización opt-in del borde HTTP
├── agentic/                         # agentes del kit (generator, worker, auditor) y sección de AGENTS.md
└── _domain-slice/                   # plantilla de un caso de uso hexagonal (adapters typeorm, sp y http)
test/                                # suite con el runner nativo de Node (node:test) + e2e real

Nota de arquitectura — acoplamiento: generate_from_spec reutiliza add_use_case como motor de siembra y luego aplica los enriquecedores (portMethods, dtoFields, businessRules) y el inventario. Es un acoplamiento deliberado y unidireccional (tools → lib), que mantiene el camino imperativo (add_use_case) intacto mientras el declarativo (generate_from_spec) se construye encima.


Diagramas

Arquitectura de componentes

flowchart TD
  Agent["Agente / IDE (Kiro, Claude, Cursor)"] -->|stdio / MCP| Server["McpServer (src/index.ts)"]
  Server --> Prompts["Prompts: start · greenfield · refactor"]
  Server --> Tools["15 Tools"]
  Tools --> Lib["lib/ (núcleo puro)"]
  Lib --> Dataset["templates/ (plantillas + rules.yaml)"]
  Lib -->|escribe disco| Target["Proyecto NestJS destino (src/, docs/)"]

Flujo greenfield (crear servicio desde cero)

flowchart TD
  A["get_rules — carga el estándar"] --> B["scaffold_service — base: shared + config + main.ts"]
  B --> C["generate_from_spec / add_use_case — casos de uso"]
  C --> D["npm install + npm run build"]
  D --> E["verify_standards — naming/seguridad/JSON:API"]
  E --> F["record_architecture — inventario + auditoría"]

Flujo refactor (NestJS existente → hexagonal)

sequenceDiagram
  participant Ag as Agente
  participant MCP as MCP
  participant Repo as Proyecto destino
  Ag->>MCP: get_rules
  Ag->>MCP: inspect_project(projectRoot)
  MCP->>Repo: lectura (convención, conexión, infra existente)
  MCP-->>Ag: reglas a respetar + nombres de clase a reusar
  Ag->>MCP: add_use_case(mode="refactor", ...)
  MCP->>Repo: genera slice (NO toca app.module)
  Ag->>Repo: mueve la lógica real + reusa infra existente
  Ag->>MCP: verify_standards + record_architecture

Generación declarativa desde spec

flowchart LR
  Spec["middleware.spec.yaml"] --> V["spec.ts — valida (module/entity/use_cases/methods)"]
  V --> Plan["dryRun=true → PLAN (casos, métodos, archivos)"]
  V --> Gen["dryRun=false → genera"]
  Gen --> Seed["add_use_case por caso (método principal)"]
  Seed --> Enrich["portMethods — N métodos tipados + entidades"]
  Enrich --> DTO["dtoFields — DTOs input/output"]
  DTO --> Rules["businessRules — guardas (condición inferida + NOTA)"]
  Rules --> Inv["inventory — architecture-inventory.json"]

Capacidades

Generación (greenfield)

  • scaffold_service siembra la capa shared completa (JSON:API, errores, logger, config + Joi, seguridad, health, utils), los archivos de config/enforcement (eslint, prettier, Dockerfile, verify-standards, hooks husky), main.ts, app.module.ts, un .gitignore que excluye .env (nunca pisa el del proyecto) y el .env.example por secciones derivado de joi-schema.ts.

  • Motor de base de datos: el agente lo pregunta (mssql, postgres, mysql) y de la respuesta salen el driver, las opciones de TypeORM y el dialecto del stored procedure (mssql EXEC, mysql CALL; el área no usa stored procedures en PostgreSQL, el MCP los rechaza). Con none (el servicio no usa base de datos) no se genera ninguna conexión, módulo, variable DB_* ni driver.

  • Conexiones: su nombre no se pregunta, sale del motor (Mssql, Postgres, Mysql); una adicional del mismo motor se numera (Mssql2, variables DB_MSSQL2_*).

Vertical slice (greenfield y refactor)

  • add_use_case genera un caso completo: puertos inbound/outbound, domain/application services, adapter, controller JSON:API + DTOs, entidades de dominio, catálogos de error y los módulos del dominio.

  • Tres adapters: typeorm (por defecto), sp (stored procedure, opt-in; no con PostgreSQL) y http (API externa con el fetch nativo; no necesita base de datos ni conexión). El adapter http declara <API>_BASE_URL en la configuración, en Joi y en el .env.example, y traduce las respuestas (404 = no encontrado; error o API caída = 502 EXTERNAL_API_ERROR).

  • Multi-caso: al añadir el 2º/3er caso al mismo dominio, mergea el caso en los módulos y catálogos existentes de forma idempotente.

  • Refactor: reutiliza la conexión que el proyecto ya tiene (se detecta; no se pregunta nombre ni motor). Si no tiene ninguna, el MCP no crea una por su cuenta: solo con pedido expreso (crearConexion=true + motor).

Generación declarativa (desde spec)

  • generate_from_spec toma un middleware.spec.yaml y genera el módulo. Soporta casos con N métodos por puerto con entidades request/response tipadas. Hexagonal puro: la firma del método del puerto es siempre (data: Request); el nombre del SP, la URL y el verbo de una API externa son infraestructura y no viajan por el puerto. Materializa DTOs input/output y reglas de negocio (con condición inferida + NOTA), y actualiza el inventario. dryRun=true (default) devuelve el plan sin escribir disco.

Seguridad y borde HTTP (obligatorios)

  • Cabeceras de seguridad, rate limit con los tres controles (por IP, concurrencia, tamaño de payload), correlation ID (también hacia APIs externas), CORS por variable, health público (POST /{api}/api/v1/health), errores del parser con el sobre del área y solo POST con application/vnd.api+json.

  • Autorización opt-in (add_authorization): puerto agnóstico + Guard global, secure-by-default y fail-closed. El agente siempre pregunta.

  • Sin axios (se usa fetch) y sin uuid (se usa crypto).

Textos de los errores

  • El MCP escribe el message, el title y el suggestedActions de cada error en español, a partir de la entidad (LockType → "Lock type no encontrado.", "No se encontró lock type con los parámetros enviados."), también para un caso que se suma a un dominio existente y para el error de API externa. Es una suposición razonable: la persona la corrige si no se apega al caso. verify_standards avisa con ERROR_CATALOG_PLACEHOLDER si un catálogo conserva el texto de plantilla.

Códigos de error

  • Formato <PREFIJO>-<SLUG>-<NNN>, por ejemplo CATALOG-PRODUCTNOTFOUND-001. El número va de 001 a 999 y es una secuencia por prefijo que asigna el MCP leyendo el código existente: dos errores nunca comparten número. El slug no lleva guiones. Cada catálogo trae su error por defecto <PREFIJO>-GENERICERROR-000 (el filtro global usa SERVICE-GENERICERROR-000).

Documentación de la API

  • generate_api_docs lee el código y escribe el contrato por módulo, un diagrama Mermaid de secuencia por módulo y el índice; docs/ARCHITECTURE.md (architecture-beta, siempre, no se pregunta) y, opcionalmente, la colección de Postman. Se mantiene al día en cada generación.

Verificación y descubrimiento

  • verify_standards corre el verificador del servicio generado con reglas de ID estable: naming, seguridad HTTP, correlation ID, @Version, .env.example y defaults de Joi, autorización, health, conexiones de BD, SP declarado, reglas de código (sin console.log, process.env directo, any, dinero como float, HTTP en el core...), dependencias prohibidas, documentación desactualizada, códigos de error repetidos y .env sin ignorar por git.

  • inspect_project: descubrimiento de solo lectura del proyecto destino (convención de carpetas, forma de la conexión TypeORM, infra transversal a reusar con sus nombres de clase, nombre que tomaría una conexión nueva).

Cuántas preguntas hace el agente

En una API nueva, tres momentos:

  1. Cinco preguntas generales, de una en una: prefijo de la API, prefijo de errores, base de datos (mssql, postgres, mysql o none), autorización y Postman. Cada una va en su propio mensaje (🧱 Middleware Generator pregunta (1 de 5)), el agente espera la respuesta y la guarda antes de pasar a la siguiente (autorización y Postman en AGENTS.md); salta las que ya estén respondidas. Las preguntas del agente llevan emojis para distinguirlo del agente por defecto. Tras generar la base no se detiene: pide el primer caso de uso.

  2. Por caso de uso: "qué hace, qué recibe y qué devuelve". De ahí el agente deduce si los datos salen de la base de datos, de una API externa o de un stored procedure, y solo pregunta el dato que falta de ese caso (nombre, verbo y ruta de la API; nombre del SP). Con "ninguna" base de datos, todos los casos son de API externa.

  3. Los valores reales del entorno (host, usuario, URLs), al preparar el servicio.

No pregunta la conexión, los números de error, CORS, los límites de peticiones, el health, las rutas, la complejidad (nivel 0), el esquema ni reglas que no mencionaste: lo supone y lo lista como TODO al final.

Memoria por repo y agentes

  • record_architecture: inventario docs/architecture-inventory.json (una entrada por módulo, sin tocar las de otros) + auditoría docs/audits/<module>-<fecha>.md.

  • get_learnings / record_decision: memoria consultiva por repo (prefijos, conexiones, decisión de autorización, errores que se repiten); nunca cambia las reglas base.

  • Kit de agentes (middleware-generator, middleware-gen-worker, middleware-auditor): se instala solo la primera vez que una herramienta trabaja sobre un repo (ver más abajo). El agente prepara el entorno: corre npm install, crea el .env con los valores que le da el usuario y no repite contraseñas.


Stack tecnológico

Componente

Tecnología

Versión

Rol

Runtime

Node.js

≥ 18 (probado en 22)

Ejecuta el servidor MCP (ESM).

Lenguaje

TypeScript

^5.4

Código fuente (src/), compila a dist/.

Protocolo

@modelcontextprotocol/sdk

^1.0.4

McpServer + transporte stdio.

Validación

zod

^3.23.8

Esquemas de input de cada tool.

Parsing

yaml

2.6.1 (pinned)

Lee el middleware.spec.yaml.

Tests

node:test

nativo

Suite sin dependencias extra.

Tipos

@types/node

^20.11

Tipos de Node para el build.

Las dependencias se documentan tal cual están en package.json. El MCP es deliberadamente ligero: solo SDK + zod + yaml en runtime.


Instalación

npm install
npm run build

El dataset de plantillas vive en templates/ y se empaqueta con el servidor (campo files del package.json: dist + templates).

Conectar a Kiro

Añade el servidor a la config MCP. Workspace: .kiro/settings/mcp.json. Usuario: ~/.kiro/settings/mcp.json.

{
  "mcpServers": {
    "midd-nestjs-hexagonal-architecture": {
      "command": "node",
      "args": ["C:/Propuestas/midd-nestjs-hexagonal-architecture-mcp/dist/index.js"],
      "disabled": false,
      "autoApprove": ["get_rules", "get_flow", "get_learnings", "list_templates", "get_template", "inspect_project"]
    }
  }
}

Solo las herramientas de lectura van en autoApprove; las que escriben archivos piden confirmación.

Actualizar el MCP: npm run build y reconectar el servidor desde la vista MCP de Kiro. El repo no necesita nada más.

Este MCP comparte nombres de herramientas (scaffold_service, add_use_case, get_rules...) con midd-hexagonal-nestjs y midd-architecture. Si los tienes activos a la vez, desactiva los otros para que el agente no llame a uno equivocado.

Instalación automática de los agentes

No hace falta pedir install_agentic_kit. La primera herramienta que trabaja sobre un repo (scaffold_service, add_use_case, generate_from_spec, add_authorization, inspect_project) revisa si el kit está y, si no, lo instala antes de seguir:

Situación del repo

Qué hace el MCP

No tiene el kit

Lo instala: .kiro/agents/middleware-generator.md, middleware-gen-worker.md, middleware-auditor.md, agentic/templates/, la sección del MCP en AGENTS.md y el bloque de decisiones (ver abajo). Avisa qué agente seleccionar. Si la herramienta que lo disparó genera algo (scaffold_service, add_use_case, add_authorization, generate_from_spec), en esa primera llamada no genera nada: instala, avisa y espera a que el usuario elija el agente y repita su pedido.

Tiene el kit de una versión anterior

Lo actualiza y conserva los modelos que el equipo haya puesto en los agentes.

Ya está al día (o es un generate_from_spec con dryRun=true, que solo planifica)

No escribe nada. scaffold_service e inspect_project solo recuerdan qué agente usar.

Hay un agente con esos nombres que no instaló este MCP

No toca nada y lo dice (los tres agentes van como conjunto). Para reemplazarlos: install_agentic_kit con overwrite=true.

El agente del chat no lo puede fijar un MCP. Kiro lo elige en el selector de agentes de la barra del chat (junto al selector de modelo); el agente aparece ahí al guardarse el archivo, y si no se ve hay que recargar la ventana. Según el changelog de Kiro IDE 1.0, ese mismo selector permite dejar un agente preferido que persiste entre reinicios. Un chat que ya empezó con el agente por defecto sigue con él hasta que se cambie.

Decisiones a la vista en AGENTS.md

El agente pregunta una vez por repo la autorización y Postman, y guarda la respuesta en un bloque de AGENTS.md que el kit deja desde el principio:

AUTHORIZATION: undefined   # required = autorizacion activa | none = endpoints publicos
POSTMAN: undefined   # yes | no

undefined es que todavía no se preguntó. El agente solo pregunta lo que dice undefined; el siguiente módulo del repo no vuelve a preguntar. Para cambiar una decisión se edita el valor. Solo se leen valores cerrados (cualquier otra cosa cuenta como no decidida), el bloque tiene sus propios marcadores y actualizar el kit nunca toca lo que contiene. Lo que dice AGENTS.md manda sobre lo guardado en docs/mcp-learnings.json.

Para desactivar la instalación automática, en la configuración del servidor MCP:

"env": { "MIDD_NESTJS_AUTO_KIT": "off" }

Variables de entorno

Del servidor MCP

Variable

Valores

Descripción

MIDD_NESTJS_AUTO_KIT

off / 0 / false / no

Desactiva la instalación automática del kit de agentes. Por defecto está activa. Se define en env de la config MCP.

Del servicio que el MCP genera

Derivadas de joi-schema.ts (fuente de verdad, que alimenta el .env.example). Todo lo que tiene valor por defecto lo aplica Joi si la variable no está configurada.

Variable

Tipo

Requerida

Descripción

PORT

number

no (3000)

Puerto HTTP.

API_CONTEXT

string

sí

Prefijo de la API (prefijoApi): los endpoints quedan en /<prefijo>/api/v1/{recurso}.

CORS_ALLOWED_ORIGINS

string

no (*)

Orígenes permitidos separados por coma. * es el valor por defecto (middleware servidor-a-servidor); se restringe con la variable, sin tocar código.

RL_MAX_REQUESTS_PER_WINDOW / RL_WINDOW_SECONDS

number

no (150 / 5)

Peticiones por IP en la ventana. Al pasarse: 429.

RL_MAX_CONCURRENT_PER_IP

number

no (20)

Conexiones simultáneas por IP.

RL_MAX_PAYLOAD_BYTES / RL_MAX_JSON_PAYLOAD_BYTES

number

no (8 MB / 2 MB)

Tamaño máximo del cuerpo. Al pasarse: 413.

RL_CACHE_TTL_MS / RL_CACHE_MAX_ENTRIES

number

no (600000 / 100000)

Cuánto y cuántas IPs recuerda el contador.

RL_TRUSTED_PROXIES

string

no (rangos privados)

Proxies de confianza para leer la IP real.

DB_<CONEXION>_HOST / _PORT / _USERNAME / _PASSWORD / _NAME

string / number

sí, si hay conexión

Por conexión (p.ej. DB_MSSQL_HOST). El puerto por defecto depende del motor: mssql 1433, postgres 5432, mysql 3306.

AUTHORIZATION_API_URL

URL

solo con autorización

API de autorización.

<API>_BASE_URL

URL

condicional

URL base de cada API externa consumida por un caso http (p.ej. EXCHANGE_RATES_BASE_URL). Sin ella el servicio no arranca.

<NOMBRE_SP>_SP

string

condicional

Se añade por cada caso con adapter sp.

.env.example generado (agrupado por temas; cada herramienta mete su variable en su sección):

# --- Server ---
PORT=3000
API_CONTEXT=midd-catalog

# --- CORS ---
CORS_ALLOWED_ORIGINS=*

# --- Ratelimit ---
RL_MAX_REQUESTS_PER_WINDOW=150
# ... las demás RL_*

# --- Database connection 'Mssql' (SQL Server) ---
DB_MSSQL_HOST=localhost
DB_MSSQL_PORT=1433
DB_MSSQL_USERNAME=sa
DB_MSSQL_PASSWORD=changeme
DB_MSSQL_NAME=MyDatabase

# --- Authorization ---
AUTHORIZATION_API_URL=...

# --- External APIs ---
EXCHANGE_RATES_BASE_URL=https://api.example.com

El .env real lo crea el agente, a partir del .env.example y con los valores que le da el usuario (sin repetir contraseñas). El .gitignore generado lo excluye y verify_standards falla con ENV_NOT_IGNORED si un .env no está ignorado por git.


Herramientas MCP (la "API")

El equivalente a "endpoints" de este servidor. Cada tool recibe un input validado con zod y devuelve un reporte de texto.

get_rules

Devuelve rules.yaml: el cerebro de calidad agnóstico (arquitectura hexagonal, naming, puertos inbound/outbound multi-método, DTOs JSON:API, acceso a datos, reglas de negocio, errores, seguridad, complejidad) con snippets destilados del canon. Debe leerse antes de generar o refactorizar.

  • Input: (ninguno)

scaffold_service

Genera la base de un servicio NestJS hexagonal nuevo.

  • Input: projectRoot, conexion? (opcional: por defecto el nombre del motor), motor (mssql|postgres|mysql|none, obligatorio: el agente lo pregunta; none = sin base de datos, no se genera ninguna conexión), prefijoApi (kebab-case), prefijoError (MAYÚSCULAS), overwrite?. Los tres obligatorios (prefijoApi, prefijoError, motor) los valida la herramienta, no el esquema: si falta alguno no genera nada y responde con la lista de lo que hay que preguntarle al usuario.

  • Escribe: src/shared/**, config/enforcement, main.ts, app.module.ts, .env.example.

add_use_case

Genera un caso de uso completo (vertical slice).

  • Input: projectRoot, dominio, caso, entidad, metodo, param, request?, accion, prefijoError, conexion? (opcional), crearConexion? (solo refactor, si el usuario la pidió expresamente), motor? (obligatorio solo si la conexión es nueva), adapterType (typeorm|sp|http), nombreSp?, apiExterna?, rutaApi?, metodoHttp?, envVarSp?, mode (greenfield|refactor), connectionStyle (named|default), infraStyle (dataset|project), infraRoot?, overwrite?

  • Nota: SP requiere nombreSp (opt-in). En refactor no toca app.module.

generate_from_spec

Genera un módulo completo desde un middleware.spec.yaml.

  • Input: projectRoot, specPath, mode (greenfield|refactor), dryRun (default true), overwrite?

  • dryRun=true: devuelve el plan (casos, métodos, archivos) sin escribir. dryRun=false: genera + actualiza el inventario.

record_architecture

Registra el módulo en el inventario y escribe su auditoría.

  • Input: projectRoot, specPath, compliance?, buildStatus?, decisions?, writeAuditFile? (default true)

generate_api_docs

Genera la documentación de la API leyendo el código real (controllers, DTOs y catálogos de error). Determinista: el mismo código da los mismos archivos.

  • Input: projectRoot, modules? (por defecto todos), postman? (default false), architecture? (default true: docs/ARCHITECTURE.md se genera siempre)

  • Siempre escribe: src/<modulo>/contracts/<modulo>.api.md (contrato: endpoints, campos, errores, curl), src/<modulo>/diagrams/<modulo>.flow.mmd (Mermaid sequenceDiagram por módulo) y docs/api/README.md (índice).

  • Opt-in (el agente pregunta): postman=true crea docs/api/middleware.postman_collection.json (una colección v2.1, una carpeta por módulo; al fusionar solo se reemplaza la carpeta del módulo). architecture=true crea docs/ARCHITECTURE.md con un diagrama Mermaid architecture-beta (11.1+; las líneas align requieren 11.16+).

  • Se mantiene al día: add_use_case, generate_from_spec y record_architecture regeneran el contrato y el diagrama del módulo, y refrescan ARCHITECTURE.md siempre y Postman si ya existe. verify_standards avisa (WARN, no bloquea) con API_DOCS_MISSING / API_DOCS_STALE.

add_authorization, record_decision, get_learnings, install_agentic_kit, get_flow

Ver docs/DESIGN.md: autorización opt-in del borde HTTP, memoria por repo (consultiva), kit de agentes y procedimiento de cada flujo.

inspect_project

Descubrimiento de solo lectura del proyecto destino (refactor).

  • Input: projectRoot

  • Devuelve: convención de carpetas/case, forma de conexión TypeORM, infra transversal existente + nombres de clase, módulos, infraRoot.

verify_standards

Corre la verificación de estándares sobre el proyecto destino.

  • Input: projectRoot, installScript? (default true)

  • Devuelve: reporte; falla (isError) si hay errores bloqueantes.

list_templates / get_template

Inspeccionar el dataset.

  • list_templates — Input: subdir (shared|config|_domain-slice|all).

  • get_template — Input: relativePath.

Prompts (flujos guía)

  • start — desambigua greenfield vs refactor según el estado del workspace.

  • scaffold_greenfield — guía la creación de un servicio nuevo paso a paso.

  • refactor_to_hexagonal — guía la conversión de un NestJS existente a hexagonal.


Documentación interna

El spec declarativo (middleware.spec.yaml)

Agnóstico de dominio: module, entity y use_cases los define el usuario. Un caso de uso declara N métodos por puerto, cada uno con su entidad request y response (firma canónica (data: <Request>): Promise<<Response>>). El parser (spec.ts) valida naming (kebab/Pascal/camel/MAYÚSCULAS), exige al menos un caso con un método, exige sp cuando adapter="sp", y obliga a declarar reglas o none: true — el MCP no inventa reglas.

Enriquecedores (parcheo idempotente)

  • moduleMerge.ts — registra casos adicionales en los módulos del dominio (controller, adapter, providers, tokens, forFeature, app.module) balanceando corchetes y evitando duplicados.

  • spWiring.ts — wiring SP quirúrgico: apunta al .sp.adapter, quita del forFeature solo la entidad del caso SP (preserva las demás), y registra el SP en config/joi/.env.

  • portMethods.ts — añade N métodos tipados a puertos/domain service/adapter y crea las entidades *.entity.ts faltantes.

  • httpWiring.ts — wiring del adapter de API externa: apunta los módulos al .http.adapter, declara <API>_BASE_URL (config + Joi .uri().required() + .env.example) y la entrada EXTERNAL_API_ERROR del catálogo.

  • caseErrors.ts / errorCodes.ts — un caso nuevo en un dominio existente agrega sus entradas a los catálogos de error, y cada código toma el siguiente número libre del prefijo.

  • businessRules.ts — materializa reglas como guardas con GenericException; infiere la condición por patrón (obligatorio, enum, unicidad, 404, branching) y estampa una NOTA de que es una aproximación a revisar.

Convención de nombres

Nombres en inglés. Carpetas y archivos en kebab-case con sufijo de tipo (store-configuration/, retrieve-product.controller.ts, retrieve-product.inbound.port.ts, store-configuration.infrastructure.module.ts); clases e interfaces en PascalCase (IRetrieveProductService, HttpClientService), variables y propiedades en camelCase, constantes y tokens en MAYÚSCULAS.

Mapeo desde la base de datos (como el canon). La entidad de dominio de respuesta es una clase con @Expose en cada campo y el adapter la construye con Mapper/MapperList (plainToInstance + excludeExtraneousValues: un campo sin @Expose se pierde). Nunca se castea una fila con as (BLIND_CAST). Las propiedades van en camelCase con las palabras tal como vienen de la fuente (tipo_bloqueo → tipoBloqueo, PFM_Id → pfmId):

  • Stored procedure o API externa: @Expose({ name: 'tipo_bloqueo' }) tipoBloqueo?: number.

  • TypeORM: la entidad TypeORM tiene @Column({ name: 'tipo_bloqueo' }) tipoBloqueo: number y la de dominio @Expose() tipoBloqueo?: number; el adapter devuelve Mapper(Entidad, row).

Con generate_from_spec, los campos de dtos.output se escriben así solos. verify_standards avisa NAMING_FILE_CASE (WARN) ante un archivo o carpeta que no sea kebab-case. Sustitución de placeholders case-sensitive.


Testing

Suite con el runner nativo de Node (node:test), sin dependencias extra. Se ejecuta sobre el dist compilado.

npm test          # rápida (~1 min, sin red): tsc && node --test "test/**/*.test.mjs"
npm run test:e2e # genera, instala, compila y arranca un servicio real (necesita red la 1ª vez)

Archivo

Cubre

test/spec.test.mjs

Validación del spec: acepta válido, acumula errores, exige sp/reglas/casos.

test/businessRules.test.mjs

Inferencia de guardas (obligatorio/enum activas; unicidad/404 comentadas; no-reconocible → andamiaje).

test/inventory.test.mjs

Envelope, agregar 2º módulo sin tocar el 1º, reemplazo de entrada, auditoría.

test/placeholders.test.mjs

Derivación de case, __Request__, sustitución case-sensitive, <ConexionArg>.

test/scaffold.e2e.test.mjs

Genera servicios y exige que verify-standards pase limpio; una mutación por cada regla bloqueante (seguridad, ruta, dependencias, autorización, health, SP).

test/database.test.mjs

Motores (mssql, postgres, mysql): perfiles, dialecto de SP con un DataSource falso, conexiones adicionales, el motor es obligatorio. En PostgreSQL no se aceptan stored procedures.

test/errorTexts.test.mjs

Textos de error en español desde la entidad (también al sumar un caso a un dominio existente y en el error de API externa) y aviso del verificador por texto de plantilla.

test/connectionName.test.mjs, test/noDatabase.test.mjs

Nombre de la conexión por motor, reutilización, refactor (detecta, no crea sin pedido expreso) y servicio sin base de datos.

test/httpAdapter.test.mjs

Adapter de API externa: cableado sin base de datos, verbos GET/POST/PUT, config/Joi/.env, mezcla con TypeORM, spec, refactor, documentación.

test/errorCodes.test.mjs

Códigos PREFIJO-SLUG-NNN: secuencia por prefijo, 001-999, agotamiento, capa compartida de 3 dígitos y reglas del verificador.

test/envFile.test.mjs, test/environment.test.mjs

.env.example por secciones y defaults de Joi; pasos dirigidos al agente, .gitignore y ENV_NOT_IGNORED.

test/naming.test.mjs

Convención de nombres: helpers, módulo de varias palabras (identificadores válidos, archivos kebab-case, verificador limpio), merge de un segundo caso, resource_type, rechazo de un dominio con la estructura anterior y aviso NAMING_FILE_CASE.

test/mapping.test.mjs

Mapeo como el canon: propiedades camelCase, @Expose con el nombre de la columna (SP) o simple (TypeORM), @Column en la entidad TypeORM, Mapper en el adapter y aviso BLIND_CAST ante as unknown as.

test/apiDocs.test.mjs

Documentación generada desde el código: contrato, diagrama, fusión de Postman, architecture-beta, refresco automático y avisos del verificador.

test/preferences.test.mjs

Bloque de decisiones en AGENTS.md: se crea sin valores, escribir una respuesta cambia solo su valor, se respeta lo que el usuario edita, actualizar el kit no lo toca, CRLF, bloque roto, y get_learnings informa lo que dice AGENTS.md.

test/agentic.test.mjs, test/autoKit.test.mjs

Kit de agentes: instalación idempotente, AGENTS.md ajeno/roto, modelos; instalación automática por el protocolo MCP (compuerta del primer contacto, actualiza conservando modelos, respeta agentes ajenos, opt-out).

test/learnings.test.mjs

Aprendizaje por repo: captura, saneamiento de texto hostil, y que el verificador no lo lee.

test/e2e/compile.e2e.mjs

End-to-end real (npm run test:e2e): genera módulos (SP y TypeORM) + autorización, npm install, npm run build, tests y lint del servicio generado, verify-standards, y lo arranca para probarlo por HTTP (health, cabeceras, 401/403/200, 413, 400, 429, defaults de Joi sin variables). Además un servicio sin base de datos que consume una API externa falsa (200, 404, 502, API caída, propagación del correlation ID).

Estado actual: 233 tests rápidos y 25 comprobaciones end-to-end, todos en verde. Lo que no está probado: postgres y mysql contra motores vivos (solo con un DataSource falso), y la conversación del agente con modelos reales dentro de Kiro.


DevOps

  • Build: tsc (TypeScript → dist/, ESM Node16). Configuración en tsconfig.json (target ES2022, strict: true).

  • Empaquetado: package.json → bin: midd-nestjs-hexagonal-mcp, files: [dist, templates]. El dataset viaja con el paquete.

  • Transporte: stdio (StdioServerTransport). stdout reservado para el protocolo; los logs van a stderr.

  • CI/CD propio del MCP: pendiente de confirmar — no se detectó pipeline (.github/, .gitlab-ci.yml) ni Dockerfile para el propio servidor en el repo. (El Dockerfile que existe está en templates/config/ y pertenece al servicio generado, no al MCP.)

  • .gitignore: ignora node_modules, dist, *.log, .DS_Store.

  • Repo del MCP: hoy solo tiene git init (sin commits ni remoto).

Seguridad en los servicios generados (no en el MCP): main.ts fuerza Helmet, HSTS (1 año), CSP, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, Cache-Control: no-store. CORS vale * por defecto y se restringe con CORS_ALLOWED_ORIGINS (ver Variables de entorno).


Comandos

Comando

Qué hace

npm install

Instala dependencias.

npm run build

Compila src/ → dist/ con tsc.

npm start

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

npm run dev

Compila en modo watch (tsc --watch).

npm test

Compila y corre la suite rápida node:test.

npm run test:e2e

Genera un servicio real, lo instala, compila, prueba y arranca. Deja las dependencias en caché en la carpeta temporal (midd-e2e-workspace).


Buenas prácticas

  • Agnóstico de dominio, opinado en calidad: el MCP nunca hornea un dominio; el usuario define module/entity, el MCP aporta la forma y la calidad.

  • El MCP no inventa reglas ni columnas: las reglas de negocio y el schema se extraen del usuario/spec; lo generado lleva NOTA cuando es una aproximación.

  • Parcheo idempotente y quirúrgico: los enriquecedores nunca duplican ni tocan código de otros casos/módulos.

  • Leer get_rules (y el inventario) antes de generar: así todo sale consistente y no se duplican módulos.

  • dryRun por defecto: revisa el plan antes de escribir disco.

  • El agente ejecuta, el usuario decide: npm install, el .env y el arranque los hace el agente; al usuario solo se le piden los valores. Nunca se repiten contraseñas ni tokens.

  • El MCP no cambia el agente del chat: lo elige el usuario en el selector de Kiro; el MCP instala los agentes y avisa cuál usar.

  • stdout limpio: en un servidor MCP stdio, nunca escribas a stdout fuera del protocolo (usa stderr).


Mejoras sugeridas

  • CI propio del MCP (lint + build + test en cada push).

  • Probar postgres y mysql contra motores vivos (hoy solo con un DataSource falso).

  • Autenticación en el adapter de API externa (hoy deja un TODO; las credenciales deben salir de ConfigurationVariables).

  • Confirmar el formato vigente de los agentes de Kiro (permissions en lugar de allowedTools/toolsSettings) y migrarlos si hace falta.


Licencia

Software propietario de Macropay. Copyright (c) 2026 Macropay. Todos los derechos reservados.

Este MCP, sus plantillas, sus reglas y su documentación son de uso interno de Macropay (empleados y colaboradores autorizados). No se concede ningún derecho de copia, modificación, distribución ni uso fuera de Macropay sin autorización previa y por escrito. Ver LICENSE.

Available Tools

15 tools
add_authorizationA

OPT-IN. Agrega la autorización del borde HTTP al servicio: puerto agnóstico IAuthorizationVerifier + adapter por defecto (API de autorización) + Guard GLOBAL, secure-by-default (todo endpoint protegido salvo @SkipAuthorization()) y FAIL-CLOSED (denegado o autorizador inalcanzable = 403). El agente DEBE PREGUNTAR al usuario si quiere activarla; nunca decide solo ni la omite en silencio. Se crea UNA vez por servicio en src/shared/authorization. Parchea ConfigurationVariables, el schema Joi, .env.example y app.module (la registra DESPUÉS de SecurityModule para que el rate limit corra primero). Idempotente.

NameRequiredDescriptionDefault
overwriteNoSi true, sobrescribe archivos existentes. Por defecto false (no pisa).
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.
authorizationApiUrlNoSample base URL of the authorization API for .env.example. Use a placeholder: the real value goes in the untracked .env.https://authorization.example.com/authorization/v1

TDQS

A4.4/5.0
Behavior5/5

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

With no annotations, the description carries the full burden and does so thoroughly: secure-by-default with @SkipAuthorization() escape hatch, fail-closed semantics (403 on denial or unreachable authorizer), registration order after SecurityModule so rate limiting runs first, the files it patches, and idempotency.

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?

Dense but front-loaded with 'OPT-IN.' and the mandatory-ask rule, which are the highest-stakes facts. Every clause carries information (fail-closed, module ordering, patched files), though the single long sentence-per-idea style is harder to scan than it could be.

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 side-effectful scaffolding tool with no annotations and no output schema, the description covers what changes, what is created, security behavior, ordering constraints, and idempotency—everything an agent needs to call it correctly and warn the user.

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 coverage is 100%, so all three parameters are already documented in the schema. The description adds context about file patching and overwrite/idempotent behavior but does not explain the individual parameters beyond what the schema provides, making the baseline 3 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?

States a specific verb and resource ('Agrega la autorización del borde HTTP al servicio') and enumerates the concrete artifacts created (IAuthorizationVerifier port, default adapter, GLOBAL Guard). This is clearly distinguishable from siblings like scaffold_service or add_use_case.

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?

Explicit when-to-use context: OPT-IN, agent must ask the user, never decide alone or silently omit, created once per service, idempotent. It does not name alternative tools for related security concerns, which keeps it below a 5, but the usage conditions are unusually clear.

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

add_use_caseA

Genera un caso de uso completo (vertical slice hexagonal) en un dominio: puerto inbound/outbound, domain service, application service + interface + spec, adapter (TypeORM por defecto; SP opt-in con nombreSp), controller JSON:API + DTOs, entidad de dominio y TypeORM, catálogos de error, y los módulos del dominio. Escribe en src// (carpeta siempre lowercase; las clases salen en PascalCase sin importar el case de "dominio"). MULTI-CASO: al añadir el 2º/3er caso al MISMO dominio, el MCP MERGEA ese caso en los módulos del dominio ya generados (controller, adapter, providers, tokens, forFeature) — tanto en greenfield como en refactor. En refactor NUNCA toca app.module (eso lo cablea el agente). API EXTERNA: con adapterType="http" (apiExterna, rutaApi, metodoHttp) el caso consume una API con el fetch nativo y NO necesita base de datos, conexion ni motor; declara _BASE_URL en config, Joi y .env.example. SP: con adapterType="sp" el wiring es quirúrgico — apunta el módulo al .sp.adapter y quita del forFeature SOLO la entidad de ese caso, preservando las de los casos TypeORM. INFRA (refactor): usa infraStyle="project" + infraRoot (p.ej. "common") para que los imports de infra apunten a la carpeta del proyecto; aun así, concilia a mano los NOMBRES de clase (ResponseJsonApiBase/GenericException de los templates vs los del proyecto).

NameRequiredDescriptionDefault
casoYesNombre del caso de uso en INGLES y PascalCase, p.ej. "RetrieveProduct" (los archivos resultan kebab-case: retrieve-product.*).
modeNoModo de generación. "greenfield" (default): servicio nuevo, cablea app.module y mergea módulos del dataset. "refactor": proyecto existente — NO toca app.module ni módulos ajenos; genera el slice hexagonal para que el agente lo adapte a la infra del proyecto.greenfield
motorNoMotor de la conexión. Greenfield: obligatorio si la conexión es nueva (el MCP la crea completa); "none" = sin base de datos (rechaza adapters TypeORM/SP). Refactor: solo se pasa, junto con "conexion", cuando el usuario pidió EXPRESAMENTE crear una conexión que el proyecto no tiene; si no, se reutiliza la del proyecto y el motor se ignora. Valores: mssql | postgres | mysql | none.
paramYesParámetro principal del método en camelCase, p.ej. "sku". (Legado: usado solo para el fixture del test generado.)
accionYesRuta del endpoint POST (camel o kebab), p.ej. "retrieveProduct".
metodoYesMétodo del puerto en camelCase, p.ej. "retrieveBySku".
dominioYesNombre del bounded context en INGLES y PascalCase, p.ej. "Catalog" o "StoreConfiguration" (varias palabras = PascalCase; la carpeta resulta kebab-case: store-configuration). Si el usuario lo dio en espanol, traducelo y confirmalo en el plan.
entidadYesNombre de la entidad de dominio en INGLES y PascalCase, p.ej. "Product".
requestNoEntidad de dominio request del método principal en PascalCase, p.ej. "RetrieveProductRequest". Canon: los métodos del puerto reciben una entidad tipada, no un string. Por defecto <Caso>Request.
rutaApiNoSolo adapterType="http": ruta del endpoint de la API externa que llama el metodo, empieza con "/", sin query string, p.ej. "/rates".
conexionNoOPCIONAL: no se le pregunta al usuario. Sin valor, la conexión se llama como su motor (Mssql, Postgres, Mysql): se reutiliza la única conexión de ese motor o se crea una nueva. Pásalo solo para una conexión ADICIONAL de un motor que ya tiene una (Mssql2, Mssql3; inspect_project dice cuál toca) y solo si el usuario la pide. En refactor NO lo pases: la conexión del proyecto se detecta y se reutiliza (solo si el proyecto tiene varias, indica cuál). PascalCase, sin el sufijo Connection.
envVarSpNoNombre de la variable de entorno que porta el SP (MAYÚSCULAS, solo si adapterType="sp"). Por defecto se deriva de nombreSp como <NOMBRE_SP>_SP.
nombreSpNoNombre del stored procedure (solo si adapterType="sp"). El MCP lo registra en ConfigurationVariables.storedProcedures + joiSchema + .env.example.
infraRootNoSolo con infraStyle="project": carpeta (relativa a src/) de la infra transversal propia del proyecto que reemplaza a "shared" en los imports generados, p.ej. "common". Por defecto "common".
overwriteNoSi true, sobrescribe archivos existentes. Por defecto false (no pisa).
apiExternaNoSolo adapterType="http": nombre PascalCase de la API externa, p.ej. "ExchangeRates". Su URL base vive en la variable de entorno <NOMBRE>_BASE_URL (EXCHANGE_RATES_BASE_URL), validada con Joi al arrancar.
infraStyleNoCapa de infraestructura transversal (logger, excepciones, respuesta JSON:API base, config) que importan los archivos generados. "dataset" (default, greenfield): usa la capa shared del dataset (src/shared/*). "project" (refactor): los imports apuntan a la carpeta de infra propia del proyecto (ver infraRoot); el agente aún debe conciliar los NOMBRES de símbolo (p.ej. ResponseJsonApiBase vs ResponseJsonApi del proyecto).dataset
metodoHttpNoSolo adapterType="http": verbo de la llamada. GET (default) envia la request como query string; POST y PUT la envian como cuerpo JSON.
adapterTypeNoTipo de acceso a datos. "typeorm" por defecto. "sp" (stored procedure) es OPT-IN: requiere nombreSp. "http" consume una API externa con fetch nativo y NO usa base de datos: requiere apiExterna y rutaApi (y no necesita conexion ni motor).typeorm
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.
tipoRecursoNoType JSON:API del recurso en kebab-case, en ingles (p.ej. "exchange-rate"). Si se omite: la entidad en kebab-case. Con generate_from_spec sale del resource_type del spec.
prefijoErrorYesPrefijo de errores de la API en mayúsculas. Por ejemplo, CATALOG. Los errores quedarán como CATALOG-PRODUCTNOTFOUND-001; el número va de 001 a 999 y lo asigna el MCP en secuencia por prefijo.
crearConexionNoSOLO refactor, y SOLO si el usuario pidio EXPRESAMENTE crear una conexion. Un refactor reutiliza la conexion que el proyecto ya tiene y, si no tiene ninguna, NO crea una por su cuenta. Con true el MCP crea la conexion completa, nombrada por el motor, asi que tambien hay que pasar el motor (se le pregunta al usuario si no lo dijo).
connectionStyleNoForma de la conexión TypeORM del proyecto. "named" (default): conexión nombrada (<Conexion>Connection). "default": conexión por defecto de forRoot (los adapters no inyectan nombre de conexión). Úsalo según lo que reporte inspect_project.named

TDQS

A3.6/5.0
Behavior4/5

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

No annotations, so the description carries the full burden and mostly succeeds: it discloses write location and casing rules, that later cases MERGE into existing domain modules, that refactor mode leaves app.module alone, and that class-name reconciliation is manual under infraStyle=project. It says nothing about what the tool returns or reports after generation, and overwrite semantics live only in the schema.

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

Conciseness2/5

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

A single dense paragraph mixing purpose, mode rules, adapter rules, merge behavior, and manual reconciliation, with ALL-CAPS fragments instead of headings or bullets. Every fact is relevant, but nothing is grouped, and several clauses (http adapter needs no DB, default adapterType) duplicate schema text the agent already sees.

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 24-parameter generator with no annotations and no output schema, the description covers the critical decision points and side effects an agent needs before calling: mode semantics, adapter variants, merge behavior, and infra reconciliation caveats. Missing pieces are the return payload and whether inspect_project should run first.

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 baseline is 3. The description only re-states a handful of parameters (adapterType modes, nombreSp, apiExterna, infraStyle/infraRoot, motor/conexion defaults) and adds little beyond those schema texts, notably the merge effect of adding a case to an existing domain.

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?

First sentence gives a specific verb and artifact list (hexagonal vertical slice with port, service, adapter, controller, DTOs, entities, error catalogs, modules) written to src/<dominio>/. The scope is unmistakable. It never contrasts itself with generate_from_spec or scaffold_service, so an agent must infer which generator to pick when both could apply.

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?

Rich conditional guidance: greenfield vs refactor (refactor never touches app.module), adapterType selection with prerequisites (sp requires nombreSp, http requires apiExterna/rutaApi and no DB), infraStyle=project with infraRoot for existing projects, and multi-case merge semantics. It stops short of stating when to prefer this over the sibling generate_from_spec, which is the one routing decision left implicit.

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

generate_api_docsA

Genera la documentacion de la API LEYENDO EL CODIGO REAL (controllers, DTOs, catalogos de error), nunca de memoria. Siempre: contrato por modulo (src//contracts/.api.md), diagrama Mermaid sequenceDiagram por modulo (src//diagrams/.flow.mmd) e indice docs/api/README.md, mas docs/ARCHITECTURE.md (diagrama Mermaid architecture-beta; siempre, no se pregunta). Opt-in (el agente PREGUNTA al usuario): postman=true crea docs/api/middleware.postman_collection.json (una coleccion, una carpeta por modulo, fusion sin tocar las demas). Idempotente y determinista; add_use_case y record_architecture la refrescan solos.

NameRequiredDescriptionDefault
modulesNoSolo estos modulos (carpetas bajo src/). Por defecto todos los que tengan controllers.
postmanNoCrear/actualizar docs/api/middleware.postman_collection.json (una coleccion, una carpeta por modulo, fusion sin tocar las demas). El agente debe PREGUNTAR al usuario antes de poner true. Si la coleccion ya existe se actualiza siempre.
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.
architectureNoCrear/actualizar docs/ARCHITECTURE.md con un diagrama Mermaid architecture-beta. Se genera siempre (no se pregunta al usuario); pon false solo si no se quiere.

TDQS

A4/5.0
Behavior4/5

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

With no annotations, the description carries the burden well: it discloses that files are written under specific paths, that output is idempotent and deterministic, that the Postman collection is merged without touching other folders, and that it must read source rather than recall. It omits failure modes (e.g. what happens with no controllers) and any return value.

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

Conciseness3/5

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

The mandatory outputs are front-loaded, which is good, but the body is a dense run-on with nested parentheticals and file paths that make it hard to scan. Sentences are long and mix purpose, policy and artifacts together; restructuring into bullets would earn the space better.

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 multi-file generator with no annotations and no output schema, the description covers what gets produced, where, the default module scope, and idempotency. What's missing is edge-case behavior (no controllers found, existing conflicting docs) and confirmation of what the tool returns to the caller.

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 modules, postman, projectRoot and architecture. The description mostly restates that same policy (postman opt-in, architecture always on), adding little new meaning beyond the schema text. 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?

States a concrete verb and resource ('Genera la documentacion de la API') plus its defining constraint: it reads the real code (controllers, DTOs, error catalogs) rather than memory. It also enumerates the exact outputs (per-module contract, Mermaid sequence diagram, docs/api/README.md, ARCHITECTURE.md), which separates it cleanly from siblings like verify_standards or generate_from_spec.

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?

Gives explicit interaction policy: the agent MUST ask the user before enabling postman, while the architecture doc is generated unconditionally ('siempre, no se pregunta'). It also names the siblings that invoke it implicitly ('add_use_case y record_architecture la refrescan solos'), clarifying it need not be called manually after those. No explicit when-not-to-use case, though.

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

generate_from_specA

Genera un módulo hexagonal a partir de un middleware.spec.yaml declarativo (agnóstico de dominio: module/entity/use_cases los define el usuario en el spec). Soporta casos de uso con N métodos por puerto (inbound/outbound). Con dryRun=true (default) valida el spec y devuelve el PLAN de generación (casos, métodos, archivos) SIN escribir disco; con dryRun=false genera el slice por cada caso reutilizando add_use_case. Respeta las reglas de get_rules.

NameRequiredDescriptionDefault
modeNoModo de generación. "greenfield" (default): servicio nuevo, cablea app.module y mergea módulos del dataset. "refactor": proyecto existente — NO toca app.module ni módulos ajenos; genera el slice hexagonal para que el agente lo adapte a la infra del proyecto.greenfield
dryRunNoSi true (default): valida el spec y devuelve el PLAN de generación SIN escribir disco. Si false: genera el módulo.
specPathYesRuta absoluta al middleware.spec.yaml a generar. La ubicación la decide el usuario (no se impone carpeta).
overwriteNoSi true, sobrescribe archivos existentes. Por defecto false (no pisa).
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.

TDQS

A4.1/5.0
Behavior4/5

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

With no annotations, the description carries the burden well: it discloses that dryRun is the default (safe), that false writes to disk, that it reuses add_use_case, and that it honors get_rules. It doesn't cover failure behavior on invalid specs, permissions, or idempotency, which keeps it off a 5.

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?

Front-loaded with the purpose, then dryRun semantics, then the dependencies on add_use_case and get_rules. Fairly tight, though the dryRun explanation partly duplicates the schema's own description.

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?

With no output schema, the description usefully says what dryRun=true returns (the plan: use cases, methods, files) so the agent knows the shape of the response. Missing only failure-mode and mode-selection detail for a five-parameter file-writing tool.

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 coverage is 100%, so the schema already documents all five parameters including the mode enum and overwrite semantics. The description reinforces dryRun and specPath at a conceptual level but adds no syntax beyond the schema and never mentions the mode parameter's greenfield/refactor distinction.

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 a specific verb and resource ("Genera un módulo hexagonal a partir de un middleware.spec.yaml") plus the scope (domain-agnostic, N methods per inbound/outbound port). It also differentiates from siblings by noting it reuses add_use_case and respects get_rules, so an agent can distinguish it without opening a schema.

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?

Explains the two operational modes clearly: dryRun=true validates and returns a plan without disk writes, dryRun=false generates the slice per use case. However, it doesn't state when to prefer this over scaffold_service or add_use_case directly, nor when-not to use it.

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

get_flowA

Devuelve el procedimiento paso a paso de un flujo (start | greenfield | refactor). Es la ÚNICA fuente del procedimiento: la comparten los prompts del MCP y el agente spec-builder-middleware instalado, para que no haya copias que se desincronicen.

NameRequiredDescriptionDefault
flowYesstart = decide greenfield vs refactor from the workspace state. greenfield = new service. refactor = convert an existing NestJS service.

TDQS

A3.5/5.0
Behavior3/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; "Devuelve" implies a pure read with no side effects, but this is never stated outright. The consistency guarantee (shared with MCP prompts and the spec-builder-middleware agent, no desynchronized copies) is genuinely useful context beyond the name, yet nothing is said about the response form or whether the procedure text depends on workspace state.

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?

Two sentences, front-loaded with what is returned and the flow variants before the design rationale. Both sentences earn their place, though the second is more architectural justification than invocation guidance and could be tightened.

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 single-parameter read tool with full schema coverage and no output schema, the description covers what is returned (step-by-step procedure keyed by flow) and why it is authoritative. The only gap is the shape of the returned procedure, which the agent must discover by calling it.

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% and the enum values are already documented in the schema, including what greenfield vs refactor mean. The description's parenthetical listing of the three values essentially repeats the schema, adding no syntax, default, or selection advice beyond it, so the baseline 3 applies.

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?

States a specific verb and resource ("Devuelve el procedimiento paso a paso de un flujo") and enumerates the three supported flow values, so the agent knows exactly what it retrieves. It also asserts it is the sole source of the procedure, which implicitly separates it from template/rule lookups, but it never names or contrasts with a specific sibling such as get_template or get_rules.

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 claim that this is the "ÚNICA fuente del procedimiento" implies the agent should call it rather than rely on prompt copies or the installed agent, which is useful routing context. However there is no explicit when-to-use/when-not statement and no mention of prerequisites or ordering relative to scaffold_service or inspect_project.

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

get_learningsA

Devuelve lo que el MCP recuerda de ESTE repo por usos anteriores: convenciones (contexto del servicio, prefijos de error y conexiones ya usados), decisiones que el usuario tomo una vez (autorizacion) y los errores del verificador que se repiten en este repo. Es SOLO LECTURA y CONSULTIVO: no sustituye ni relaja las reglas base (get_rules) ni el verificador. Llamala justo despues de get_rules y usa los datos para PROPONER defaults que el usuario confirma. Si no hay nada util, lo dice y no pasa nada.

NameRequiredDescriptionDefault
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.

TDQS

A4.5/5.0
Behavior4/5

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

With no annotations, the description carries the burden and does well: it declares read-only/advisory status, that it does not substitute for base rules or the verifier, and the graceful empty-result behavior ('si no hay nada util, lo dice y no pasa nada'). It does not explain scope/permanence of the stored memory (how it is accumulated or whether results are cached), leaving a small gap.

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?

Front-loaded with what is returned, then the read-only/advisory constraint, then the call ordering. Slightly dense with parenthetical enumerations, but every sentence contributes distinct guidance.

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?

No output schema exists, and the description compensates by naming the three categories of returned content and the empty case. Combined with the sequencing guidance, an agent has enough to call it correctly; only memory-scope details are 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?

Single parameter with 100% schema description coverage, so the baseline is 4. The description adds no extra meaning about projectRoot beyond the schema, which is acceptable at this coverage level.

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 a specific verb and resource: returns what the MCP remembers about THIS repo from prior uses, enumerated as conventions, one-off user decisions, and recurring verifier errors. It explicitly distinguishes itself from the sibling get_rules and from the verifier, so an agent can route correctly without opening the schema.

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?

Gives explicit sequencing ('Llamala justo despues de get_rules') and states the intended downstream action (use the data to PROPOSE defaults that the user confirms). It also names the alternative, get_rules, and clarifies that this tool does not replace or relax it.

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

get_rulesA

Devuelve el cerebro de calidad del área (rules.yaml): las convenciones de arquitectura hexagonal, naming, puertos inbound/outbound multi-método, DTOs JSON:API, acceso a datos (TypeORM/SP), reglas de negocio, catálogo de errores, seguridad y complejidad. Es AGNÓSTICO de dominio (module/entity los pone el usuario) e incluye snippets destilados del repo canónico. El agente DEBE leerlo ANTES de generar un servicio nuevo o refactorizar uno existente.

NameRequiredDescriptionDefault

No parameters

TDQS

A3.8/5.0
Behavior3/5

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

No annotations exist, so the description carries the burden; it does disclose that the payload is domain-agnostic (module/entity supplied by the user) and includes distilled repo snippets, which is useful for interpreting the result. It says nothing about failure behavior (e.g. missing rules.yaml), caching, or whether the content is static — relevant for a file-backed fetch.

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?

Front-loaded with the verb and the artifact name, then a dense but purposeful enumeration of covered topics and a clear imperative. The content list is long but each item maps to a real rules domain; slightly verbose in Spanish prose but no filler.

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?

With no output schema, no annotations and no params, the description does the necessary work: it describes what comes back and when to call it. The only gap is operational behavior (what happens if the rules file is unavailable), which matters for an agent planning a scaffold or refactor.

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?

Zero parameters, so baseline 4 applies; the description correctly reinforces this by stating the tool is domain-agnostic and that module/entity are supplied by the user rather than as arguments.

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?

States a specific verb+resource ('Devuelve el cerebro de calidad del área (rules.yaml)') and enumerates its contents precisely: hexagonal architecture, naming, ports, DTOs, data access, error catalog, security. An agent can distinguish it from get_template or get_learnings by the contents, though no sibling is named explicitly.

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?

Gives an explicit trigger: read it BEFORE generating a new service or refactoring an existing one, which positions it relative to scaffold_service. It lacks any when-not guidance or named alternative, so it stops short of a 5.

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

get_templateA

Devuelve el contenido crudo de una plantilla del dataset por su ruta relativa.

NameRequiredDescriptionDefault
relativePathYesRuta relativa de la plantilla dentro del dataset, p.ej. "shared/utils/services/http-client.service.ts".

TDQS

A3.6/5.0
Behavior3/5

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

No annotations are provided, so the description carries the behavioral burden. It usefully discloses that the return is the raw template content scoped to the dataset, but it does not describe missing-path behavior, permissions, or any other operating context.

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?

A single sentence with no waste, front-loading the action and the key selector. Nothing needs to be trimmed.

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 simple one-parameter getter with a fully documented schema and no output schema, the description gives enough to understand the operation and return form ('contenido crudo'). It could still mention failure behavior or path expectations, but the core is covered.

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%, and the sole parameter is already documented with an example. The description only restates that lookup is by relative path, adding no extra format or constraints beyond the 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 states a specific verb ('Devuelve') and resource ('contenido crudo de una plantilla del dataset') and makes clear the lookup is by relative path. This naturally separates it from list_templates, but it does not explicitly name or contrast against any sibling.

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?

Usage is implied: an agent should call this when it already has a relative template path and wants the raw contents. The description does not explicitly say when to use this versus list_templates or what to do if the path is unknown.

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

inspect_projectA

Descubrimiento del proyecto destino (para el Flujo 2 refactor): detecta la convención de carpetas/case de dominios, la forma de la conexión TypeORM (forRoot por defecto vs conexiones nombradas, replication), la infraestructura transversal ya existente (JSON:API response, tipo de error, middleware, ConfigurationVariables) que debe REUSARSE, y los módulos presentes. Devuelve reglas a respetar antes de generar nada. Sobre el proyecto solo LEE; lo unico que puede escribir es la instalacion automatica del kit de agentes del MCP (.kiro/agents, agentic/templates y la seccion de AGENTS.md) la primera vez que se usa una herramienta en un repo, que es lo que el usuario pidio al configurar el MCP y se desactiva con MIDD_NESTJS_AUTO_KIT=off. Si lo instala, avisa que agente seleccionar.

NameRequiredDescriptionDefault
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.

TDQS

A4/5.0
Behavior4/5

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

With no annotations, the description carries the full burden and does well: it discloses that the project is only READ, and that the sole write is a one-time agent-kit installation (.kiro/agents, agentic/templates, AGENTS.md), disabled via MIDD_NESTJS_AUTO_KIT=off, with a user-facing notice about which agent to select. This is unusually complete side-effect disclosure; only return-format/pagination-like details are absent.

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

Conciseness3/5

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

The purpose is front-loaded, but the body is a single sprawling run-on sentence that crams detection targets, reuse rules, and the agent-kit write exception into one block. It is informative but would benefit from splitting the discovery scope from the side-effect disclosure.

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 complex discovery tool with a fully documented single param and no output schema, the description explains what it returns (rules to respect) and covers the one surprising behavior (kit install on first use). An agent has enough to call it correctly, though the return shape is only loosely sketched.

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?

There is a single parameter (projectRoot) with 100% schema description coverage, so the schema already documents it fully. The description adds no syntax or constraint detail beyond what the schema provides, making the baseline 3 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 names a specific verb+resource (project discovery of the target NestJS repo) and enumerates concrete artifacts it detects: folder/case conventions, TypeORM connection shape, transversal infrastructure, present modules. It also distinguishes itself from the generation siblings by framing itself as producing rules to respect 'antes de generar nada'.

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?

It scopes usage to 'Flujo 2 refactor' and states the output is rules to apply before generating anything, implying it runs ahead of scaffold_service/generate_from_spec. It does not explicitly name those alternatives or state when-not-to-use, so it falls short of a 5.

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

install_agentic_kitA

Instala (o actualiza) en el repo consumidor el punto de entrada del MCP: los agentes middleware-generator (el unico que se selecciona), middleware-gen-worker y middleware-auditor (.kiro/agents), la plantilla del middleware.spec.yaml (agentic/templates) y la sección del MCP en AGENTS.md (entre marcadores BEGIN/END; el resto del archivo no se toca). Idempotente: volver a correrla actualiza a la versión del MCP. Un archivo con el mismo nombre que no instaló este MCP se respeta salvo overwrite=true. Úsala cuando el usuario quiera dejar el repo listo para crear servicios con el MCP.

NameRequiredDescriptionDefault
modelsNoSobrescribe el modelo de cada agente. Los defaults son los del kit de lib-midd-mcp-architecture. Como volver a instalar reemplaza los archivos, usa este parametro para cambiar un modelo en vez de editar el .md a mano.
overwriteNoSi false (default), un archivo con el mismo nombre que NO fue instalado por este MCP se respeta y se reporta. Si true, lo reemplaza.
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.

TDQS

A3.9/5.0
Behavior4/5

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

With no annotations, the description carries full burden and does well: it discloses idempotency (re-running updates to the MCP version), non-destructive default behavior (files not installed by this MCP are respected unless overwrite=true), and marker-scoped editing of AGENTS.md so the rest of the file is untouched. It omits any mention of permissions or what the call reports back.

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?

Information is front-loaded: what gets installed first, then the idempotency/overwrite contract, then the usage trigger. It is dense but nearly every clause carries distinct operational detail; only the file enumeration is slightly long.

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 3-parameter mutation tool with no output schema, the description covers target files, safety behavior, and the select-the-orchestrator detail that matters when calling it. Missing only return/report information and permission expectations.

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 including the models defaults and the overwrite semantics. The description reinforces the overwrite rule consistently with the schema but adds no extra syntax or constraint detail beyond it, making the baseline of 3 appropriate.

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?

States a specific verb (installs/updates) plus an enumerated resource list (middleware agents, spec template, AGENTS.md section), leaving no ambiguity about what gets written. It does not explicitly name a sibling to distinguish against, but the scope (repo bootstrap) is clearly different from scaffolding-oriented siblings.

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 closing sentence gives a clear trigger: use it when the user wants the repo ready to create services with the MCP. It also implies a precondition via 'repo consumidor'. No explicit when-not or named alternative (e.g., scaffold_service) is given.

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

list_templatesC

Lista las plantillas disponibles en el dataset (shared, config, _domain-slice).

NameRequiredDescriptionDefault
subdirNoSubconjunto del dataset a listar.all

TDQS

C2.9/5.0
Behavior2/5

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

No annotations are provided, so the description carries the full behavioral burden. "Lista" implies a read operation, but the description does not state read-only status, permissions, pagination, return format, or any other operational context.

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 front-loaded sentence with no wasted words. The parenthetical example list is compact, though it is incomplete relative to the schema enum.

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 one-parameter list tool, the description is minimally adequate. However, with no annotations or output schema, it could better explain return behavior, and its subset examples omit two schema enum values including the default all.

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 defines the subdir parameter and its enum values. The description mentions three subsets parenthetically but does not add meaning beyond the schema, and omits the authorization and all enum values.

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 uses a specific verb ("Lista") and resource ("plantillas") and scopes it to the dataset. It implicitly distinguishes itself from get_template by focusing on listing rather than fetching a single template, but it does not name any sibling explicitly.

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

Usage Guidelines2/5

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

There is no explicit guidance on when to use this tool versus alternatives such as get_template. The listing intent is implied, but no conditions, prerequisites, or exclusions are stated.

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

record_architectureA

Registra un módulo en docs/architecture-inventory.json (envelope con mcpVersion/generatedAt; una entrada por módulo, sin tocar las de otros) y escribe docs/audits/-.md. Lee el middleware.spec.yaml del módulo para no duplicar datos; acepta compliance (salida de verify_standards), estado de build y decisiones. Es la memoria por repo del MCP: léela al abrir una sesión futura para no duplicar módulos.

NameRequiredDescriptionDefault
specPathYesRuta absoluta al middleware.spec.yaml del módulo a inventariar/auditar.
decisionsNoDecisiones de diseño tomadas durante la generación/refactor, para la auditoría.
complianceNoSalida de verify_standards (u observaciones) para la sección de compliance de la auditoría.
buildStatusNoResultado de build/tests para la auditoría (p.ej. "build OK, 12 tests en verde").
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.
writeAuditFileNoSi true (default), escribe también docs/audits/<module>-<fecha>.md además del inventario.

TDQS

A4.1/5.0
Behavior4/5

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

With no annotations at all, the description carries the full burden and does disclose key mutation semantics: it writes two file types, merges one entry per module 'sin tocar las de otros', and uses an envelope with mcpVersion/generatedAt. It omits what happens on re-registration of the same module (overwrite vs. append), required filesystem permissions, and error behavior.

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, front-loaded with the write targets and followed by inputs and the memory rationale; little waste. The final sentence about being 'la memoria por repo del MCP' is useful routing context rather than filler.

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 6-parameter mutation tool with no output schema, it covers artifacts written, data sources read, and cross-session usage well. The remaining gap is the return value / confirmation shape, which an agent would need to verify the write succeeded.

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 coverage is 100%, so the schema already documents all six parameters including compliance ('Salida de verify_standards') and buildStatus. The description mostly restates those fields rather than adding syntax or format guidance, and it never mentions writeAuditFile, which lets the caller opt out of the audit file it describes as always written.

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 a specific verb (registra) plus the exact resources touched: docs/architecture-inventory.json and docs/audits/<module>-<fecha>.md. It also names the source artifact it consumes (middleware.spec.yaml, verify_standards output), so an agent can distinguish it from pure documentation generators like generate_api_docs or verify_standards.

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?

Gives clear context for use: call it after generating/refactoring a module, feeding it compliance, build status and decisions; and read the inventory at the start of a future session to avoid re-registering modules. It lacks an explicit exclusion versus the sibling record_decision, which overlaps conceptually with the 'decisions' parameter.

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

record_decisionA

Registra una decision que el USUARIO tomo de forma explicita y que vale para todo el repo, para no volver a preguntarla en la siguiente sesion. Lista cerrada: authorization = enabled | disabled. Solo con una respuesta clara del usuario; nunca por suposicion del agente. Escribe en docs/mcp-learnings.json.

NameRequiredDescriptionDefault
valueYes"enabled" o "disabled" (solo si el usuario lo dijo de forma explicita). Se guarda en AGENTS.md, a la vista, para no volver a preguntarlo.
decisionYesDecision del usuario para todo el repo. Lista cerrada: authorization y postman (coleccion de Postman).
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.

TDQS

A3.6/5.0
Behavior3/5

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

No annotations, so the description carries the full burden. It usefully discloses the effect (persist across sessions) and the write target, but it does not say whether an existing decision is overwritten, what permissions are needed, or what the response looks like; it also conflicts with the schema's claim that the value is written to AGENTS.md rather than docs/mcp-learnings.json.

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?

Compact and front-loaded: what is recorded comes first, followed by constraints and the write target. No filler, though the closing file reference adds a contradiction rather than clarity.

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?

With no annotations and no output schema, the description must cover behavior on its own. It covers purpose, trigger discipline, and persistence, but leaves overwrite/merge semantics and the full decision set unaddressed and introduces a destination inconsistency an agent cannot resolve.

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 baseline is 3. The description only restates part of the 'decision' enum (authorization) and the value set, omitting 'postman', and its stated output location contradicts the schema's per-parameter notes.

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?

Specific verb+resource: records an explicit user decision that applies repo-wide so it isn't asked again next session, and names the storage file. The scope is clear, though it only enumerates 'authorization' while the schema also allows 'postman', leaving the full purpose slightly under-stated.

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?

Gives an explicit when-to-use (a decision already made that must persist) and a firm when-not ('solo con una respuesta clara del usuario; nunca por suposicion del agente'). It does not name alternatives such as record_architecture, so routing between the two record_* siblings 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.

scaffold_serviceA

Genera la base de un servicio NestJS hexagonal nuevo: capa shared completa (JSON:API, errores, logger, config+Joi, database-context, utils), archivos de config/enforcement (eslint, prettier, Dockerfile, verify-standards, hooks husky), main.ts y app.module.ts canónicos. Escribe en projectRoot. OBLIGATORIOS y SIEMPRE se le preguntan al usuario (no se inventan ni tienen valor por defecto): prefijoApi, prefijoError y motor (mssql | postgres | mysql | none); si falta alguno la herramienta no genera nada y dice cuál preguntar.

NameRequiredDescriptionDefault
motorNoMotor de base de datos: mssql (SQL Server), postgres (PostgreSQL) o mysql (MySQL), o "none" si el servicio NO usa base de datos (no se crea ninguna conexión, ni módulo, ni variables, ni driver). SIEMPRE se le pregunta al usuario: no hay default. Define el tipo de TypeORM, el driver, el puerto y la sintaxis de los stored procedures.
conexionNoOPCIONAL: no se le pregunta al usuario. Sin valor, la conexión se llama como su motor (Mssql, Postgres, Mysql): se reutiliza la única conexión de ese motor o se crea una nueva. Pásalo solo para una conexión ADICIONAL de un motor que ya tiene una (Mssql2, Mssql3; inspect_project dice cuál toca) y solo si el usuario la pide. En refactor NO lo pases: la conexión del proyecto se detecta y se reutiliza (solo si el proyecto tiene varias, indica cuál). PascalCase, sin el sufijo Connection.
overwriteNoSi true, sobrescribe archivos existentes. Por defecto false (no pisa).
prefijoApiNoPrefijo de la API en kebab-case. Por ejemplo, midd-catalog. Los endpoints quedarán como /<prefijo>/api/v1/{recurso}. Se guarda como API_CONTEXT (prefijo global). Pregúntalo como "prefijo de la API", no como prefijo del servicio.
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.
prefijoErrorNoPrefijo de errores de la API en mayúsculas. Por ejemplo, CATALOG. Los errores quedarán como CATALOG-PRODUCTNOTFOUND-001; el número va de 001 a 999 y lo asigna el MCP en secuencia por prefijo.

TDQS

A4.3/5.0
Behavior4/5

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

With no annotations, the description carries the burden well: it discloses the write target (projectRoot), the overwrite default of false (no pisa), and the fail-closed behavior when mandatory params are absent. It stops short of describing the response/return shape or idempotency on re-runs, which is a meaningful gap for a mutation 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?

The output scope is front-loaded before the mandatory-parameter rules, and every clause maps to actionable behavior. The file enumeration is dense but earns its place by telling the agent what the tool creates; two long sentences is reasonably tight for the amount of behavior conveyed.

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 6-param mutation tool with no annotations and no output schema, the description covers scope, write location, overwrite semantics, and the hard prerequisite on three parameters. The main remaining gap is what the agent should expect back (created file list, refusal message format) after invocation.

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 coverage is 100%, so the baseline is 3, but the description adds real meaning: it names the three mandatory, never-defaulted parameters and states the consequence of omission, which is not fully spelled out for prefijoApi/prefijoError in the schema. Other params (overwrite, conexion) are left to the already-rich 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 a specific verb and resource (generate the base of a new hexagonal NestJS service) and enumerates exactly what gets written (shared layer, config/enforcement files, main.ts, app.module.ts) and where (projectRoot). This is clearly distinguishable from siblings like add_use_case, generate_from_spec, or install_agentic_kit.

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?

Implies a greenfield/new-service context and explicitly flags that prefijoApi, prefijoError and motor are always asked to the user and never defaulted, with the tool refusing to generate if any is missing. It does not, however, explicitly contrast itself with generate_from_spec or add_use_case, which would be the natural alternatives an agent might confuse it with.

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

verify_standardsA

Ejecuta la verificación de estándares (naming, cabeceras de seguridad, @Version, .env.example, SP opt-in) sobre el proyecto destino. Devuelve el reporte; falla si hay errores bloqueantes.

NameRequiredDescriptionDefault
projectRootYesRuta absoluta de la raíz del servicio NestJS destino donde se escriben los archivos.
installScriptNoSi true, copia verify-standards.mjs a scripts/ del proyecto antes de ejecutarlo.

TDQS

A3.5/5.0
Behavior3/5

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

With no annotations, the description carries the full burden, and it does disclose two useful traits: it returns a report and it fails when blocking errors are found. It does not disclose that the tool writes into the target project (copying verify-standards.mjs to scripts/ when installScript is true), nor whether the run is idempotent or what permissions the project root requires.

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?

Two tight sentences: the first front-loads what is verified with a concrete checklist, the second covers the return and failure behavior. Nothing is redundant or padded.

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 tool with no annotations and no output schema, the description should say more: the shape of the returned 'reporte' is undefined, and the side effect of writing a script into the project is only discoverable via the schema. The essential invocation contract is present, but behavioral completeness has clear gaps.

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 both projectRoot and installScript are already documented in the schema, and the description adds no parameter-level detail. Baseline 3 applies since the schema does the work and the description merely implies scope with 'proyecto destino'.

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?

States a specific verb ('Ejecuta la verificación') plus the resource (estándares del proyecto) and enumerates the exact checks performed (naming, cabeceras de seguridad, @Version, .env.example, SP opt-in), which lets an agent distinguish it from siblings like get_rules or inspect_project. It stops short of naming a sibling explicitly, so it is clear but not fully differentiated.

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 phrase 'sobre el proyecto destino' implies this runs against an already-scaffolded target project, which gives some usage context. However, there is no explicit statement of when to call it versus get_rules or inspect_project, and no preconditions (e.g., that the project must already exist) are spelled out.

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. 15 tool updatesv0.1.0
    • First observedadd_authorization
    • First observedadd_use_case
    • First observedgenerate_api_docs
    • First observedgenerate_from_spec
    • First observedget_flow
    • First observedget_learnings
    • First observedget_rules
    • First observedget_template
    • First observedinspect_project
    • First observedinstall_agentic_kit
    • First observedlist_templates
    • First observedrecord_architecture
    • First observedrecord_decision
    • First observedscaffold_service
    • First observedverify_standards

TDQS

A3.8/5.0

Scored across 15 tools

Disambiguation4/5

Most tools have clearly distinct purposes: retrieval (get_rules, get_flow, get_learnings, list/get templates), generation (scaffold_service, add_use_case, generate_from_spec), and workflow helpers (inspect_project, verify_standards, install_agentic_kit). The main overlap is among the three generation tools, but their descriptions make the boundaries reasonably clear (base scaffold vs. vertical slice vs. spec-driven module).

Naming Consistency5/5

All tool names use consistent snake_case verb_noun form: get_template, scaffold_service, add_use_case, record_decision, install_agentic_kit, inspect_project, generate_from_spec, verify_standards, etc. No mixed casing or inconsistent verb style.

Tool Count5/5

15 tools is within the well-scoped range and each tool maps to a distinct phase of the NestJS hexagonal generation lifecycle: templates, rules, flows, scaffolding, use cases, authorization, inspection, verification, documentation, and repo memory. The count feels earned rather than padded.

Completeness4/5

The surface covers the full generation lifecycle well: discovery, rules/flow retrieval, scaffolding, use-case addition, spec-driven generation, verification, documentation, and persistent repo memory. Minor gaps exist around explicit update/removal operations for previously generated modules or use cases, but core workflows are covered.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    A
    maintenance
    Builds rich code graphs from TypeScript/NestJS codebases using AST analysis and Neo4j, enabling semantic search, natural language querying, and intelligent graph traversal to provide deep contextual understanding of code relationships and dependencies.
    1,082 npm
    17
    MIT
  • A
    license
    B
    quality
    D
    maintenance
    An MCP server that exposes structured Functional Requirements Documents (FRDs) to enable AI assistants like GitHub Copilot to automatically generate complete NestJS boilerplate architectures. It orchestrates the multi-phase creation of production-ready APIs including core CRUD, database integration, JWT authentication, and unit testing.
    1
    MIT