Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions ProcessMaker/Mcp/McpSystemSkills.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
11 changes: 11 additions & 0 deletions ProcessMaker/Mcp/Processes/BpmnLayoutException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace ProcessMaker\Mcp\Processes;

use RuntimeException;

final class BpmnLayoutException extends RuntimeException
{
}
104 changes: 104 additions & 0 deletions ProcessMaker/Mcp/Processes/BpmnLayoutService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?php

declare(strict_types=1);

namespace ProcessMaker\Mcp\Processes;

use Illuminate\Support\Str;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process;

final class BpmnLayoutService
{
/**
* @return array{bpmn: string, warnings: list<string>}
*/
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<string>, error: ?string}
*/
private function parseStderr(string $stderr): array

Check failure on line 70 in ProcessMaker/Mcp/Processes/BpmnLayoutService.php

View check run for this annotation

Decisions SonarQube / SonarQube Code Analysis

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed.

[S3776] Cognitive Complexity of functions should not be too high See more on https://builds.decisions.com:9000/project/issues?id=ProcessMaker_processmaker_AYkzkfKexYvY_isvKt07&pullRequest=9155&issues=d36cb412-f7a6-44e5-9d0b-8581c8117f61&open=d36cb412-f7a6-44e5-9d0b-8581c8117f61
{
$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];
}
}
85 changes: 85 additions & 0 deletions ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

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';

Check warning on line 25 in ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php

View check run for this annotation

Decisions SonarQube / SonarQube Code Analysis

Using HTTP protocol is insecure. Use HTTPS instead.

[S5332] Clear-text protocols should not be used See more on https://builds.decisions.com:9000/project/issues?id=ProcessMaker_processmaker_AYkzkfKexYvY_isvKt07&pullRequest=9155&issues=103c45a1-d643-46de-b9d2-68325db04309&open=103c45a1-d643-46de-b9d2-68325db04309

/**
* @return array{ok: bool, errors: list<array{nodeId: ?string, code: string, message: string}>, warnings: list<array{nodeId: ?string, code: string, message: string}>}
*/
Expand Down Expand Up @@ -52,13 +54,41 @@
$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);

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<string>
*/
Expand Down Expand Up @@ -106,6 +136,7 @@
}

$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);
Expand Down Expand Up @@ -189,6 +220,60 @@
}
}

/**
* Nayra wires runtime flows from bpmn:outgoing / bpmn:incoming children.
* sourceRef/targetRef alone leave Start Events with 0 outgoing flows.
*
* @param list<array{nodeId: ?string, code: string, message: string}> $errors
*/
/**
* @param list<array{nodeId: ?string, code: string, message: string}> $errors
*/
private function requireSequenceFlowDiagramInterchange(DOMXPath $xpath, array &$errors): void

Check failure on line 232 in ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php

View check run for this annotation

Decisions SonarQube / SonarQube Code Analysis

Refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed.

[S3776] Cognitive Complexity of functions should not be too high See more on https://builds.decisions.com:9000/project/issues?id=ProcessMaker_processmaker_AYkzkfKexYvY_isvKt07&pullRequest=9155&issues=726ab0fe-86d1-4029-ae6d-bd6b3acbcb72&open=726ab0fe-86d1-4029-ae6d-bd6b3acbcb72
{
$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.
Expand Down
76 changes: 74 additions & 2 deletions ProcessMaker/Mcp/Processes/ProcessCatalog.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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']);
}
Expand Down Expand Up @@ -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']);
}
Expand Down Expand Up @@ -186,6 +190,38 @@ public function validate(User $user, array $input): array
return $this->validator->validate(is_string($bpmn) ? $bpmn : null);
}

/**
* @param array<string, mixed> $input
* @return array{bpmn: string, warnings: list<string>, 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<string, mixed> $filters
*/
Expand Down Expand Up @@ -282,6 +318,42 @@ private function writable(array $input): array
]));
}

/**
* @param array<string, mixed> $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<string, mixed> $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);
Expand Down
3 changes: 3 additions & 0 deletions ProcessMaker/Mcp/Servers/ProcessServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -58,6 +60,7 @@ class ProcessServer extends Server
CreateProcessTool::class,
UpdateProcessTool::class,
ValidateProcessTool::class,
LayoutBpmnTool::class,
];

public function createContext(): ServerContext
Expand Down
1 change: 1 addition & 0 deletions ProcessMaker/Mcp/Tools/Processes/CreateProcessTool.php
Original file line number Diff line number Diff line change
Expand Up @@ -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),
];
}
}
Loading
Loading