@markasso/mcp 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,21 +80,23 @@ Bump `version` in `mcp/package.json`, add the entry to `mcp/CHANGELOG.md`, merge
80
80
  |---|---|
81
81
  | `diagram_new` | Start an empty diagram |
82
82
  | `diagram_open` | Open a `.markasso` file or a markasso.it share link |
83
- | `diagram_read` | Describe nodes (key, kind, label, position, size) and connections (with their ids) |
83
+ | `diagram_read` | Describe nodes (key, kind, label, position, size), connections (with their ids) and layout warnings |
84
84
  | `diagram_add_nodes` | Add nodes by key: rectangle, ellipse, rhombus, text, flowchart symbols, icons, with an optional font size. Nodes without a size fit their label |
85
85
  | `diagram_connect` | Connect nodes by key: label and its font size, straight/elbow routing, arrowhead styles, dashed |
86
86
  | `diagram_update` | Change a node's label, color, font size, position or size |
87
87
  | `diagram_update_edge` | Change a connection's label, label font size, routing, heads, dash or color |
88
88
  | `diagram_disconnect` | Remove connections (by id or by from/to), keeping the nodes |
89
89
  | `diagram_remove` | Remove nodes and their connections |
90
- | `diagram_layout` | Arrange nodes in layers (top-to-bottom or left-to-right) |
90
+ | `diagram_layout` | Arrange nodes in layers (top-to-bottom or left-to-right), then report layout warnings |
91
91
  | `icons_search` | Find generic architecture icons and Kubernetes icons |
92
92
  | `diagram_save` | Save as `.markasso` |
93
93
  | `diagram_export_svg` | Export an SVG image |
94
- | `diagram_export_png` | Render a PNG the agent can look at (optionally saved to a file) |
94
+ | `diagram_export_png` | Render a PNG the agent can look at (optionally saved to a file), with layout warnings. With `path` and `returnImage: false` it only writes the file, for a live preview, and answers in text |
95
95
  | `diagram_share` | Publish and return a markasso.it link, with its expiry date |
96
96
  | `live_join` / `live_leave` | Draw on a live board in real time (link from ⋯ More tools → Start live session) |
97
97
 
98
+ **Layout warnings.** `diagram_layout`, `diagram_read` and `diagram_export_png` check the diagram as it is drawn and list, by node key and connection id, what makes it hard to read: connections passing through a node, connection labels on top of a node or another label, crossing connections (with how many crossings) and overlapping nodes. Each kind comes with a hint, such as trying the other layout direction or elbow routing. A node drawn around others counts as a frame and is not reported. No warnings, no extra text.
99
+
98
100
  Vendor icon packs (AWS, Azure, Google Cloud) are not available to agents: they can't be redistributed, and in the app they are imported by each user into their own browser.
99
101
 
100
102
  ## Example prompts
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { readFile, writeFile } from "node:fs/promises";
2
+ import { readFile, rename, rm, writeFile } from "node:fs/promises";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
5
  import { z } from "zod";
6
+ import { basename, dirname, join } from "node:path";
6
7
  import { Resvg } from "@resvg/resvg-js";
7
8
  //#region ../src/elements/element.ts
8
9
  /**
@@ -3657,7 +3658,7 @@ var FRACTIONS = [
3657
3658
  .85
3658
3659
  ];
3659
3660
  /** Samples used to treat a curved connector as a polyline. */
3660
- var CURVE_SAMPLES = 12;
3661
+ var CURVE_SAMPLES$1 = 12;
3661
3662
  /** Label box size, padding included (matches the gap the shaft leaves). */
