bpmn-generator-mcp
# BPMN Generator MCP
**MCP (Model Context Protocol) server** que genera y **reconstruye** diagramas **BPMN 2.0** desde múltiples fuentes: texto, templates, YAML/JSON, imágenes (OCR) y diagramas escaneados (visión por computadora). El output se importa directamente en **Bizagi Modeler**, Camunda Modeler, bpmn.io y cualquier herramienta compatible con el estándar OMG BPMN 2.0.
> **Stack dual**: TypeScript (capa MCP) + Python (visión por computadora). Dockerizado en **una sola imagen**.
---
## ✨ Características
### 🎨 **44 herramientas MCP** registradas
- **6 de generación**: `create_simple_linear_process`, `create_process_with_decision`, `create_process_with_parallel`, `create_from_yaml_spec`, `create_process_from_text_description`, `create_process_from_image` (OCR)
- **3 de visión** *(NUEVO)*: `reconstruct_bpmn_from_image` (PaddleOCR + YOLO + OpenCV), `preview_bpmn_ir`, `validate_bpmn_ir`
- **8 de conocimiento BPMN**: `list_bpmn_elements`, `get_bpmn_cheatsheet`, `get_event_matrix`, `explain_bpmn_concept`, etc.
- **6 de plantillas**: 9 plantillas predefinidas (aprobación, pedidos, onboarding, etc.)
- **6 de subprocesos avanzados**: subproceso, call activity, boundary events, error handling, transactions, loops/multi-instance
- **2 de eventos**: timer, message, signal, error, escalation, etc.
- **2 de validación**: `validate_bpmn_file`, `validate_bpmn_xml`
- **2 de OCR**: `is_ocr_available`, `extract_text_from_image`
- **3 de files**: `get_output_directory`, `list_generated_files`, `read_bpmn_file`
- **2 de subprocess**: `add_event_with_trigger`, `create_process_with_timer`
- **4 prompts** predefinidos: `design_bpmn_process`, `review_bpmn_process`, `convert_description_to_bpmn`, `bpmn_best_practices`
### 🧠 **Knowledge Base** BPMN 2.0 exhaustivo
- **41 tipos de eventos** (start/intermediate/end/boundary × todos los triggers)
- **13 actividades** (tasks + subprocesos: embedded, call, ad-hoc, event, transaction)
- **5 gateways** (exclusive, parallel, inclusive, event-based, complex)
- **30+ atributos** del estándar
- **5 marcadores** (loops, multi-instance, compensation)
- **30+ reglas de validación**
- **9 plantillas** de procesos comunes
- **4 categorías** de paleta Bizagi
- **Especificidades de Bizagi** Modeler
### 🛡️ **Seguridad Hardened**
- Path traversal sandbox (path.resolve + relative_to)
- XXE prevention (`fast-xml-parser` con `processEntities: false`)
- Resource limits anti-DoS (MAX_TASKS, MAX_XML_SIZE, MAX_IMAGE_SIZE_BYTES)
- Unicode normalization NFC + filtrado zero-width/bidi
- Exception sanitization (no exponer paths internos)
- Race condition locks (Mutex en BPMNGenerator)
- Non-root Docker user (uid 1001)
- Pinned dependency versions (`package.json` con `==` exactos)
### 🏗️ **Calidad de código**
- **TypeScript strict mode** + `noUncheckedIndexedAccess`
- **Python con type hints** en todas las funciones
- **< 700 LOC por archivo** (regla dura)
- **Tests reproducibles**: 8/8 archivos BPMN válidos en suite completa
- **Pydantic + Zod** schemas sincronizados (23 tipos BPMN) entre Python y TS
---
## 📦 Stack Técnico
| Capa | Tecnología |
|------|-----------|
| **MCP Server** | TypeScript + `@modelcontextprotocol/sdk` 1.0.4 + `mcp-shim` custom |
| **Validación** | `zod` (TS) + `pydantic` (Py) |
| **XML BPMN** | `fast-xml-parser` 4.5.0 + post-processing regex |
| **Logging** | `pino` estructurado |
| **OCR TS** | `tesseract.js` 5.1.1 + `sharp` 0.33.5 |
| **OCR Py** | `PaddleOCR` 3.0.3 + `PP-StructureV3` (bbox precisos) |
| **Detección símbolos** | `Ultralytics YOLO` (entrenable, transfer learning COCO) |
| **Geometría** | `OpenCV` 4.10 (HoughLinesP, contornos, convex hull farthest-pair) |
| **Grafo** | `NetworkX` 3.3 + `scipy.spatial.KDTree` |
| **Imagen Docker** | `node:22-slim` + `python:3.11-venv` multi-stage |
---
## 🏗️ Arquitectura
```
bpmn-generator-mcp/
├── src/ # TypeScript MCP server (4978 LOC, 47 archivos)
│ ├── server.ts # Entry point (stdio MCP)
│ ├── constants.ts # BPMN namespaces, security limits
│ ├── schemas/ # Zod schemas para MCP inputs
│ ├── utils/ # logger, errors, sandbox
│ ├── bpmn/ # Generador BPMN (core, builders, elements, DI)
│ ├── knowledge/ # Catálogo BPMN 2.0
│ ├── mcp-tools/ # 44 tools + 4 prompts
│ └── vision/ # Cliente HTTP al vision pipeline Python
├── vision-pipeline/ # Python vision (2245 LOC, 17 archivos)
│ ├── src/vision_pipeline/
│ │ ├── ocr/ # PaddleOCR wrapper
│ │ ├── detection/ # YOLO 17 clases BPMN
│ │ ├── geometry/ # OpenCV preprocessing + arrows
│ │ ├── graph/ # NetworkX + KDTree mapping
│ │ ├── ir/ # Pydantic BPMNIR (23 tipos)
│ │ └── bridge/ # CLI subprocess + FastAPI server
│ ├── tools/ # ⭐ scrape, generate, train
│ ├── requirements.txt # Deps pinned
│ ├── data/ # scraped + yolo_dataset (gitignored)
│ └── PLAN.md # Plan completo
├── migration/ # Trazabilidad Python→TS (47 microtareas)
├── .agents/ # ⭐ Reglas persistentes (claude.md, rules.md, agents.md)
├── tests/ # test-all.ts + test-final.ts
├── examples/ # ejemplo-basico.ts
├── Dockerfile # ⭐ UN SOLO multi-stage (Node + Python)
├── docker-compose.yml
├── package.json # ESM, deps pinned
├── tsconfig.json # strict + noUncheckedIndexedAccess
├── tsconfig.build.json # Solo src/ para producción
├── .dockerignore
└── .gitignore
```
---
## 🚀 Instalación y Uso
### Opción 1: Docker (Recomendado para producción)
```bash
# Build de la imagen unificada (~5 min, descarga PaddleOCR + YOLO)
docker build -t bpmn-generator-mcp:latest .
# Ejecutar el servidor MCP via stdio
docker run -i --rm \
-v "C:\Users\LENOVO\.agents\mcps\bpmn-generator-mcp\output:/app/output" \
-v "C:\Users\LENOVO\.Pictures:/mnt/pictures:ro" \
bpmn-generator-mcp:latest
# O usar docker-compose
docker compose up -d
```
La imagen Docker incluye:
- ✅ Node.js 22 + TypeScript compilado (4978 LOC)
- ✅ Python 3.11 + venv con PaddleOCR + YOLO + OpenCV
- ✅ Tesseract OCR (spa + eng)
- ✅ Usuario no-root `bpmn` (uid 1001, SEC-011)
- ✅ Comunicación Node ↔ Python vía subprocess CLI
### Opción 2: Desarrollo TS local (sin Docker)
```bash
# Solo para editar/compilar el TypeScript MCP server
npm install
npm run build # tsc -> dist/
npm test # tsx tests/test-all.ts && tsx tests/test-final.ts
# Ejecutar el MCP server
npm start # node dist/server.js
```
### Opción 3: Desarrollo Python del vision pipeline (en venv)
```bash
# ⚠️ NUNCA uses `pip install -e .` global
# Usa siempre un entorno virtual LOCAL
cd vision-pipeline
python -m venv .venv # Crea .venv/ (gitignored)
.venv\Scripts\activate.bat # Windows
# source .venv/bin/activate # Linux/Mac
pip install -r requirements.txt
```
---
## 🔧 Configuración MCP en opencode
El archivo `~/.config/opencode/opencode.jsonc` debe apuntar al container Docker:
```jsonc
"bpmn-generator": {
"type": "local",
"enabled": true,
"timeout": 60000,
"command": [
"docker", "run", "-i", "--rm",
"-v", "C:\\Users\\LENOVO\\.agents\\mcps\\bpmn-generator-mcp\\output:/app/output",
"-v", "C:\\Users\\LENOVO\\Pictures:/mnt/pictures:ro",
"bpmn-generator-mcp:latest"
],
"environment": {
"BPMN_OUTPUT_DIR": "/app/output",
"LOG_LEVEL": "info"
}
}
```
Hay una entrada legacy `bpmn-generator-python` (deshabilitada) por si se necesita rollback.
---
## 🤖 Entrenamiento del modelo YOLO (visión)
### Pipeline completo (3 pasos)
```bash
cd vision-pipeline
.venv\Scripts\activate.bat
# Paso 1: Scraping de imágenes reales (Wikimedia + DuckDuckGo + GitHub)
python tools/scrape_bpmn_images.py \
--query "bpmn diagram example" \
--output data/scraped \
--max 200
# Paso 2: Generación de imágenes sintéticas (Graphviz + PIL fallback)
python tools/generate_synthetic_dataset.py \
--output data/yolo_dataset \
--num 1000
# Paso 3: Anotar las imágenes scrapeadas con LabelImg o Roboflow
# (manual, formato YOLO: class_id x_center y_center width height)
# Paso 4: Entrenar YOLO con transfer learning desde COCO
python tools/train_yolo.py \
--data data/yolo_dataset \
--model yolo11n.pt \
--epochs 100
```
**Salida del training**: `weights/bpmn_best.pt` (modelo entrenado con tus datos).
**17 Clases BPMN soportadas** (sincronizadas entre Python y TS):
| ID | Clase | Tipo |
|----|-------|------|
| 0 | startEvent | Evento |
| 1 | endEvent | Evento |
| 2 | intermediateEvent | Evento |
| 3 | task | Tarea |
| 4 | userTask | Tarea |
| 5 | serviceTask | Tarea |
| 6 | manualTask | Tarea |
| 7 | scriptTask | Tarea |
| 8 | exclusiveGateway | Gateway |
| 9 | parallelGateway | Gateway |
| 10 | inclusiveGateway | Gateway |
| 11 | subProcess | Sub-proceso |
| 12 | callActivity | Sub-proceso |
| 13 | pool | Swimlane |
| 14 | lane | Swimlane |
| 15 | sequenceFlow | Conector |
| 16 | messageFlow | Conector |
**Limitación**: solo 13/17 clases son sintetizables con bbox rectangular. `pool`, `lane`, `sequence_flow`, `message_flow` requieren datos scrapeados anotados manualmente.
### Tiempos estimados
- **CPU** (i7-12700): 5-15 min/epoch × 100 = ~8-25 horas total
- **GPU** (RTX 3060+): 1-2 min/epoch × 100 = ~2-4 horas total
---
## 🧪 Testing
```bash
# TypeScript build (producción)
npx tsc -p tsconfig.build.json --noEmit # exit 0
# Suite completa TS (8 tests, genera 8 archivos BPMN válidos)
npx tsx tests/test-all.ts
# Verificar tools MCP registradas
npx tsx tests/test-final.ts
# Python parse check (sin instalar deps)
python -c "import ast; ast.parse(open('vision-pipeline/tools/scrape_bpmn_images.py').read())"
```
**Resultados esperados**:
- `tsc -p tsconfig.build.json`: exit 0
- `test-all.ts`: 8 archivos `.bpmn` generados, 8/8 válidos
- `test-final.ts`: 44 tools + 4 prompts listadas
---
## 🐛 Debug
### Ver logs del MCP server
```bash
docker logs bpmn-generator-mcp
```
### Logs estructurados (niveles)
- `LOG_LEVEL=debug` → máxima verbosidad
- `LOG_LEVEL=info` (default)
- `LOG_LEVEL=warn` → solo warnings
### Vision pipeline debug
```bash
# Probar CLI directamente
echo '{"image_path": "test.jpg"}' | docker exec -i bpmn-generator-mcp \
python -m vision_pipeline.bridge.cli
```
---
## 📜 Reglas de Contribución
Ver `.agents/claude.md` (reglas de memoria), `.agents/rules.md` (reglas duras) y `.agents/agents.md` (configuración de subagentes).
### Reglas Hard (NO ROMPER)
1. **NO archivos >700 LOC**
2. **NO commitear** `node_modules/`, `dist/`, `*.traineddata`, `.venv/`
3. **Trazabilidad** en microtareas para features >500 LOC
4. **Backup antes de cambios grandes** → `~/.config/opencode/backups/`
5. **TS strict** mode obligatorio
6. **NO `pip install -e .` global** — usar venv local
7. **TODOS los `add_*` métodos del BPMNGenerator DEBEN registrar en `elementsLayout`**
8. **Post-processing en `toXmlString`** — fast-xml-parser bug con boolean
9. **Dockerfile multi-stage** con non-root
10. **YOLO_CLASSES sincronizado** Python ↔ TypeScript
### Bugs Históricos (NO reintroducir)
1. ~~`createProcess` retornaba `undefined`~~ → usar `this._definitions['bpmn:definitions']['bpmn:process']`
2. ~~XML `<bpmn:process>` duplicado~~ → no mirror top-level
3. ~~Circular import rompía registro~~ → usar `register.ts` separado
4. ~~fast-xml-parser serializa `'true'` como self-closing~~ → post-processing regex
5. ~~`isExecutable` boolean inválido en BPMN 2.0 strict~~ → eliminado
---
## 📊 Estadísticas del Proyecto
| Métrica | Valor |
|---------|-------|
| **Total LOC TS** | 4,978 (47 archivos en `src/`) |
| **Total LOC Python** | 2,245 (17 archivos en `vision-pipeline/`) |
| **MCP Tools** | 44 |
| **MCP Prompts** | 4 |
| **BPMN Templates** | 9 |
| **Knowledge entries** | 100+ |
| **Microtareas migración** | 47 (completadas) |
| **Microtareas vision pipeline** | 18/35 (Fases 1-7 completas) |
| **Tests** | 8/8 BPMN válidos + 63/63 Python checks |
---
## 🤝 Licencia y Créditos
Proyecto educativo de **TECSUP** - Integración de Sistemas Empresariales (Week 2).
Tecnologías usadas:
- [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk) (Apache 2.0)
- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR) (Apache 2.0)
- [Ultralytics YOLO](https://github.com/ultralytics/ultralytics) (AGPL-3.0)
- [OpenCV](https://opencv.org/) (Apache 2.0)
- [NetworkX](https://networkx.org/) (BSD-3-Clause)
- [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) (MIT)
---
## 🔗 Links
- **Repositorio**: https://github.com/johnleyva28/bpmn-generator-mcp
- **Bizagi Modeler**: https://www.bizagi.com/es/platform/modeler
- **BPMN 2.0 Spec**: https://www.omg.org/spec/BPMN/2.0/
- **MCP Protocol**: https://modelcontextprotocol.io/
---
## 🎯 Próximos Pasos
1. **Entrenar YOLO** cuando tengas GPU + dataset (100 scraped + 1000 sintético)
2. **Anotar imágenes scrapeadas** con LabelImg/Roboflow (manual, ~30-60 min para 100 imágenes)
3. **Re-entrenar** con dataset completo
4. **Build & deploy**:
```bash
docker build -t bpmn-generator-mcp:vision .
docker push your-registry/bpmn-generator-mcp:vision
```
5. **Monitorear** el uso de las tools MCP en producciónTDQS
Scored across 41 tools
Many tools are clearly distinct, but the set includes several overlapping reference/catalog tools (e.g., get_flow_elements_catalog vs list_bpmn_elements, get_activities_catalog vs get_task_types_info) and closely related creation variants (e.g., create_process_with_boundary_events vs create_process_with_error_handling). Descriptions help, but an agent could easily select the wrong lookup or generator in a 41-tool surface.
Tool names consistently use snake_case and mostly follow a verb_noun pattern, which is predictable. Minor deviations exist, such as create_from_yaml_spec vs create_process_from_text_description vs create_simple_linear_process, but the overall style remains coherent.
With 41 tools, the server is over-scoped for most agent workflows. The many catalog/reference/lookup tools could be consolidated into a smaller set, and the proliferation of create_process_with_* variants adds unnecessary bulk.
The server covers BPMN generation well: multiple construction patterns, validation, templates, catalogs, OCR input, and output file access. Minor gaps exist around updating/deleting generated files or directly editing existing BPMN models, but these are not core to a generator's main workflow.