From 4b53c1b6e266ee04e909b6df6393724866dc1c84 Mon Sep 17 00:00:00 2001 From: Rodrigo Date: Wed, 11 Nov 2026 10:28:02 -0400 Subject: [PATCH] feat: implement bpmn-auto-layout-extended --- ProcessMaker/Mcp/McpSystemSkills.php | 8 ++ .../Mcp/Processes/BpmnLayoutException.php | 11 ++ .../Mcp/Processes/BpmnLayoutService.php | 104 +++++++++++++++ .../Mcp/Processes/ProcessBpmnValidator.php | 85 ++++++++++++ ProcessMaker/Mcp/Processes/ProcessCatalog.php | 76 ++++++++++- ProcessMaker/Mcp/Servers/ProcessServer.php | 3 + .../Mcp/Tools/Processes/CreateProcessTool.php | 1 + .../Mcp/Tools/Processes/LayoutBpmnTool.php | 41 ++++++ .../Mcp/Tools/Processes/ProcessFields.php | 11 ++ .../Mcp/Tools/Processes/ProcessTool.php | 2 + .../Mcp/Tools/Processes/UpdateProcessTool.php | 1 + .../Mcp/skills/process-bpmn-layout.md | 37 ++++++ .../Mcp/skills/process-creation-rules.md | 9 +- ProcessMaker/Mcp/skills/process-validation.md | 2 +- .../Feature/Mcp/McpSystemSkillsSeederTest.php | 1 + tests/Feature/Mcp/ProcessServerTest.php | 124 ++++++++++++++++++ tests/unit/Mcp/BpmnLayoutServiceTest.php | 39 ++++++ ...essBpmnValidatorDiagramInterchangeTest.php | 82 ++++++++++++ tools/mcp/bpmn-auto-layout/cli.mjs | 35 +++++ .../mcp/bpmn-auto-layout/fixtures/linear.bpmn | 31 +++++ tools/mcp/bpmn-auto-layout/layout.mjs | 39 ++++++ tools/mcp/bpmn-auto-layout/package-lock.json | 88 +++++++++++++ tools/mcp/bpmn-auto-layout/package.json | 19 +++ .../mcp/bpmn-auto-layout/test/layout.test.mjs | 47 +++++++ 24 files changed, 889 insertions(+), 7 deletions(-) create mode 100644 ProcessMaker/Mcp/Processes/BpmnLayoutException.php create mode 100644 ProcessMaker/Mcp/Processes/BpmnLayoutService.php create mode 100644 ProcessMaker/Mcp/Tools/Processes/LayoutBpmnTool.php create mode 100644 ProcessMaker/Mcp/skills/process-bpmn-layout.md create mode 100644 tests/unit/Mcp/BpmnLayoutServiceTest.php create mode 100644 tests/unit/Mcp/ProcessBpmnValidatorDiagramInterchangeTest.php create mode 100644 tools/mcp/bpmn-auto-layout/cli.mjs create mode 100644 tools/mcp/bpmn-auto-layout/fixtures/linear.bpmn create mode 100644 tools/mcp/bpmn-auto-layout/layout.mjs create mode 100644 tools/mcp/bpmn-auto-layout/package-lock.json create mode 100644 tools/mcp/bpmn-auto-layout/package.json create mode 100644 tools/mcp/bpmn-auto-layout/test/layout.test.mjs diff --git a/ProcessMaker/Mcp/McpSystemSkills.php b/ProcessMaker/Mcp/McpSystemSkills.php index 3d962da220..96025628dc 100644 --- a/ProcessMaker/Mcp/McpSystemSkills.php +++ b/ProcessMaker/Mcp/McpSystemSkills.php @@ -169,6 +169,14 @@ private static function catalog(): array 'file' => 'process-validation.md', 'scope' => McpGuidance::SCOPE_PROCESSES, ], + [ + 'id' => 'mcp-system-process-bpmn-layout', + 'name' => 'Process BPMN layout', + 'slug' => 'process-bpmn-layout', + 'when' => 'When authoring BPMN for MCP or calling layout-bpmn / auto_layout_bpmn on create-update', + 'file' => 'process-bpmn-layout.md', + 'scope' => McpGuidance::SCOPE_PROCESSES, + ], [ 'id' => self::DATA_CONNECTOR_CREATION_RULES_ID, 'name' => 'Data Connector creation rules', diff --git a/ProcessMaker/Mcp/Processes/BpmnLayoutException.php b/ProcessMaker/Mcp/Processes/BpmnLayoutException.php new file mode 100644 index 0000000000..802a0a2f12 --- /dev/null +++ b/ProcessMaker/Mcp/Processes/BpmnLayoutException.php @@ -0,0 +1,11 @@ +} + */ + public function layout(string $bpmn): array + { + if (!config('mcp.bpmn_layout.enabled')) { + throw new BpmnLayoutException('BPMN auto-layout is disabled (MCP_BPMN_LAYOUT_ENABLED).'); + } + + $maxBytes = (int) config('mcp.bpmn_layout.max_input_bytes', 2_097_152); + if (strlen($bpmn) > $maxBytes) { + throw new BpmnLayoutException('BPMN XML exceeds the maximum size for auto-layout.'); + } + + $node = (string) config('mcp.bpmn_layout.node_binary', 'node'); + $script = (string) config('mcp.bpmn_layout.script_path'); + if ($script === '' || !is_file($script)) { + throw new BpmnLayoutException('BPMN layout script is not installed at ' . $script); + } + + $timeout = max(1, (int) config('mcp.bpmn_layout.timeout', 30)); + $process = new Process([$node, $script]); + $process->setInput($bpmn); + $process->setTimeout($timeout); + + try { + $process->mustRun(); + } catch (ProcessTimedOutException) { + throw new BpmnLayoutException('BPMN auto-layout timed out after ' . $timeout . ' seconds.'); + } catch (\Throwable $exception) { + $parsed = $this->parseStderr($process->getErrorOutput()); + if ($parsed['error'] !== null) { + throw new BpmnLayoutException($parsed['error']); + } + + throw new BpmnLayoutException( + 'BPMN auto-layout failed: ' . ($exception->getMessage() !== '' ? $exception->getMessage() : 'unknown error'), + ); + } + + $output = trim($process->getOutput()); + if ($output === '') { + $parsed = $this->parseStderr($process->getErrorOutput()); + throw new BpmnLayoutException($parsed['error'] ?? 'BPMN auto-layout produced empty output.'); + } + + $parsed = $this->parseStderr($process->getErrorOutput()); + + return [ + 'bpmn' => $output, + 'warnings' => $parsed['warnings'], + ]; + } + + /** + * @return array{warnings: list, error: ?string} + */ + private function parseStderr(string $stderr): array + { + $warnings = []; + $error = null; + + foreach (preg_split('/\r\n|\r|\n/', $stderr) ?: [] as $line) { + $line = trim($line); + if ($line === '') { + continue; + } + + $decoded = json_decode($line, true); + if (!is_array($decoded)) { + if ($error === null && Str::contains($line, 'error')) { + $error = $line; + } + continue; + } + + $level = $decoded['level'] ?? null; + $message = $decoded['message'] ?? null; + if (!is_string($message) || $message === '') { + continue; + } + + if ($level === 'error') { + $error = $message; + } elseif ($level === 'warning') { + $warnings[] = $message; + } + } + + return ['warnings' => $warnings, 'error' => $error]; + } +} diff --git a/ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php b/ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php index 4838dc5405..7a165d2b9c 100644 --- a/ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php +++ b/ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php @@ -22,6 +22,8 @@ final class ProcessBpmnValidator private const DI_NS = 'http://www.omg.org/spec/BPMN/20100524/DI'; + private const DD_DI_NS = 'http://www.omg.org/spec/DD/20100524/DI'; + /** * @return array{ok: bool, errors: list, warnings: list} */ @@ -52,6 +54,7 @@ public function validate(?string $bpmn): array $xpath = new DOMXPath($dom); $xpath->registerNamespace('bpmn', self::BPMN_NS); $xpath->registerNamespace('bpmndi', self::DI_NS); + $xpath->registerNamespace('di', self::DD_DI_NS); $xpath->registerNamespace('pm', self::PM_NS); $this->collectSemanticIssues($xpath, $errors, $warnings); @@ -59,6 +62,33 @@ public function validate(?string $bpmn): array return $this->result($errors, $warnings); } + /** + * True when any sequence flow lacks a BPMNEdge with at least two waypoints (Modeler spider-line bug). + */ + public function lacksSequenceFlowDiagramInterchange(string $bpmn): bool + { + $bpmn = BpmnDocument::replaceHtmlEntities($bpmn); + $dom = new DOMDocument(); + if (@$dom->loadXML($bpmn) !== true) { + return true; + } + + $xpath = new DOMXPath($dom); + $xpath->registerNamespace('bpmn', self::BPMN_NS); + $xpath->registerNamespace('bpmndi', self::DI_NS); + $xpath->registerNamespace('di', self::DD_DI_NS); + + $flows = $xpath->query('//bpmn:sequenceFlow[@id]'); + if ($flows === false || $flows->length === 0) { + return false; + } + + $issues = []; + $this->requireSequenceFlowDiagramInterchange($xpath, $issues); + + return $issues !== []; + } + /** * @return list */ @@ -106,6 +136,7 @@ private function collectSemanticIssues(DOMXPath $xpath, array &$errors, array &$ } $this->requireFlowWiring($xpath, $errors); + $this->requireSequenceFlowDiagramInterchange($xpath, $errors); $this->requireInterstitialScreen($xpath, $errors); $this->requireAttr($xpath, '//bpmn:task', 'screenRef', 'missing_screen_ref', 'Form Task requires pm:screenRef.', $errors); @@ -189,6 +220,60 @@ private function requireInterstitialScreen(DOMXPath $xpath, array &$errors): voi } } + /** + * Nayra wires runtime flows from bpmn:outgoing / bpmn:incoming children. + * sourceRef/targetRef alone leave Start Events with 0 outgoing flows. + * + * @param list $errors + */ + /** + * @param list $errors + */ + private function requireSequenceFlowDiagramInterchange(DOMXPath $xpath, array &$errors): void + { + $edgesByFlowId = []; + foreach ($xpath->query('//bpmndi:BPMNEdge[@bpmnElement]') ?: [] as $edge) { + if (!$edge instanceof DOMElement) { + continue; + } + $ref = $edge->getAttribute('bpmnElement'); + if ($ref !== '') { + $edgesByFlowId[$ref] = $edge; + } + } + + foreach ($xpath->query('//bpmn:sequenceFlow[@id]') ?: [] as $flow) { + if (!$flow instanceof DOMElement) { + continue; + } + $flowId = $flow->getAttribute('id'); + if ($flowId === '') { + continue; + } + + $edge = $edgesByFlowId[$flowId] ?? null; + if (!$edge instanceof DOMElement) { + $errors[] = $this->issue( + $flowId, + 'missing_bpmn_edge', + 'Sequence flow ' . $flowId . ' has no bpmndi:BPMNEdge; ProcessMaker Modeler draws broken connectors from (0,0). ' + . 'Call layout-bpmn or save via MCP create/update with auto layout enabled.', + ); + + continue; + } + + $waypoints = $xpath->query('.//di:waypoint', $edge); + if ($waypoints === false || $waypoints->length < 2) { + $errors[] = $this->issue( + $flowId, + 'incomplete_bpmn_edge', + 'Sequence flow ' . $flowId . ' BPMNEdge needs at least two di:waypoint elements.', + ); + } + } + } + /** * Nayra wires runtime flows from bpmn:outgoing / bpmn:incoming children. * sourceRef/targetRef alone leave Start Events with 0 outgoing flows. diff --git a/ProcessMaker/Mcp/Processes/ProcessCatalog.php b/ProcessMaker/Mcp/Processes/ProcessCatalog.php index 1d60a696a1..7ae5ce588e 100644 --- a/ProcessMaker/Mcp/Processes/ProcessCatalog.php +++ b/ProcessMaker/Mcp/Processes/ProcessCatalog.php @@ -33,8 +33,10 @@ class ProcessCatalog */ private const ORDER_COLUMNS = ['name', 'status', 'updated_at', 'created_at', 'id']; - public function __construct(private readonly ProcessBpmnValidator $validator) - { + public function __construct( + private readonly ProcessBpmnValidator $validator, + private readonly BpmnLayoutService $layout, + ) { } public function actor(?Authenticatable $user): User @@ -111,6 +113,7 @@ public function create(User $user, array $input): array $validated = validator($input, $this->createRules($input))->validate(); if (array_key_exists('bpmn', $validated) && is_string($validated['bpmn']) && $validated['bpmn'] !== '') { + $validated['bpmn'] = $this->layoutBpmnIfRequested($input, $validated['bpmn']); $this->assertBpmnAcceptable($validated['bpmn']); $validated['bpmn'] = BpmnDocument::replaceHtmlEntities($validated['bpmn']); } @@ -156,6 +159,7 @@ public function update(User $user, array $input): array } if (isset($attributes['bpmn'])) { + $attributes['bpmn'] = $this->layoutBpmnIfRequested($input, $attributes['bpmn']); $this->assertBpmnAcceptable($attributes['bpmn']); $attributes['bpmn'] = BpmnDocument::replaceHtmlEntities($attributes['bpmn']); } @@ -186,6 +190,38 @@ public function validate(User $user, array $input): array return $this->validator->validate(is_string($bpmn) ? $bpmn : null); } + /** + * @param array $input + * @return array{bpmn: string, warnings: list, layout_engine: string} + */ + public function layoutBpmn(User $user, array $input): array + { + $this->assertCan($user, self::VIEW); + $validated = validator($input, [ + 'bpmn' => 'nullable|string', + 'id' => 'nullable|integer|min:1', + ])->validate(); + + $bpmn = $validated['bpmn'] ?? null; + if (($bpmn === null || $bpmn === '') && isset($validated['id'])) { + $bpmn = Process::query()->findOrFail((int) $validated['id'])->bpmn; + } + + if (!is_string($bpmn) || trim($bpmn) === '') { + throw ValidationException::withMessages([ + 'bpmn' => 'BPMN XML is required (or pass process id).', + ]); + } + + $result = $this->layout->layout($bpmn); + + return [ + 'bpmn' => $result['bpmn'], + 'warnings' => $result['warnings'], + 'layout_engine' => 'bpmn-auto-layout-extended', + ]; + } + /** * @param array $filters */ @@ -282,6 +318,42 @@ private function writable(array $input): array ])); } + /** + * @param array $input + */ + private function layoutBpmnIfRequested(array $input, string $bpmn): string + { + $needsLayout = $this->shouldAutoLayout($input) + || $this->validator->lacksSequenceFlowDiagramInterchange($bpmn); + + if (!$needsLayout) { + return $bpmn; + } + + if (!config('mcp.bpmn_layout.enabled')) { + return $bpmn; + } + + return $this->layout->layout($bpmn)['bpmn']; + } + + /** + * @param array $input + */ + private function shouldAutoLayout(array $input): bool + { + if (!config('mcp.bpmn_layout.enabled')) { + return false; + } + + $flag = $input['auto_layout_bpmn'] ?? true; + if ($flag === false || $flag === 0 || $flag === '0' || $flag === 'false') { + return false; + } + + return true; + } + private function assertBpmnAcceptable(string $bpmn): void { $result = $this->validator->validate($bpmn); diff --git a/ProcessMaker/Mcp/Servers/ProcessServer.php b/ProcessMaker/Mcp/Servers/ProcessServer.php index eefe66b303..0bef44513e 100644 --- a/ProcessMaker/Mcp/Servers/ProcessServer.php +++ b/ProcessMaker/Mcp/Servers/ProcessServer.php @@ -16,6 +16,7 @@ use ProcessMaker\Mcp\Tools\Processes\GetProcessTool; use ProcessMaker\Mcp\Tools\Processes\ListGroupsTool; use ProcessMaker\Mcp\Tools\Processes\ListProcessesTool; +use ProcessMaker\Mcp\Tools\Processes\LayoutBpmnTool; use ProcessMaker\Mcp\Tools\Processes\ListUsersTool; use ProcessMaker\Mcp\Tools\Processes\PlanProcessTool; use ProcessMaker\Mcp\Tools\Processes\UpdateProcessTool; @@ -40,6 +41,7 @@ create-process requires name and description; bpmn is optional (empty template if omitted — add a start event before running). For MCP create-process/update-process use numeric pm:screenRef / pm:scriptRef (list-screens after create-screen). Portable ${screen:title} only resolves via package-plg deploy-process. Call validate-process before create/update when unsure. +MCP create/update always runs `bpmn-auto-layout-extended` when sequence flows lack BPMNEdge waypoints (prevents Modeler spider lines). Default `auto_layout_bpmn` is true; `validate-process` errors on `missing_bpmn_edge` if layout is disabled. update-process changes only the fields you send. MARKDOWN)] class ProcessServer extends Server @@ -58,6 +60,7 @@ class ProcessServer extends Server CreateProcessTool::class, UpdateProcessTool::class, ValidateProcessTool::class, + LayoutBpmnTool::class, ]; public function createContext(): ServerContext diff --git a/ProcessMaker/Mcp/Tools/Processes/CreateProcessTool.php b/ProcessMaker/Mcp/Tools/Processes/CreateProcessTool.php index 7b0b7c9c14..9706d4da8c 100644 --- a/ProcessMaker/Mcp/Tools/Processes/CreateProcessTool.php +++ b/ProcessMaker/Mcp/Tools/Processes/CreateProcessTool.php @@ -37,6 +37,7 @@ public function schema(JsonSchema $schema): array 'status' => ProcessFields::status($schema), 'process_category_id' => ProcessFields::category($schema, false), 'bpmn' => ProcessFields::bpmn($schema, false), + 'auto_layout_bpmn' => ProcessFields::autoLayoutBpmn($schema), ]; } } diff --git a/ProcessMaker/Mcp/Tools/Processes/LayoutBpmnTool.php b/ProcessMaker/Mcp/Tools/Processes/LayoutBpmnTool.php new file mode 100644 index 0000000000..f760b7673f --- /dev/null +++ b/ProcessMaker/Mcp/Tools/Processes/LayoutBpmnTool.php @@ -0,0 +1,41 @@ +respond(fn (): array => $processes->layoutBpmn( + $processes->actor($request->user()), + $request->all(), + )); + } + + /** + * @return array + */ + public function schema(JsonSchema $schema): array + { + return [ + 'bpmn' => ProcessFields::bpmn($schema, false), + 'id' => $schema->integer()->description('Existing process id whose BPMN should be layouted when bpmn is omitted.'), + ]; + } +} diff --git a/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php b/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php index cb04cfabd5..4417fe85a5 100644 --- a/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php +++ b/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php @@ -5,6 +5,7 @@ namespace ProcessMaker\Mcp\Tools\Processes; use Illuminate\Contracts\JsonSchema\JsonSchema; +use Illuminate\JsonSchema\Types\BooleanType; use Illuminate\JsonSchema\Types\IntegerType; use Illuminate\JsonSchema\Types\StringType; @@ -59,4 +60,14 @@ public static function bpmn(JsonSchema $schema, bool $required): StringType return $required ? $field->required() : $field; } + + public static function autoLayoutBpmn(JsonSchema $schema): BooleanType + { + return $schema->boolean() + ->description( + 'When true (default) and bpmn is provided, run bpmn-auto-layout-extended before save. ' + . 'Set false to keep coordinates only when every sequenceFlow already has BPMNEdge waypoints; ' + . 'incomplete diagram interchange is still auto-laid out to avoid Modeler rendering bugs.', + ); + } } diff --git a/ProcessMaker/Mcp/Tools/Processes/ProcessTool.php b/ProcessMaker/Mcp/Tools/Processes/ProcessTool.php index 75888033b4..821922608c 100644 --- a/ProcessMaker/Mcp/Tools/Processes/ProcessTool.php +++ b/ProcessMaker/Mcp/Tools/Processes/ProcessTool.php @@ -10,6 +10,7 @@ use Laravel\Mcp\Response; use Laravel\Mcp\ResponseFactory; use Laravel\Mcp\Server\Tool; +use ProcessMaker\Mcp\Processes\BpmnLayoutException; use Throwable; abstract class ProcessTool extends Tool @@ -32,6 +33,7 @@ private function errorResponse(Throwable $exception): Response $exception instanceof ValidationException => $this->validationMessage($exception), $exception instanceof AuthorizationException => $exception->getMessage(), $exception instanceof ModelNotFoundException => 'Process not found.', + $exception instanceof BpmnLayoutException => $exception->getMessage(), default => throw $exception, }; diff --git a/ProcessMaker/Mcp/Tools/Processes/UpdateProcessTool.php b/ProcessMaker/Mcp/Tools/Processes/UpdateProcessTool.php index 5d97c40091..d0a3a6576f 100644 --- a/ProcessMaker/Mcp/Tools/Processes/UpdateProcessTool.php +++ b/ProcessMaker/Mcp/Tools/Processes/UpdateProcessTool.php @@ -38,6 +38,7 @@ public function schema(JsonSchema $schema): array 'status' => ProcessFields::status($schema), 'process_category_id' => ProcessFields::category($schema, false), 'bpmn' => ProcessFields::bpmn($schema, false), + 'auto_layout_bpmn' => ProcessFields::autoLayoutBpmn($schema), ]; } } diff --git a/ProcessMaker/Mcp/skills/process-bpmn-layout.md b/ProcessMaker/Mcp/skills/process-bpmn-layout.md new file mode 100644 index 0000000000..32bce622a8 --- /dev/null +++ b/ProcessMaker/Mcp/skills/process-bpmn-layout.md @@ -0,0 +1,37 @@ +# Skill: BPMN diagram layout + +Load when authoring BPMN for MCP and the diagram needs readable Modeler positions (DI), or when calling `layout-bpmn`. + +## What it does + +ProcessMaker runs **[bpmn-auto-layout-extended](https://github.com/krasucki/bpmn-auto-layout-extended)** on the server (`tools/mcp/bpmn-auto-layout`). It regenerates diagram interchange (shapes, edges, **lanes**, collaborations) while preserving BPMN semantics (`incoming`/`outgoing`, `pm:*`, conditions). + +Compared to a flat graph layout only, this engine understands **swimlanes (`laneSet`)**, message flows, groups, and annotations. + +## Agent workflow + +1. Author BPMN structure and ProcessMaker attrs (`process-creation-rules` + node skills). +2. You may use placeholder DI (overlapping bounds are fine). +3. Call **`layout-bpmn`** to preview layout, or rely on **`auto_layout_bpmn`** (default **true**) on **`create-process`** / **`update-process`**. +4. Call **`validate-process`**, then create/update. + +Do **not** spend tokens hand-tuning `dc:Bounds` or `di:waypoint` values. + +## Tools + +| Tool | Behavior | +|------|----------| +| `layout-bpmn` | Returns `{ bpmn, warnings, layout_engine: "bpmn-auto-layout-extended" }` without saving | +| `create-process` / `update-process` | Layout before save when `auto_layout_bpmn` is true **or** any `sequenceFlow` lacks `BPMNEdge` waypoints (forced). `validate-process` errors with `missing_bpmn_edge` if layout is disabled. | + +## Operations + +- Requires **Node.js ≥ 18** and `npm ci` in `tools/mcp/bpmn-auto-layout` on the ProcessMaker host. +- Disable globally: `MCP_BPMN_LAYOUT_ENABLED=false` (or legacy `MCP_BPMN_AUTO_LAYOUT=false`). +- Optional script override: `MCP_BPMN_LAYOUT_SCRIPT` (defaults to `tools/mcp/bpmn-auto-layout/cli.mjs`). +- Preserve manual coordinates: `auto_layout_bpmn: false` only when every flow already has `BPMNEdge` + waypoints; otherwise MCP still auto-layouts. + +## Limits + +- Extremely large diagrams may hit timeout (`MCP_BPMN_LAYOUT_TIMEOUT`, default 30s). +- Sub-processes stay collapsed unless the layout library is called with `expandSubProcesses` (not exposed on MCP tools yet). diff --git a/ProcessMaker/Mcp/skills/process-creation-rules.md b/ProcessMaker/Mcp/skills/process-creation-rules.md index 4eb539e199..e862c5a1e9 100644 --- a/ProcessMaker/Mcp/skills/process-creation-rules.md +++ b/ProcessMaker/Mcp/skills/process-creation-rules.md @@ -57,7 +57,7 @@ Rules: 1. Exactly **one** `bpmndi:BPMNDiagram` (API validates this). 2. Form Task element type is **`bpmn:Task`**, not `bpmn:UserTask`. 3. Node `id` must match Advanced inspector: `^[a-zA-Z][^\s][a-zA-Z0-9_-]+$` (e.g. `node_1`). -4. Every flow needs matching diagram edge; every shape needs bounds. +4. Every `sequenceFlow` must have a `bpmndi:BPMNEdge` with ≥2 `di:waypoint` (shapes-only XML breaks Modeler). **Do not hand-draw coordinates** — MCP create/update auto-layouts when edges are missing; `validate-process` fails with `missing_bpmn_edge` if you bypass layout. 5. **Every sequence flow must also appear as `` on the source and `` on the target.** Nayra wires the runtime graph from those child refs — `sourceRef`/`targetRef` alone is not enough. Without them, a Start Event has 0 outgoing flows and the Request never reaches the first task. 6. Do **not** put Form Task assignment values like `pm:assignment="requester"` on a Start Event (start permissions use `user` / `group` / `process_manager` or omit). 7. Interstitial (“Display Next Assigned Task to Task Assignee”): if you set `pm:allowInterstitial="true"` you **must** also set `pm:interstitialScreenRef` to a **DISPLAY** screen (system key `interstitial` is fine). Enabling interstitial without a screen leaves the UI stuck on loading after start. If you do not need that UX, omit both attributes. @@ -119,9 +119,10 @@ Never put connector settings in the wrong place: Service Tasks use BPMN `impleme 2. **Catalogs first** — for every multi-option select the screens will need, `list-collections` / `create-collection` + seed (`collection-creation-rules`, `collection-test-data`). Keep **collection id** map; confirm Data Connectors with `list-data-connectors`. 3. Ensure assets — create/upsert every screen/script/child process; wire collection ids into Vue mounts; keep a **title → id** map. 4. Author BPMN — start → tasks/gateways → end; for MCP use **numeric** `pm:screenRef` / `pm:scriptRef` from that map; gateway conditions use catalog **codes**. -5. Validate — see skill `process-validation` (schema, refs, gateway defaults, screen types, no unresolved `${…}`). -6. Create/update — MCP `create-process`/`update-process`, or PLG `deploy-process` for portable git BPMN. -7. Verify — `get-process`; every Form/Manual Task has a numeric screen id; runnable path start → end. +5. Layout — skill `process-bpmn-layout`: `layout-bpmn` or rely on `auto_layout_bpmn` (default true) on MCP create/update. +6. Validate — see skill `process-validation` (schema, refs, gateway defaults, screen types, no unresolved `${…}`). +7. Create/update — MCP `create-process`/`update-process`, or PLG `deploy-process` for portable git BPMN. +8. Verify — `get-process`; every Form/Manual Task has a numeric screen id; runnable path start → end. ## Do not diff --git a/ProcessMaker/Mcp/skills/process-validation.md b/ProcessMaker/Mcp/skills/process-validation.md index 2583a150b9..424ea14ce6 100644 --- a/ProcessMaker/Mcp/skills/process-validation.md +++ b/ProcessMaker/Mcp/skills/process-validation.md @@ -1,6 +1,6 @@ # Skill: Process BPMN validation -Use before create/update/deploy, or when implementing a future `validate-process` MCP tool. Validates structure, refs, and runtime-readiness — not visual layout aesthetics. +Use before create/update/deploy, or with the `validate-process` MCP tool. Validates structure, refs, and runtime-readiness — **not** visual layout aesthetics (use skill `process-bpmn-layout` / `layout-bpmn` for diagram positions). ## Levels diff --git a/tests/Feature/Mcp/McpSystemSkillsSeederTest.php b/tests/Feature/Mcp/McpSystemSkillsSeederTest.php index 960f897c75..8016ce391b 100644 --- a/tests/Feature/Mcp/McpSystemSkillsSeederTest.php +++ b/tests/Feature/Mcp/McpSystemSkillsSeederTest.php @@ -75,6 +75,7 @@ public function testSeederUpsertsSystemSkillAndKeepsCustomSkills(): void $slugs = array_column($skills, 'slug'); $this->assertContains('process-node-form-task', $slugs); $this->assertContains('process-validation', $slugs); + $this->assertContains('process-bpmn-layout', $slugs); $this->assertContains('process-web-entry', $slugs); $this->assertContains('data-connector-creation-rules', $slugs); $this->assertContains('data-connector-in-process', $slugs); diff --git a/tests/Feature/Mcp/ProcessServerTest.php b/tests/Feature/Mcp/ProcessServerTest.php index 300c000610..6e9fe11ead 100644 --- a/tests/Feature/Mcp/ProcessServerTest.php +++ b/tests/Feature/Mcp/ProcessServerTest.php @@ -12,6 +12,7 @@ use ProcessMaker\Mcp\Tools\GetMcpGuidanceTool; use ProcessMaker\Mcp\Tools\GetMcpSkillTool; use ProcessMaker\Mcp\Tools\Processes\CreateProcessTool; +use ProcessMaker\Mcp\Tools\Processes\LayoutBpmnTool; use ProcessMaker\Mcp\Tools\Processes\GetProcessTool; use ProcessMaker\Mcp\Tools\Processes\ListGroupsTool; use ProcessMaker\Mcp\Tools\Processes\ListProcessesTool; @@ -232,6 +233,112 @@ public function testGetMcpSkillReturnsFullSkillBodyBySlug(): void ->etc()); } + /** + * @group requires-node + */ + public function testLayoutBpmnToolAppliesAutoLayout(): void + { + $this->assumeBpmnLayoutAvailable(); + + $bpmn = file_get_contents(base_path('tools/mcp/bpmn-auto-layout/fixtures/linear.bpmn')); + $this->assertNotFalse($bpmn); + + ProcessServer::actingAs($this->user)->tool(LayoutBpmnTool::class, [ + 'bpmn' => $bpmn, + ])->assertOk() + ->assertHasNoErrors() + ->assertStructuredContent(function (AssertableJson $json): void { + $json->where('layout_engine', 'bpmn-auto-layout-extended') + ->whereType('bpmn', 'string') + ->whereType('warnings', 'array'); + + $out = $json->toArray(); + $this->assertStringContainsString('pm:screenRef="1"', $out['bpmn'] ?? ''); + preg_match_all('/dc:Bounds x="(\d+)"/', $out['bpmn'] ?? '', $matches); + $xs = array_map('intval', $matches[1] ?? []); + $this->assertGreaterThanOrEqual(3, count($xs)); + $this->assertTrue($xs[1] > $xs[0] && $xs[2] > $xs[1]); + $json->etc(); + }); + } + + /** + * @group requires-node + */ + public function testCreateProcessWithoutBpmnEdgesStillAutoLayoutsBeforeSave(): void + { + $this->assumeBpmnLayoutAvailable(); + Event::fake([ProcessCreated::class]); + + $bpmn = <<<'XML' + + + + flow_1 + + flow_1 + flow_2 + + flow_2 + + + + + + + + + + + +XML; + + ProcessServer::actingAs($this->user)->tool(CreateProcessTool::class, [ + 'name' => 'MCP forced layout edges', + 'description' => 'Shapes only input', + 'bpmn' => $bpmn, + 'auto_layout_bpmn' => false, + ])->assertOk()->assertHasNoErrors() + ->assertStructuredContent(function (AssertableJson $json): void { + $stored = $json->toArray()['bpmn'] ?? ''; + $this->assertGreaterThanOrEqual(2, substr_count($stored, 'bpmndi:BPMNEdge')); + $this->assertGreaterThanOrEqual(4, substr_count($stored, 'di:waypoint')); + $json->etc(); + }); + } + + /** + * @group requires-node + */ + public function testCreateProcessAutoLayoutSpreadsDiagramCoordinates(): void + { + $this->assumeBpmnLayoutAvailable(); + Event::fake([ProcessCreated::class]); + + $bpmn = file_get_contents(base_path('tools/mcp/bpmn-auto-layout/fixtures/linear.bpmn')); + $this->assertNotFalse($bpmn); + + $created = ProcessServer::actingAs($this->user)->tool(CreateProcessTool::class, [ + 'name' => 'MCP ELK Layout Flow', + 'description' => 'Auto layout test', + 'bpmn' => $bpmn, + 'auto_layout_bpmn' => true, + ]); + + $created->assertOk()->assertHasNoErrors() + ->assertStructuredContent(function (AssertableJson $json): void { + $payload = $json->toArray(); + preg_match_all('/dc:Bounds x="(\d+)"/', $payload['bpmn'] ?? '', $matches); + $xs = array_map('intval', $matches[1] ?? []); + $this->assertTrue($xs[1] > $xs[0] && $xs[2] > $xs[1]); + $json->etc(); + }); + } + public function testServerInstructionsIncludeProcessCatalogWithoutSkillBodies(): void { $this->seedMcpGuidance(); @@ -241,6 +348,7 @@ public function testServerInstructionsIncludeProcessCatalogWithoutSkillBodies(): $this->assertStringContainsString('get-mcp-guidance', $instructions); $this->assertStringContainsString('validate-process', $instructions); + $this->assertStringContainsString('layout-bpmn', $instructions); $this->assertStringContainsString('Prefer clear process names', $instructions); $this->assertStringContainsString('process-creation-rules', $instructions); $this->assertStringNotContainsString('Author BPMN carefully', $instructions); @@ -259,6 +367,22 @@ public function testSkillResourcesAreProcessScoped(): void $this->assertSame('pm://mcp/skills/process-creation-rules', $resources->first()->uri()); } + private function assumeBpmnLayoutAvailable(): void + { + $script = config('mcp.bpmn_layout.script_path'); + if (!is_string($script) || !is_file($script)) { + $this->markTestSkipped('BPMN auto-layout script is not installed.'); + } + + $node = config('mcp.bpmn_layout.node_binary', 'node'); + $check = new \Symfony\Component\Process\Process([$node, '--version']); + try { + $check->mustRun(); + } catch (\Throwable) { + $this->markTestSkipped('Node.js is not available for BPMN layout.'); + } + } + private function seedMcpGuidance(): void { Setting::factory()->create([ diff --git a/tests/unit/Mcp/BpmnLayoutServiceTest.php b/tests/unit/Mcp/BpmnLayoutServiceTest.php new file mode 100644 index 0000000000..3bc8e332dd --- /dev/null +++ b/tests/unit/Mcp/BpmnLayoutServiceTest.php @@ -0,0 +1,39 @@ +markTestSkipped('BPMN auto-layout script is not installed.'); + } + + $node = config('mcp.bpmn_layout.node_binary', 'node'); + $check = new Process([$node, '--version']); + try { + $check->mustRun(); + } catch (\Throwable) { + $this->markTestSkipped('Node.js is not available for BPMN layout.'); + } + + $input = file_get_contents(base_path('tools/mcp/bpmn-auto-layout/fixtures/linear.bpmn')); + $this->assertNotFalse($input); + + $result = (new BpmnLayoutService())->layout($input); + + $this->assertStringContainsString('pm:screenRef="1"', $result['bpmn']); + $this->assertMatchesRegularExpression('/dc:Bounds x="\d+"/', $result['bpmn']); + } +} diff --git a/tests/unit/Mcp/ProcessBpmnValidatorDiagramInterchangeTest.php b/tests/unit/Mcp/ProcessBpmnValidatorDiagramInterchangeTest.php new file mode 100644 index 0000000000..f4a6ad62eb --- /dev/null +++ b/tests/unit/Mcp/ProcessBpmnValidatorDiagramInterchangeTest.php @@ -0,0 +1,82 @@ + + + + flow_1 + flow_1 + + + + + + + + + +XML; + + $validator = new ProcessBpmnValidator(); + + $this->assertTrue($validator->lacksSequenceFlowDiagramInterchange($bpmn)); + + $result = $validator->validate($bpmn); + $this->assertFalse($result['ok']); + $codes = array_column($result['errors'], 'code'); + $this->assertContains('missing_bpmn_edge', $codes); + } + + public function testCompleteBpmnEdgePassesDiagramCheck(): void + { + $bpmn = <<<'XML' + + + + flow_1 + flow_1 + + + + + + + + + + + + +XML; + + $validator = new ProcessBpmnValidator(); + + $this->assertFalse($validator->lacksSequenceFlowDiagramInterchange($bpmn)); + + $diagramErrors = array_filter( + $validator->validate($bpmn)['errors'], + static fn (array $row): bool => in_array($row['code'], ['missing_bpmn_edge', 'incomplete_bpmn_edge'], true), + ); + $this->assertSame([], $diagramErrors); + } +} diff --git a/tools/mcp/bpmn-auto-layout/cli.mjs b/tools/mcp/bpmn-auto-layout/cli.mjs new file mode 100644 index 0000000000..cf9071e211 --- /dev/null +++ b/tools/mcp/bpmn-auto-layout/cli.mjs @@ -0,0 +1,35 @@ +#!/usr/bin/env node +import { layoutBpmn } from './layout.mjs'; + +async function readStdin() { + const chunks = []; + for await (const chunk of process.stdin) { + chunks.push(chunk); + } + + return Buffer.concat(chunks).toString('utf8'); +} + +function emitWarning(message) { + process.stderr.write(`${JSON.stringify({ level: 'warning', message })}\n`); +} + +async function main() { + try { + const input = await readStdin(); + const { xml, warnings } = await layoutBpmn(input); + for (const message of warnings) { + emitWarning(message); + } + process.stdout.write(xml); + if (!xml.endsWith('\n')) { + process.stdout.write('\n'); + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + process.stderr.write(`${JSON.stringify({ level: 'error', message })}\n`); + process.exit(1); + } +} + +main(); diff --git a/tools/mcp/bpmn-auto-layout/fixtures/linear.bpmn b/tools/mcp/bpmn-auto-layout/fixtures/linear.bpmn new file mode 100644 index 0000000000..f40d98c70c --- /dev/null +++ b/tools/mcp/bpmn-auto-layout/fixtures/linear.bpmn @@ -0,0 +1,31 @@ + + + + + flow_1 + + + flow_1 + flow_2 + + + flow_2 + + + + + + + + + + + + + + diff --git a/tools/mcp/bpmn-auto-layout/layout.mjs b/tools/mcp/bpmn-auto-layout/layout.mjs new file mode 100644 index 0000000000..a1da2f4bf2 --- /dev/null +++ b/tools/mcp/bpmn-auto-layout/layout.mjs @@ -0,0 +1,39 @@ +import { layoutProcess } from 'bpmn-auto-layout-extended'; + +/** + * @param {string} xml + * @param {{ expandSubProcesses?: boolean }} [options] + * @returns {Promise<{ xml: string, warnings: string[] }>} + */ +export async function layoutBpmn(xml, options = {}) { + const trimmed = xml.trim(); + if (trimmed === '') { + throw new Error('BPMN XML is empty.'); + } + + const layoutOptions = {}; + if (options.expandSubProcesses === true) { + layoutOptions.expandSubProcesses = true; + } + + const result = await layoutProcess(trimmed, layoutOptions); + const output = typeof result === 'string' ? result : result?.xml; + if (typeof output !== 'string' || output.trim() === '') { + throw new Error('BPMN auto-layout produced empty output.'); + } + + const warnings = []; + if (typeof result === 'object' && result !== null && Array.isArray(result.warnings)) { + for (const item of result.warnings) { + if (typeof item === 'string') { + warnings.push(item); + } else if (item?.message) { + warnings.push(String(item.message)); + } + } + } + + const withDeclaration = output.startsWith('\n${output}`; + + return { xml: withDeclaration, warnings }; +} diff --git a/tools/mcp/bpmn-auto-layout/package-lock.json b/tools/mcp/bpmn-auto-layout/package-lock.json new file mode 100644 index 0000000000..7ff233f20b --- /dev/null +++ b/tools/mcp/bpmn-auto-layout/package-lock.json @@ -0,0 +1,88 @@ +{ + "name": "@processmaker/mcp-bpmn-auto-layout", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@processmaker/mcp-bpmn-auto-layout", + "version": "1.0.0", + "dependencies": { + "bpmn-auto-layout-extended": "^1.0.5" + }, + "bin": { + "mcp-bpmn-auto-layout": "cli.mjs" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/bpmn-auto-layout-extended": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/bpmn-auto-layout-extended/-/bpmn-auto-layout-extended-1.0.5.tgz", + "integrity": "sha512-HEDqM1Jir5FmafiS8Gz5+rqnHutVeuMwn70AFWaRVcLQmqhA4bATYbXgFFwHmn0c0HkygoYJO/KTGmmd3IbTNA==", + "license": "MIT", + "workspaces": [ + "example" + ], + "dependencies": { + "bpmn-moddle": "^10.0.0", + "min-dash": "^5.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/bpmn-moddle": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/bpmn-moddle/-/bpmn-moddle-10.3.1.tgz", + "integrity": "sha512-xjJ8GzseRkjjM0MX/rODVB6iv+rhGLt8FCHJIovLAjJsDEAUjITfyiJZYczJ4pp3wmesbY3sQR7eRT+q5uroVA==", + "license": "MIT", + "dependencies": { + "min-dash": "^5.1.0", + "moddle": "^8.2.1", + "moddle-xml": "^12.3.1" + } + }, + "node_modules/min-dash": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.1.0.tgz", + "integrity": "sha512-HAvN6XzmCQj+js43G9sJRRw8kj/7DvoxN7qhoIN9Xo5ZN1NMljtpyKs/NunXmw0QSWwlgZzNv6tLeEa4xaZ0tg==", + "license": "MIT" + }, + "node_modules/moddle": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/moddle/-/moddle-8.2.1.tgz", + "integrity": "sha512-20qzO/ZpMGO9j9gdQgXk9bfGxb9wA3JKnGth/21YZKODLrZE4RW/uVMIL5pTskYm34Z61DucBEPkq93qByNsBQ==", + "license": "MIT", + "dependencies": { + "min-dash": "^5.1.0" + } + }, + "node_modules/moddle-xml": { + "version": "12.3.2", + "resolved": "https://registry.npmjs.org/moddle-xml/-/moddle-xml-12.3.2.tgz", + "integrity": "sha512-fo6DSZdLr7Lr4ydgpHbEQEXu63QxxRPNmu5k2n3B/+oRTT9ybBLrcxo/hIK6Bo16ORVtw8FoZbwRCwZRr5l19g==", + "license": "MIT", + "dependencies": { + "min-dash": "^5.1.0", + "saxen": "^11.2.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "moddle": ">= 6.2.0" + } + }, + "node_modules/saxen": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/saxen/-/saxen-11.2.0.tgz", + "integrity": "sha512-2bG564AAJcm/3vyZC0Uhs/mACrH+4AHMaKHKAB2M5xMqomUZa27FQ7MYaQGFKVcJk/MVzSEQ34A8QZWW+eiWEw==", + "license": "MIT", + "engines": { + "node": ">= 20.12" + } + } + } +} diff --git a/tools/mcp/bpmn-auto-layout/package.json b/tools/mcp/bpmn-auto-layout/package.json new file mode 100644 index 0000000000..dac27b5310 --- /dev/null +++ b/tools/mcp/bpmn-auto-layout/package.json @@ -0,0 +1,19 @@ +{ + "name": "@processmaker/mcp-bpmn-auto-layout", + "private": true, + "version": "1.0.0", + "description": "BPMN diagram auto-layout for ProcessMaker MCP (lanes, collaborations)", + "type": "module", + "bin": { + "mcp-bpmn-auto-layout": "./cli.mjs" + }, + "scripts": { + "test": "node --test test/*.test.mjs" + }, + "engines": { + "node": ">=18" + }, + "dependencies": { + "bpmn-auto-layout-extended": "^1.0.5" + } +} diff --git a/tools/mcp/bpmn-auto-layout/test/layout.test.mjs b/tools/mcp/bpmn-auto-layout/test/layout.test.mjs new file mode 100644 index 0000000000..78075fcbd2 --- /dev/null +++ b/tools/mcp/bpmn-auto-layout/test/layout.test.mjs @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; +import { layoutBpmn } from '../layout.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repoRoot = join(__dirname, '..', '..', '..', '..'); + +function loadFixture(name) { + return readFileSync(join(__dirname, '..', 'fixtures', name), 'utf8'); +} + +test('layout spreads overlapping nodes left-to-right', async () => { + const input = loadFixture('linear.bpmn'); + const { xml, warnings } = await layoutBpmn(input); + assert.equal(warnings.length, 0); + assert.match(xml, /pm:screenRef="1"/); + const bounds = [...xml.matchAll(/dc:Bounds x="(\d+)"/g)].map((m) => Number(m[1])); + assert.ok(bounds.length >= 3); + assert.ok(bounds[1] > bounds[0], 'task should be to the right of start'); + assert.ok(bounds[2] > bounds[1], 'end should be to the right of task'); +}); + +test('every sequence flow has at least two waypoints', async () => { + const input = loadFixture('linear.bpmn'); + const { xml } = await layoutBpmn(input); + const edges = (xml.match(//g)]; + for (const block of waypointBlocks) { + const count = (block[0].match(/di:waypoint/g) ?? []).length; + assert.ok(count >= 2, `expected >= 2 waypoints, got ${count}`); + } +}); + +test('laneSet emits lane shapes', async () => { + const input = readFileSync( + join(repoRoot, 'database/processes/inactive/VacationRequet.bpmn'), + 'utf8', + ); + const { xml } = await layoutBpmn(input); + assert.match(xml, /laneSet|lane/i); + const laneShapes = (xml.match(/BPMNShape[^>]*bpmnElement="(_6|_7|_8)"/g) ?? []).length; + assert.ok(laneShapes >= 3, `expected lane BPMNShapes, got ${laneShapes}`); +});