Skip to main content
Glama
johnleyva28

bpmn-generator-mcp

by johnleyva28

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


Related MCP server: MCP-BPMN Server

📦 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)

# 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)

# 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)

# ⚠️ 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:

"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)

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

# 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

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

# 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:



🎯 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:

    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ón

F
license - not found
C
quality
B
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

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

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    An MCP server that enables AI assistants to programmatically create, modify, and export BPMN 2.0 workflow diagrams. It supports managing various process elements and sequence flows while providing export capabilities to standard XML and SVG formats.
    7
    11
    MIT
  • F
    license
    B
    quality
    D
    maintenance
    Enables AI agents to create, manipulate, and manage BPMN 2.0 diagrams programmatically, with support for Mermaid conversion, auto-layout, and file persistence.
    24
    9
  • F
    license
    Not graded
    quality
    F
    maintenance
    Enables AI-driven graphical diagram creation and manipulation using natural language, with support for BPMN workflows, analysis, and manual editing via the Model Context Protocol.
    1
  • A
    license
    B
    quality
    D
    maintenance
    A Model Context Protocol (MCP) server that enables AI assistants to interact with Camunda Platform workflow engine. Provides 21 specialized tools for complete workflow automation and process management.
    21
    5
    MIT

View all related MCP servers

Related MCP Connectors

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/johnleyva28/bpmn-generator-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server