3662
3663
  function getConnectorLabelSize(el) {
3663
3664
  const fontSize = el.labelFontSize ?? 12;
@@ -3672,20 +3673,20 @@ function isCurved(el) {
3672
3673
  return el.type === "line" && el.cx !== void 0 && el.cy !== void 0;
3673
3674
  }
3674
3675
  /** Polyline the connector is drawn along (curves sampled). */
3675
- function polylineOf(el, elements) {
3676
+ function polylineOf$1(el, elements) {
3676
3677
  const route = resolveConnectorRoute(el, elements);
3677
3678
  if (!isCurved(el) || route.length !== 2) return route;
3678
3679
  const [[x1, y1], [x2, y2]] = route;
3679
3680
  return Array.from({ length: 13 }, (_, i) => {
3680
- const p = getQuadraticPoint(x1, y1, el.cx, el.cy, x2, y2, i / CURVE_SAMPLES);
3681
+ const p = getQuadraticPoint(x1, y1, el.cx, el.cy, x2, y2, i / CURVE_SAMPLES$1);
3681
3682
  return [p.x, p.y];
3682
3683
  });
3683
3684
  }
3684
- function segmentsOf(points) {
3685
+ function segmentsOf$1(points) {
3685
3686
  return points.slice(1).map((p, i) => [points[i], p]);
3686
3687
  }
3687
3688
  /** Length of the part of segment a→b inside `r` (Liang-Barsky clipping). */
3688
- function clippedLength(a, b, r) {
3689
+ function clippedLength$1(a, b, r) {
3689
3690
  const dx = b[0] - a[0];
3690
3691
  const dy = b[1] - a[1];
3691
3692
  let t0 = 0;
@@ -3719,7 +3720,7 @@ var rectOf = (b) => ({
3719
3720
  w: b.w,
3720
3721
  h: b.h
3721
3722
  });
3722
- function isConnector$1(el) {
3723
+ function isConnector$2(el) {
3723
3724
  return el.type === "line" || el.type === "arrow";
3724
3725
  }
3725
3726
  var cache = /* @__PURE__ */ new WeakMap();
@@ -3727,13 +3728,13 @@ var cache = /* @__PURE__ */ new WeakMap();
3727
3728
  function getConnectorLabelBoxes(elements) {
3728
3729
  const cached = cache.get(elements);
3729
3730
  if (cached) return cached;
3730
- const connectors = elements.filter((el) => isConnector$1(el) && el.visible !== false);
3731
- const polylines = new Map(connectors.map((el) => [el.id, polylineOf(el, elements)]));
3732
- const strokes = connectors.flatMap((el) => segmentsOf(polylines.get(el.id)).map((seg) => ({
3731
+ const connectors = elements.filter((el) => isConnector$2(el) && el.visible !== false);
3732
+ const polylines = new Map(connectors.map((el) => [el.id, polylineOf$1(el, elements)]));
3733
+ const strokes = connectors.flatMap((el) => segmentsOf$1(polylines.get(el.id)).map((seg) => ({
3733
3734
  owner: el.id,
3734
3735
  seg
3735
3736
  })));
3736
- const nodes = elements.filter((el) => !isConnector$1(el) && el.visible !== false && el.type !== "freehand").map((el) => getConnectorBox(el));
3737
+ const nodes = elements.filter((el) => !isConnector$2(el) && el.visible !== false && el.type !== "freehand").map((el) => getConnectorBox(el));
3737
3738
  const placed = [];
3738
3739
  const result = /* @__PURE__ */ new Map();
3739
3740
  for (const el of connectors) {
@@ -3759,7 +3760,7 @@ function curveMidpointBox(points, w, h) {
3759
3760
  }
3760
3761
  function bestBox(ownerId, points, w, h, strokes, placed, nodes) {
3761
3762
  const [mx, my] = getRoutePointAt(points, .5);
3762
- const segments = segmentsOf(points);
3763
+ const segments = segmentsOf$1(points);
3763
3764
  const total = segments.reduce((sum, [a, b]) => sum + Math.hypot(b[0] - a[0], b[1] - a[1]), 0);
3764
3765
  if (total < 1) return {
3765
3766
  x: mx,
@@ -3790,7 +3791,7 @@ function bestBox(ownerId, points, w, h, strokes, placed, nodes) {
3790
3791
  h: r.h - 2
3791
3792
  };
3792
3793
  let cost = 0;
3793
- for (const s of strokes) if (s.owner !== ownerId) cost += clippedLength(s.seg[0], s.seg[1], inner) * 20;
3794
+ for (const s of strokes) if (s.owner !== ownerId) cost += clippedLength$1(s.seg[0], s.seg[1], inner) * 20;
3794
3795
  for (const other of placed) cost += overlapArea(r, rectOf(other)) * 2;
3795
3796
  for (const node of nodes) cost += overlapArea(inner, node) * 2;
3796
3797
  cost += Math.max(0, -room) * 2;
@@ -4202,7 +4203,7 @@ function escapeXml(str) {
4202
4203
  }
4203
4204
  //#endregion
4204
4205
  //#region package.json
4205
- var version = "0.5.1";
4206
+ var version = "0.6.0";
4206
4207
  //#endregion
4207
4208
  //#region ../src/core/layout.ts
4208
4209
  /** Orders vertices without recursion, preserving input order when unconstrained. */
@@ -5677,12 +5678,12 @@ var BASE_STYLE = {
5677
5678
  function slugify(text) {
5678
5679
  return text.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
5679
5680
  }
5680
- function isConnector(el) {
5681
+ function isConnector$1(el) {
5681
5682
  return el.type === "line" || el.type === "arrow";
5682
5683
  }
5683
5684
  /** Elements an agent treats as nodes (everything that is not a connector). */
5684
5685
  function isNode(el) {
5685
- return !isConnector(el) && el.type !== "freehand" && el.type !== "curve";
5686
+ return !isConnector$1(el) && el.type !== "freehand" && el.type !== "curve";
5686
5687
  }
5687
5688
  function elementLabel(el) {
5688
5689
  if (el.type === "text") return el.content;
@@ -5715,7 +5716,7 @@ var Diagram = class {
5715
5716
  snapshot() {
5716
5717
  const all = this.elements;
5717
5718
  return all.map((el) => {
5718
- if (!isConnector(el) || !el.startElementId && !el.endElementId) return el;
5719
+ if (!isConnector$1(el) || !el.startElementId && !el.endElementId) return el;
5719
5720
  if (el.type === "line" && el.cx !== void 0 && el.cy !== void 0) return {
5720
5721
  ...el,
5721
5722
  ...resolveArrowEndpoints(el, all)
@@ -5936,8 +5937,12 @@ var Diagram = class {
5936
5937
  });
5937
5938
  return created.length;
5938
5939
  }
5940
+ /** Changes a node in one undoable step. */
5939
5941
  update(key, patch) {
5940
5942
  const id = this.idOf(key);
5943
+ this.moving([id], () => this.applyNodePatch(id, patch));
5944
+ }
5945
+ applyNodePatch(id, patch) {
5941
5946
  const el = this.elements.find((e) => e.id === id);
5942
5947
  if (patch.label !== void 0) this.dispatch(el.type === "text" ? {
5943
5948
  type: "EDIT_TEXT",
@@ -5992,7 +5997,7 @@ var Diagram = class {
5992
5997
  }
5993
5998
  /** Connector matching the reference; throws when none or several match. */
5994
5999
  edgeOf(ref) {
5995
- const connectors = this.elements.filter(isConnector);
6000
+ const connectors = this.elements.filter(isConnector$1);
5996
6001
  let matches;
5997
6002
  if (ref.id) matches = connectors.filter((el) => el.id.startsWith(ref.id));
5998
6003
  else if (ref.from && ref.to) {
@@ -6063,9 +6068,65 @@ var Diagram = class {
6063
6068
  y: el.y + (p.y - b.y)
6064
6069
  };
6065
6070
  });
6066
- if (moves.length > 0) this.dispatch({
6071
+ if (moves.length === 0) return;
6072
+ this.moving(moves.map((m) => m.id), () => this.dispatch({
6067
6073
  type: "ALIGN_ELEMENTS",
6068
6074
  moves
6075
+ }));
6076
+ }
6077
+ /**
6078
+ * Runs `change`, which may move or resize the nodes `ids`, then points the
6079
+ * floating ends of their connectors back at the nodes' centers, all in one
6080
+ * undo step.
6081
+ *
6082
+ * A floating end keeps the point stored when it was connected, and the
6083
+ * renderer treats a stored point lying on the shape's border as a spot the
6084
+ * user picked (see resolveArrowEndpoints). Once a node moves, its old
6085
+ * center can land exactly on its new border (a layout grid makes that
6086
+ * common), and the arrow then sticks to the wrong side and crosses the
6087
+ * node. A center is never on the border, so the end faces the other node
6088
+ * again. Pinned ends (anchors) follow their node and are left alone.
6089
+ */
6090
+ moving(ids, change) {
6091
+ this.history.beginDrag();
6092
+ try {
6093
+ change();
6094
+ const update = this.freshEnds(new Set(ids));
6095
+ if (update.length > 0) this.dispatch({
6096
+ type: "PATCH_ELEMENTS",
6097
+ update
6098
+ });
6099
+ } finally {
6100
+ this.history.endDrag();
6101
+ }
6102
+ }
6103
+ /** Patches moving the floating ends bound to `ids` to the node centers. */
6104
+ freshEnds(ids) {
6105
+ const centers = /* @__PURE__ */ new Map();
6106
+ for (const el of this.elements) {
6107
+ if (!ids.has(el.id)) continue;
6108
+ const b = getElementBounds(el);
6109
+ centers.set(el.id, {
6110
+ x: b.x + b.w / 2,
6111
+ y: b.y + b.h / 2
6112
+ });
6113
+ }
6114
+ return this.elements.filter(isConnector$1).flatMap((el) => {
6115
+ const start = el.startElementId && !el.startAnchor ? centers.get(el.startElementId) : void 0;
6116
+ const end = el.endElementId && !el.endAnchor ? centers.get(el.endElementId) : void 0;
6117
+ const set = {};
6118
+ if (start && (start.x !== el.x || start.y !== el.y)) {
6119
+ set.x = start.x;
6120
+ set.y = start.y;
6121
+ }
6122
+ if (end && (end.x !== el.x2 || end.y !== el.y2)) {
6123
+ set.x2 = end.x;
6124
+ set.y2 = end.y;
6125
+ }
6126
+ return Object.keys(set).length > 0 ? [{
6127
+ id: el.id,
6128
+ set
6129
+ }] : [];
6069
6130
  });
6070
6131
  }
6071
6132
  /**
@@ -6082,7 +6143,7 @@ var Diagram = class {
6082
6143
  if (nodes.length === 0) return 0;
6083
6144
  const ids = new Set(nodes.map((el) => el.id));
6084
6145
  const boxes = new Map(nodes.map((el) => [el.id, getConnectorBox(el)]));
6085
- const edges = this.elements.flatMap((el) => isConnector(el) && el.startElementId && el.endElementId && ids.has(el.startElementId) && ids.has(el.endElementId) ? [{
6146
+ const edges = this.elements.flatMap((el) => isConnector$1(el) && el.startElementId && el.endElementId && ids.has(el.startElementId) && ids.has(el.endElementId) ? [{
6086
6147
  from: el.startElementId,
6087
6148
  to: el.endElementId
6088
6149
  }] : []);
@@ -6315,6 +6376,22 @@ async function saveMarkassoFile(path, elements) {
6315
6376
  elements
6316
6377
  }, null, 2)}\n`, "utf8");
6317
6378
  }
6379
+ /**
6380
+ * Writes a file in one step for readers polling it (e.g. a live preview of
6381
+ * an exported PNG): the data goes to a temporary file in the same directory,
6382
+ * which is then renamed over `path`, so a reader sees the old file or the
6383
+ * new one, never a partial write. Same directory keeps the rename atomic.
6384
+ */
6385
+ async function writeFileAtomic(path, data) {
6386
+ const tmp = join(dirname(path), `.${basename(path)}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`);
6387
+ try {
6388
+ await writeFile(tmp, data);
6389
+ await rename(tmp, path);
6390
+ } catch (error) {
6391
+ await rm(tmp, { force: true });
6392
+ throw error;
6393
+ }
6394
+ }
6318
6395
  //#endregion
6319
6396
  //#region src/live.ts
6320
6397
  var ROOM_ID = /^[a-zA-Z0-9_-]{3,64}$/;
@@ -6485,6 +6562,229 @@ var LiveLink = class LiveLink {
6485
6562
  }
6486
6563
  };
6487
6564
  //#endregion
6565
+ //#region src/warnings.ts
6566
+ /** Shortest run of a connector inside a node that counts as crossing it. */
6567
+ var MIN_INSIDE = 8;
6568
+ /** Smallest overlap, in px on each axis, worth reporting. */
6569
+ var MIN_OVERLAP = 2;
6570
+ /** Crossings this close to a segment end are joins, not crossings. */
6571
+ var END_SLACK = 3;
6572
+ /** Samples used to treat a curved connector as a polyline. */
6573
+ var CURVE_SAMPLES = 12;
6574
+ /** Items listed per warning type before "and N more". */
6575
+ var MAX_LISTED = 8;
6576
+ function isConnector(el) {
6577
+ return el.type === "line" || el.type === "arrow";
6578
+ }
6579
+ /** Polyline the connector is drawn along (curves sampled). */
6580
+ function polylineOf(el, elements) {
6581
+ const route = resolveConnectorRoute(el, elements);
6582
+ if (el.type !== "line" || el.cx === void 0 || el.cy === void 0 || route.length !== 2) return route;
6583
+ const [[x1, y1], [x2, y2]] = route;
6584
+ const { cx, cy } = el;
6585
+ return Array.from({ length: 13 }, (_, i) => {
6586
+ const p = getQuadraticPoint(x1, y1, cx, cy, x2, y2, i / CURVE_SAMPLES);
6587
+ return [p.x, p.y];
6588
+ });
6589
+ }
6590
+ function segmentsOf(points) {
6591
+ return points.slice(1).map((p, i) => [points[i], p]);
6592
+ }
6593
+ /**
6594
+ * Part of a node a connector must not cross: the rectangle inscribed in an
6595
+ * ellipse or rhombus (so passing near a corner of the bounding box is not
6596
+ * reported), the connector box otherwise, inset by a couple of pixels so
6597
+ * a stroke running along the border doesn't count.
6598
+ */
6599
+ function coreRect(el) {
6600
+ const b = getConnectorBox(el);
6601
+ const scale = el.type === "ellipse" ? Math.SQRT1_2 : el.type === "rhombus" ? .5 : 1;
6602
+ const w = b.w * scale - 4;
6603
+ const h = b.h * scale - 4;
6604
+ return {
6605
+ x: b.x + (b.w - w) / 2,
6606
+ y: b.y + (b.h - h) / 2,
6607
+ w: Math.max(0, w),
6608
+ h: Math.max(0, h)
6609
+ };
6610
+ }
6611
+ /** Length of segment a-b inside `r` (Liang-Barsky clipping). */
6612
+ function clippedLength(a, b, r) {
6613
+ const dx = b[0] - a[0];
6614
+ const dy = b[1] - a[1];
6615
+ let t0 = 0;
6616
+ let t1 = 1;
6617
+ const edges = [
6618
+ [-dx, a[0] - r.x],
6619
+ [dx, r.x + r.w - a[0]],
6620
+ [-dy, a[1] - r.y],
6621
+ [dy, r.y + r.h - a[1]]
6622
+ ];
6623
+ for (const [p, q] of edges) {
6624
+ if (Math.abs(p) < 1e-9) {
6625
+ if (q < 0) return 0;
6626
+ continue;
6627
+ }
6628
+ const t = q / p;
6629
+ if (p < 0) t0 = Math.max(t0, t);
6630
+ else t1 = Math.min(t1, t);
6631
+ if (t0 > t1) return 0;
6632
+ }
6633
+ return (t1 - t0) * Math.hypot(dx, dy);
6634
+ }
6635
+ function overlaps(a, b) {
6636
+ const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
6637
+ const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
6638
+ return w >= MIN_OVERLAP && h >= MIN_OVERLAP;
6639
+ }
6640
+ function contains(outer, inner) {
6641
+ return inner.x >= outer.x && inner.y >= outer.y && inner.x + inner.w <= outer.x + outer.w && inner.y + inner.h <= outer.y + outer.h;
6642
+ }
6643
+ /**
6644
+ * Whether two segments cross away from their ends. Connectors that share a
6645
+ * node meet at its border, and an elbow's bends meet the next segment: both
6646
+ * are joins, not crossings. Collinear runs are left out too.
6647
+ */
6648
+ function segmentsCross(s, t) {
6649
+ const [[ax, ay], [bx, by]] = s;
6650
+ const [[cx, cy], [dx, dy]] = t;
6651
+ const rx = bx - ax;
6652
+ const ry = by - ay;
6653
+ const sx = dx - cx;
6654
+ const sy = dy - cy;
6655
+ const den = rx * sy - ry * sx;
6656
+ if (Math.abs(den) < 1e-9) return false;
6657
+ const u = ((cx - ax) * sy - (cy - ay) * sx) / den;
6658
+ const v = ((cx - ax) * ry - (cy - ay) * rx) / den;
6659
+ const lenS = Math.hypot(rx, ry);
6660
+ const lenT = Math.hypot(sx, sy);
6661
+ return u * lenS > END_SLACK && (1 - u) * lenS > END_SLACK && v * lenT > END_SLACK && (1 - v) * lenT > END_SLACK;
6662
+ }
6663
+ function findWarnings(diagram) {
6664
+ const elements = diagram.elements;
6665
+ const keys = diagram.nodeKeys();
6666
+ const nodes = elements.filter((el) => keys.has(el.id) && el.visible !== false);
6667
+ const boxes = new Map(nodes.map((el) => [el.id, getConnectorBox(el)]));
6668
+ const containers = new Set(nodes.filter((outer) => nodes.some((inner) => inner !== outer && contains(boxes.get(outer.id), boxes.get(inner.id)))).map((el) => el.id));
6669
+ const solid = nodes.filter((el) => !containers.has(el.id));
6670
+ const cores = new Map(solid.map((el) => [el.id, coreRect(el)]));
6671
+ const edges = [];
6672
+ for (const el of elements) {
6673
+ if (!isConnector(el) || el.visible === false) continue;
6674
+ const from = el.startElementId ? keys.get(el.startElementId) : void 0;
6675
+ const to = el.endElementId ? keys.get(el.endElementId) : void 0;
6676
+ if (!from || !to) continue;
6677
+ edges.push({
6678
+ name: {
6679
+ id: edgeShortId(el),
6680
+ from,
6681
+ to
6682
+ },
6683
+ el,
6684
+ segments: segmentsOf(polylineOf(el, elements))
6685
+ });
6686
+ }
6687
+ const throughNodes = [];
6688
+ for (const edge of edges) for (const node of solid) {
6689
+ if (node.id === edge.el.startElementId || node.id === edge.el.endElementId) continue;
6690
+ const core = cores.get(node.id);
6691
+ if (edge.segments.reduce((sum, [a, b]) => sum + clippedLength(a, b, core), 0) >= MIN_INSIDE) throughNodes.push({
6692
+ edge: edge.name,
6693
+ node: keys.get(node.id)
6694
+ });
6695
+ }
6696
+ const labels = getConnectorLabelBoxes(elements);
6697
+ const labelRects = edges.flatMap((edge) => {
6698
+ const box = labels.get(edge.el.id);
6699
+ return box ? [{
6700
+ edge: edge.name,
6701
+ rect: {
6702
+ x: box.x - box.w / 2,
6703
+ y: box.y - box.h / 2,
6704
+ w: box.w,
6705
+ h: box.h
6706
+ }
6707
+ }] : [];
6708
+ });
6709
+ const labelOverlaps = [];
6710
+ labelRects.forEach((label, i) => {
6711
+ for (const node of solid) if (overlaps(label.rect, cores.get(node.id))) labelOverlaps.push({
6712
+ edge: label.edge,
6713
+ node: keys.get(node.id)
6714
+ });
6715
+ for (const other of labelRects.slice(i + 1)) if (overlaps(label.rect, other.rect)) labelOverlaps.push({
6716
+ edge: label.edge,
6717
+ label: other.edge
6718
+ });
6719
+ });
6720
+ const crossings = [];
6721
+ edges.forEach((a, i) => {
6722
+ for (const b of edges.slice(i + 1)) {
6723
+ let count = 0;
6724
+ for (const s of a.segments) for (const t of b.segments) if (segmentsCross(s, t)) count++;
6725
+ if (count > 0) crossings.push({
6726
+ a: a.name,
6727
+ b: b.name,
6728
+ count
6729
+ });
6730
+ }
6731
+ });
6732
+ const nodeOverlaps = [];
6733
+ nodes.forEach((a, i) => {
6734
+ const ba = boxes.get(a.id);
6735
+ for (const b of nodes.slice(i + 1)) {
6736
+ const bb = boxes.get(b.id);
6737
+ if (overlaps(ba, bb) && !contains(ba, bb) && !contains(bb, ba)) nodeOverlaps.push([keys.get(a.id), keys.get(b.id)]);
6738
+ }
6739
+ });
6740
+ return {
6741
+ throughNodes,
6742
+ labelOverlaps,
6743
+ crossings,
6744
+ nodeOverlaps
6745
+ };
6746
+ }
6747
+ function edgeText(edge) {
6748
+ return `${edge.from} -> ${edge.to} (id ${edge.id})`;
6749
+ }
6750
+ /** Up to MAX_LISTED items joined with "; ", then how many were left out. */
6751
+ function listed(items) {
6752
+ const shown = items.slice(0, MAX_LISTED).join("; ");
6753
+ const rest = items.length - MAX_LISTED;
6754
+ return rest > 0 ? `${shown}; and ${rest} more` : shown;
6755
+ }
6756
+ /**
6757
+ * Short text for the agent, one line per kind of problem with a hint, or
6758
+ * an empty string when the diagram is clear.
6759
+ */
6760
+ function formatWarnings(w) {
6761
+ const lines = [];
6762
+ if (w.throughNodes.length > 0) {
6763
+ const byEdge = /* @__PURE__ */ new Map();
6764
+ for (const { edge, node } of w.throughNodes) {
6765
+ const entry = byEdge.get(edge.id) ?? {
6766
+ edge,
6767
+ nodes: []
6768
+ };
6769
+ entry.nodes.push(node);
6770
+ byEdge.set(edge.id, entry);
6771
+ }
6772
+ lines.push(`- Connections through nodes: ${listed([...byEdge.values()].map((e) => `${edgeText(e.edge)} crosses ${e.nodes.join(", ")}`))}. Hint: move the crossed nodes off the line (diagram_update x/y) or try the other layout direction.`);
6773
+ }
6774
+ if (w.labelOverlaps.length > 0) lines.push(`- Labels overlapping: ${listed(w.labelOverlaps.map((o) => "node" in o ? `label of ${edgeText(o.edge)} on node ${o.node}` : `labels of ${edgeText(o.edge)} and ${edgeText(o.label)}`))}. Hint: move the nodes apart or shorten the labels.`);
6775
+ if (w.crossings.length > 0) {
6776
+ const total = w.crossings.reduce((sum, c) => sum + c.count, 0);
6777
+ lines.push(`- Crossing connections (${total}): ${listed(w.crossings.map((c) => `${edgeText(c.a)} x ${edgeText(c.b)}`))}. Hint: try the other layout direction, or routing "elbow" (diagram_update_edge).`);
6778
+ }
6779
+ if (w.nodeOverlaps.length > 0) lines.push(`- Overlapping nodes: ${listed(w.nodeOverlaps.map(([a, b]) => `${a} and ${b}`))}. Hint: run diagram_layout, or move them (diagram_update x/y).`);
6780
+ return lines.length > 0 ? `Warnings:\n${lines.join("\n")}` : "";
6781
+ }
6782
+ /** Warnings of the current diagram as text to append to a tool result. */
6783
+ function warningsSuffix(diagram) {
6784
+ const text = formatWarnings(findWarnings(diagram));
6785
+ return text ? `\n${text}` : "";
6786
+ }
6787
+ //#endregion
6488
6788
  //#region src/png.ts
6489
6789
  /** Longest side of a rendered PNG, so huge boards stay a sane payload. */
6490
6790
  var MAX_SIDE = 4096;
@@ -6508,6 +6808,35 @@ function svgToPng(svg, scale = 2) {
6508
6808
  }
6509
6809
  }).render().asPng();
6510
6810
  }
6811
+ /**
6812
+ * Result of diagram_export_png: the image unless `returnImage` is false
6813
+ * (an agent refreshing a preview file doesn't need it back), then what was
6814
+ * saved and the diagram's warnings.
6815
+ */
6816
+ async function exportPng(diagram, options) {
6817
+ const { path, background, returnImage = true } = options;
6818
+ if (!returnImage && !path) throw new Error("Nothing to do: give a path to save the PNG, or leave returnImage on.");
6819
+ await diagram.loadUsedIconPacks();
6820
+ const svg = sceneToSVG(diagram.elements, {
6821
+ canvasColor: "#080808",
6822
+ withBackground: (background ?? "dark") === "dark"
6823
+ });
6824
+ if (!svg) return [{
6825
+ type: "text",
6826
+ text: "The diagram is empty: nothing to export."
6827
+ }];
6828
+ const png = svgToPng(svg);
6829
+ if (path) await writeFileAtomic(path, png);
6830
+ const notes = [path ? `Saved PNG to ${path}.` : "", formatWarnings(findWarnings(diagram))].filter(Boolean);
6831
+ return [...returnImage ? [{
6832
+ type: "image",
6833
+ data: png.toString("base64"),
6834
+ mimeType: "image/png"
6835
+ }] : [], ...notes.map((text) => ({
6836
+ type: "text",
6837
+ text
6838
+ }))];
6839
+ }
6511
6840
  //#endregion
6512
6841
  //#region src/server.ts
6513
6842
  /**
@@ -6517,7 +6846,7 @@ function svgToPng(svg, scale = 2) {
6517
6846
  var SERVER_INSTRUCTIONS = `Markasso is a whiteboard for diagrams. Workflow:
6518
6847
  1. diagram_new (or diagram_open / live_join to work on an existing board).
6519
6848
  2. diagram_add_nodes with short keys, then diagram_connect by key.
6520
- 3. diagram_layout to arrange everything (don't compute coordinates yourself).
6849
+ 3. diagram_layout to arrange everything (don't compute coordinates yourself). When it lists Warnings, fix them (each comes with a hint).
6521
6850
  4. diagram_export_png to look at the result (diagram_read for keys and connection ids); diagram_disconnect / diagram_update_edge to adjust connections.
6522
6851
  5. diagram_share for a link, or diagram_save / diagram_export_svg for files.
6523
6852
  Node kinds: rectangle, ellipse, rhombus, text, icon, and flowchart symbols (terminator = start/end, data = I/O, document, database, predefinedProcess, preparation, manualInput, delay). For architecture diagrams prefer kind "icon" (icons_search finds them).
@@ -6631,12 +6960,12 @@ server.registerTool("diagram_open", {
6631
6960
  }));
6632
6961
  server.registerTool("diagram_read", {
6633
6962
  title: "Read diagram",
6634
- description: "Describe the current diagram: nodes (key, kind, label, position, size) and connections.",
6963
+ description: "Describe the current diagram: nodes (key, kind, label, position, size), connections and layout warnings.",
6635
6964
  inputSchema: {},
6636
6965
  annotations: { readOnlyHint: true }
6637
6966
  }, guarded(() => {
6638
6967
  const peers = live?.connected ? `\nPeople in the room: ${live.otherPeers.map((p) => p.name).join(", ") || "none"}` : "";
6639
- return `${describeDiagram(diagram)}${peers}`;
6968
+ return `${describeDiagram(diagram)}${peers}${warningsSuffix(diagram)}`;
6640
6969
  }));
6641
6970
  server.registerTool("diagram_add_nodes", {
6642
6971
  title: "Add nodes",
@@ -6720,7 +7049,7 @@ server.registerTool("diagram_update_edge", {
6720
7049
  }));
6721
7050
  server.registerTool("diagram_layout", {
6722
7051
  title: "Auto layout",
6723
- description: "Arrange nodes in layers following their connections (TB = top to bottom, LR = left to right). Use after adding nodes.",
7052
+ description: "Arrange nodes in layers following their connections (TB = top to bottom, LR = left to right). Use after adding nodes. Reports layout warnings (connections through nodes, overlaps, crossings) when there are any.",
6724
7053
  inputSchema: {
6725
7054
  direction: z.enum(["TB", "LR"]).optional(),
6726
7055
  keys: z.array(z.string()).optional().describe("Only these nodes (default: all)")
@@ -6728,7 +7057,7 @@ server.registerTool("diagram_layout", {
6728
7057
  }, guarded(({ direction, keys }) => {
6729
7058
  const count = diagram.layout(direction ?? "TB", keys);
6730
7059
  if (count === 0) return "Nothing to lay out.";
6731
- return `Arranged ${count} nodes (${direction ?? "TB"}).${liveSuffix()}`;
7060
+ return `Arranged ${count} nodes (${direction ?? "TB"}).${warningsSuffix(diagram)}${liveSuffix()}`;
6732
7061
  }));
6733
7062
  server.registerTool("icons_search", {
6734
7063
  title: "Search icons",
@@ -6777,30 +7106,16 @@ server.registerTool("diagram_export_svg", {
6777
7106
  }));
6778
7107
  server.registerTool("diagram_export_png", {
6779
7108
  title: "Export PNG",
6780
- description: "Render the diagram as a PNG image, returned so you can look at it, and optionally saved to a file.",
7109
+ description: "Render the diagram as a PNG image, returned so you can look at it, and optionally saved to a file. Lists layout warnings (connections through nodes, overlaps, crossings) when there are any. To only refresh a preview file, set path and returnImage: false.",
6781
7110
  inputSchema: {
6782
7111
  path: z.string().min(1).optional().describe("Absolute path ending in .png (optional)"),
6783
- background: z.enum(["dark", "transparent"]).optional()
7112
+ background: z.enum(["dark", "transparent"]).optional(),
7113
+ returnImage: z.boolean().optional().describe("Return the image (default true). false with a path only writes the file and answers in text.")
6784
7114
  },
6785
7115
  annotations: { readOnlyHint: true }
6786
- }, async ({ path, background }) => {
7116
+ }, async (args) => {
6787
7117
  try {
6788
- await diagram.loadUsedIconPacks();
6789
- const svg = sceneToSVG(diagram.elements, {
6790
- canvasColor: "#080808",
6791
- withBackground: (background ?? "dark") === "dark"
6792
- });
6793
- if (!svg) return text("The diagram is empty: nothing to export.");
6794
- const png = svgToPng(svg);
6795
- if (path) await writeFile(path, png);
6796
- return { content: [{
6797
- type: "image",
6798
- data: png.toString("base64"),
6799
- mimeType: "image/png"
6800
- }, ...path ? [{
6801
- type: "text",
6802
- text: `Saved PNG to ${path}.`
6803
- }] : []] };
7118
+ return { content: await exportPng(diagram, args) };
6804
7119
  } catch (error) {
6805
7120
  return failure(error);
6806
7121
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markasso/mcp",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "MCP server that lets AI agents create, read and edit Markasso diagrams, offline or live on a shared board",
5
5
  "type": "module",
6
6
  "repository": {