@markasso/mcp 0.5.1 → 0.6.1

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.1";
4206
4207
  //#endregion
4207
4208
  //#region ../src/core/layout.ts
4208
4209
  /** Orders vertices without recursion, preserving input order when unconstrained. */
@@ -5668,6 +5669,8 @@ var DEFAULT_SIZES = {
5668
5669
  };
5669
5670
  /** Gap used when placing new nodes before an explicit layout. */
5670
5671
  var PLACEMENT_GAP = 60;
5672
+ /** Space below each unconnected text node (title) stacked above a layout. */
5673
+ var FLOATING_TEXT_GAP = 40;
5671
5674
  var BASE_STYLE = {
5672
5675
  strokeWidth: 2,
5673
5676
  opacity: 1,
@@ -5677,12 +5680,12 @@ var BASE_STYLE = {
5677
5680
  function slugify(text) {
5678
5681
  return text.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
5679
5682
  }
5680
- function isConnector(el) {
5683
+ function isConnector$1(el) {
5681
5684
  return el.type === "line" || el.type === "arrow";
5682
5685
  }
5683
5686
  /** Elements an agent treats as nodes (everything that is not a connector). */
5684
5687
  function isNode(el) {
5685
- return !isConnector(el) && el.type !== "freehand" && el.type !== "curve";
5688
+ return !isConnector$1(el) && el.type !== "freehand" && el.type !== "curve";
5686
5689
  }
5687
5690
  function elementLabel(el) {
5688
5691
  if (el.type === "text") return el.content;
@@ -5715,7 +5718,7 @@ var Diagram = class {
5715
5718
  snapshot() {
5716
5719
  const all = this.elements;
5717
5720
  return all.map((el) => {
5718
- if (!isConnector(el) || !el.startElementId && !el.endElementId) return el;
5721
+ if (!isConnector$1(el) || !el.startElementId && !el.endElementId) return el;
5719
5722
  if (el.type === "line" && el.cx !== void 0 && el.cy !== void 0) return {
5720
5723
  ...el,
5721
5724
  ...resolveArrowEndpoints(el, all)
@@ -5936,8 +5939,12 @@ var Diagram = class {
5936
5939
  });
5937
5940
  return created.length;
5938
5941
  }
5942
+ /** Changes a node in one undoable step. */
5939
5943
  update(key, patch) {
5940
5944
  const id = this.idOf(key);
5945
+ this.moving([id], () => this.applyNodePatch(id, patch));
5946
+ }
5947
+ applyNodePatch(id, patch) {
5941
5948
  const el = this.elements.find((e) => e.id === id);
5942
5949
  if (patch.label !== void 0) this.dispatch(el.type === "text" ? {
5943
5950
  type: "EDIT_TEXT",
@@ -5992,7 +5999,7 @@ var Diagram = class {
5992
5999
  }
5993
6000
  /** Connector matching the reference; throws when none or several match. */
5994
6001
  edgeOf(ref) {
5995
- const connectors = this.elements.filter(isConnector);
6002
+ const connectors = this.elements.filter(isConnector$1);
5996
6003
  let matches;
5997
6004
  if (ref.id) matches = connectors.filter((el) => el.id.startsWith(ref.id));
5998
6005
  else if (ref.from && ref.to) {
@@ -6063,9 +6070,65 @@ var Diagram = class {
6063
6070
  y: el.y + (p.y - b.y)
6064
6071
  };
6065
6072
  });
6066
- if (moves.length > 0) this.dispatch({
6073
+ if (moves.length === 0) return;
6074
+ this.moving(moves.map((m) => m.id), () => this.dispatch({
6067
6075
  type: "ALIGN_ELEMENTS",
6068
6076
  moves
6077
+ }));
6078
+ }
6079
+ /**
6080
+ * Runs `change`, which may move or resize the nodes `ids`, then points the
6081
+ * floating ends of their connectors back at the nodes' centers, all in one
6082
+ * undo step.
6083
+ *
6084
+ * A floating end keeps the point stored when it was connected, and the
6085
+ * renderer treats a stored point lying on the shape's border as a spot the
6086
+ * user picked (see resolveArrowEndpoints). Once a node moves, its old
6087
+ * center can land exactly on its new border (a layout grid makes that
6088
+ * common), and the arrow then sticks to the wrong side and crosses the
6089
+ * node. A center is never on the border, so the end faces the other node
6090
+ * again. Pinned ends (anchors) follow their node and are left alone.
6091
+ */
6092
+ moving(ids, change) {
6093
+ this.history.beginDrag();
6094
+ try {
6095
+ change();
6096
+ const update = this.freshEnds(new Set(ids));
6097
+ if (update.length > 0) this.dispatch({
6098
+ type: "PATCH_ELEMENTS",
6099
+ update
6100
+ });
6101
+ } finally {
6102
+ this.history.endDrag();
6103
+ }
6104
+ }
6105
+ /** Patches moving the floating ends bound to `ids` to the node centers. */
6106
+ freshEnds(ids) {
6107
+ const centers = /* @__PURE__ */ new Map();
6108
+ for (const el of this.elements) {
6109
+ if (!ids.has(el.id)) continue;
6110
+ const b = getElementBounds(el);
6111
+ centers.set(el.id, {
6112
+ x: b.x + b.w / 2,
6113
+ y: b.y + b.h / 2
6114
+ });
6115
+ }
6116
+ return this.elements.filter(isConnector$1).flatMap((el) => {
6117
+ const start = el.startElementId && !el.startAnchor ? centers.get(el.startElementId) : void 0;
6118
+ const end = el.endElementId && !el.endAnchor ? centers.get(el.endElementId) : void 0;
6119
+ const set = {};
6120
+ if (start && (start.x !== el.x || start.y !== el.y)) {
6121
+ set.x = start.x;
6122
+ set.y = start.y;
6123
+ }
6124
+ if (end && (end.x !== el.x2 || end.y !== el.y2)) {
6125
+ set.x2 = end.x;
6126
+ set.y2 = end.y;
6127
+ }
6128
+ return Object.keys(set).length > 0 ? [{
6129
+ id: el.id,
6130
+ set
6131
+ }] : [];
6069
6132
  });
6070
6133
  }
6071
6134
  /**
@@ -6082,7 +6145,7 @@ var Diagram = class {
6082
6145
  if (nodes.length === 0) return 0;
6083
6146
  const ids = new Set(nodes.map((el) => el.id));
6084
6147
  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) ? [{
6148
+ const edges = this.elements.flatMap((el) => isConnector$1(el) && el.startElementId && el.endElementId && ids.has(el.startElementId) && ids.has(el.endElementId) ? [{
6086
6149
  from: el.startElementId,
6087
6150
  to: el.endElementId
6088
6151
  }] : []);
@@ -6090,7 +6153,12 @@ var Diagram = class {
6090
6153
  x: Math.min(...[...boxes.values()].map((b) => b.x)),
6091
6154
  y: Math.min(...[...boxes.values()].map((b) => b.y))
6092
6155
  };
6093
- const positions = layeredLayout(nodes.map((el) => {
6156
+ const linked = new Set(this.elements.flatMap((el) => isConnector$1(el) ? [el.startElementId, el.endElementId].filter((id) => id !== void 0) : []));
6157
+ const floating = nodes.filter((el) => el.type === "text" && !linked.has(el.id));
6158
+ const laid = floating.length > 0 && floating.length < nodes.length ? nodes.filter((el) => !floating.includes(el)) : nodes;
6159
+ const above = laid === nodes ? [] : floating;
6160
+ const stackHeight = above.reduce((sum, el) => sum + boxes.get(el.id).h + FLOATING_TEXT_GAP, 0);
6161
+ const positions = layeredLayout(laid.map((el) => {
6094
6162
  const b = boxes.get(el.id);
6095
6163
  return {
6096
6164
  id: el.id,
@@ -6099,8 +6167,23 @@ var Diagram = class {
6099
6167
  };
6100
6168
  }), edges, {
6101
6169
  direction,
6102
- origin
6170
+ origin: {
6171
+ x: origin.x,
6172
+ y: origin.y + stackHeight
6173
+ }
6103
6174
  });
6175
+ if (above.length > 0) {
6176
+ const center = (Math.min(...laid.map((el) => positions.get(el.id).x)) + Math.max(...laid.map((el) => positions.get(el.id).x + boxes.get(el.id).w))) / 2;
6177
+ let y = origin.y;
6178
+ for (const el of above) {
6179
+ const b = boxes.get(el.id);
6180
+ positions.set(el.id, {
6181
+ x: center - b.w / 2,
6182
+ y
6183
+ });
6184
+ y += b.h + FLOATING_TEXT_GAP;
6185
+ }
6186
+ }
6104
6187
  this.moveNodes(positions);
6105
6188
  return positions.size;
6106
6189
  }
@@ -6315,6 +6398,22 @@ async function saveMarkassoFile(path, elements) {
6315
6398
  elements
6316
6399
  }, null, 2)}\n`, "utf8");
6317
6400
  }
6401
+ /**
6402
+ * Writes a file in one step for readers polling it (e.g. a live preview of
6403
+ * an exported PNG): the data goes to a temporary file in the same directory,
6404
+ * which is then renamed over `path`, so a reader sees the old file or the
6405
+ * new one, never a partial write. Same directory keeps the rename atomic.
6406
+ */
6407
+ async function writeFileAtomic(path, data) {
6408
+ const tmp = join(dirname(path), `.${basename(path)}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`);
6409
+ try {
6410
+ await writeFile(tmp, data);
6411
+ await rename(tmp, path);
6412
+ } catch (error) {
6413
+ await rm(tmp, { force: true });
6414
+ throw error;
6415
+ }
6416
+ }
6318
6417
  //#endregion
6319
6418
  //#region src/live.ts
6320
6419
  var ROOM_ID = /^[a-zA-Z0-9_-]{3,64}$/;
@@ -6485,6 +6584,229 @@ var LiveLink = class LiveLink {
6485
6584
  }
6486
6585
  };
6487
6586
  //#endregion
6587
+ //#region src/warnings.ts
6588
+ /** Shortest run of a connector inside a node that counts as crossing it. */
6589
+ var MIN_INSIDE = 8;
6590
+ /** Smallest overlap, in px on each axis, worth reporting. */
6591
+ var MIN_OVERLAP = 2;
6592
+ /** Crossings this close to a segment end are joins, not crossings. */
6593
+ var END_SLACK = 3;
6594
+ /** Samples used to treat a curved connector as a polyline. */
6595
+ var CURVE_SAMPLES = 12;
6596
+ /** Items listed per warning type before "and N more". */
6597
+ var MAX_LISTED = 8;
6598
+ function isConnector(el) {
6599
+ return el.type === "line" || el.type === "arrow";
6600
+ }
6601
+ /** Polyline the connector is drawn along (curves sampled). */
6602
+ function polylineOf(el, elements) {
6603
+ const route = resolveConnectorRoute(el, elements);
6604
+ if (el.type !== "line" || el.cx === void 0 || el.cy === void 0 || route.length !== 2) return route;
6605
+ const [[x1, y1], [x2, y2]] = route;
6606
+ const { cx, cy } = el;
6607
+ return Array.from({ length: 13 }, (_, i) => {
6608
+ const p = getQuadraticPoint(x1, y1, cx, cy, x2, y2, i / CURVE_SAMPLES);
6609
+ return [p.x, p.y];
6610
+ });
6611
+ }
6612
+ function segmentsOf(points) {
6613
+ return points.slice(1).map((p, i) => [points[i], p]);
6614
+ }
6615
+ /**
6616
+ * Part of a node a connector must not cross: the rectangle inscribed in an
6617
+ * ellipse or rhombus (so passing near a corner of the bounding box is not
6618
+ * reported), the connector box otherwise, inset by a couple of pixels so
6619
+ * a stroke running along the border doesn't count.
6620
+ */
6621
+ function coreRect(el) {
6622
+ const b = getConnectorBox(el);
6623
+ const scale = el.type === "ellipse" ? Math.SQRT1_2 : el.type === "rhombus" ? .5 : 1;
6624
+ const w = b.w * scale - 4;
6625
+ const h = b.h * scale - 4;
6626
+ return {
6627
+ x: b.x + (b.w - w) / 2,
6628
+ y: b.y + (b.h - h) / 2,
6629
+ w: Math.max(0, w),
6630
+ h: Math.max(0, h)
6631
+ };
6632
+ }
6633
+ /** Length of segment a-b inside `r` (Liang-Barsky clipping). */
6634
+ function clippedLength(a, b, r) {
6635
+ const dx = b[0] - a[0];
6636
+ const dy = b[1] - a[1];
6637
+ let t0 = 0;
6638
+ let t1 = 1;
6639
+ const edges = [
6640
+ [-dx, a[0] - r.x],
6641
+ [dx, r.x + r.w - a[0]],
6642
+ [-dy, a[1] - r.y],
6643
+ [dy, r.y + r.h - a[1]]
6644
+ ];
6645
+ for (const [p, q] of edges) {
6646
+ if (Math.abs(p) < 1e-9) {
6647
+ if (q < 0) return 0;
6648
+ continue;
6649
+ }
6650
+ const t = q / p;
6651
+ if (p < 0) t0 = Math.max(t0, t);
6652
+ else t1 = Math.min(t1, t);
6653
+ if (t0 > t1) return 0;
6654
+ }
6655
+ return (t1 - t0) * Math.hypot(dx, dy);
6656
+ }
6657
+ function overlaps(a, b) {
6658
+ const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
6659
+ const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
6660
+ return w >= MIN_OVERLAP && h >= MIN_OVERLAP;
6661
+ }
6662
+ function contains(outer, inner) {
6663
+ 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;
6664
+ }
6665
+ /**
6666
+ * Whether two segments cross away from their ends. Connectors that share a
6667
+ * node meet at its border, and an elbow's bends meet the next segment: both
6668
+ * are joins, not crossings. Collinear runs are left out too.
6669
+ */
6670
+ function segmentsCross(s, t) {
6671
+ const [[ax, ay], [bx, by]] = s;
6672
+ const [[cx, cy], [dx, dy]] = t;
6673
+ const rx = bx - ax;
6674
+ const ry = by - ay;
6675
+ const sx = dx - cx;
6676
+ const sy = dy - cy;
6677
+ const den = rx * sy - ry * sx;
6678
+ if (Math.abs(den) < 1e-9) return false;
6679
+ const u = ((cx - ax) * sy - (cy - ay) * sx) / den;
6680
+ const v = ((cx - ax) * ry - (cy - ay) * rx) / den;
6681
+ const lenS = Math.hypot(rx, ry);
6682
+ const lenT = Math.hypot(sx, sy);
6683
+ return u * lenS > END_SLACK && (1 - u) * lenS > END_SLACK && v * lenT > END_SLACK && (1 - v) * lenT > END_SLACK;
6684
+ }
6685
+ function findWarnings(diagram) {
6686
+ const elements = diagram.elements;
6687
+ const keys = diagram.nodeKeys();
6688
+ const nodes = elements.filter((el) => keys.has(el.id) && el.visible !== false);
6689
+ const boxes = new Map(nodes.map((el) => [el.id, getConnectorBox(el)]));
6690
+ 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));
6691
+ const solid = nodes.filter((el) => !containers.has(el.id));
6692
+ const cores = new Map(solid.map((el) => [el.id, coreRect(el)]));
6693
+ const edges = [];
6694
+ for (const el of elements) {
6695
+ if (!isConnector(el) || el.visible === false) continue;
6696
+ const from = el.startElementId ? keys.get(el.startElementId) : void 0;
6697
+ const to = el.endElementId ? keys.get(el.endElementId) : void 0;
6698
+ if (!from || !to) continue;
6699
+ edges.push({
6700
+ name: {
6701
+ id: edgeShortId(el),
6702
+ from,
6703
+ to
6704
+ },
6705
+ el,
6706
+ segments: segmentsOf(polylineOf(el, elements))
6707
+ });
6708
+ }
6709
+ const throughNodes = [];
6710
+ for (const edge of edges) for (const node of solid) {
6711
+ if (node.id === edge.el.startElementId || node.id === edge.el.endElementId) continue;
6712
+ const core = cores.get(node.id);
6713
+ if (edge.segments.reduce((sum, [a, b]) => sum + clippedLength(a, b, core), 0) >= MIN_INSIDE) throughNodes.push({
6714
+ edge: edge.name,
6715
+ node: keys.get(node.id)
6716
+ });
6717
+ }
6718
+ const labels = getConnectorLabelBoxes(elements);
6719
+ const labelRects = edges.flatMap((edge) => {
6720
+ const box = labels.get(edge.el.id);
6721
+ return box ? [{
6722
+ edge: edge.name,
6723
+ rect: {
6724
+ x: box.x - box.w / 2,
6725
+ y: box.y - box.h / 2,
6726
+ w: box.w,
6727
+ h: box.h
6728
+ }
6729
+ }] : [];
6730
+ });
6731
+ const labelOverlaps = [];
6732
+ labelRects.forEach((label, i) => {
6733
+ for (const node of solid) if (overlaps(label.rect, cores.get(node.id))) labelOverlaps.push({
6734
+ edge: label.edge,
6735
+ node: keys.get(node.id)
6736
+ });
6737
+ for (const other of labelRects.slice(i + 1)) if (overlaps(label.rect, other.rect)) labelOverlaps.push({
6738
+ edge: label.edge,
6739
+ label: other.edge
6740
+ });
6741
+ });
6742
+ const crossings = [];
6743
+ edges.forEach((a, i) => {
6744
+ for (const b of edges.slice(i + 1)) {
6745
+ let count = 0;
6746
+ for (const s of a.segments) for (const t of b.segments) if (segmentsCross(s, t)) count++;
6747
+ if (count > 0) crossings.push({
6748
+ a: a.name,
6749
+ b: b.name,
6750
+ count
6751
+ });
6752
+ }
6753
+ });
6754
+ const nodeOverlaps = [];
6755
+ nodes.forEach((a, i) => {
6756
+ const ba = boxes.get(a.id);
6757
+ for (const b of nodes.slice(i + 1)) {
6758
+ const bb = boxes.get(b.id);
6759
+ if (overlaps(ba, bb) && !contains(ba, bb) && !contains(bb, ba)) nodeOverlaps.push([keys.get(a.id), keys.get(b.id)]);
6760
+ }
6761
+ });
6762
+ return {
6763
+ throughNodes,
6764
+ labelOverlaps,
6765
+ crossings,
6766
+ nodeOverlaps
6767
+ };
6768
+ }
6769
+ function edgeText(edge) {
6770
+ return `${edge.from} -> ${edge.to} (id ${edge.id})`;
6771
+ }
6772
+ /** Up to MAX_LISTED items joined with "; ", then how many were left out. */
6773
+ function listed(items) {
6774
+ const shown = items.slice(0, MAX_LISTED).join("; ");
6775
+ const rest = items.length - MAX_LISTED;
6776
+ return rest > 0 ? `${shown}; and ${rest} more` : shown;
6777
+ }
6778
+ /**
6779
+ * Short text for the agent, one line per kind of problem with a hint, or
6780
+ * an empty string when the diagram is clear.
6781
+ */
6782
+ function formatWarnings(w) {
6783
+ const lines = [];
6784
+ if (w.throughNodes.length > 0) {
6785
+ const byEdge = /* @__PURE__ */ new Map();
6786
+ for (const { edge, node } of w.throughNodes) {
6787
+ const entry = byEdge.get(edge.id) ?? {
6788
+ edge,
6789
+ nodes: []
6790
+ };
6791
+ entry.nodes.push(node);
6792
+ byEdge.set(edge.id, entry);
6793
+ }
6794
+ 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.`);
6795
+ }
6796
+ 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.`);
6797
+ if (w.crossings.length > 0) {
6798
+ const total = w.crossings.reduce((sum, c) => sum + c.count, 0);
6799
+ 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).`);
6800
+ }
6801
+ 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).`);
6802
+ return lines.length > 0 ? `Warnings:\n${lines.join("\n")}` : "";
6803
+ }
6804
+ /** Warnings of the current diagram as text to append to a tool result. */
6805
+ function warningsSuffix(diagram) {
6806
+ const text = formatWarnings(findWarnings(diagram));
6807
+ return text ? `\n${text}` : "";
6808
+ }
6809
+ //#endregion
6488
6810
  //#region src/png.ts
6489
6811
  /** Longest side of a rendered PNG, so huge boards stay a sane payload. */
6490
6812
  var MAX_SIDE = 4096;
@@ -6508,6 +6830,35 @@ function svgToPng(svg, scale = 2) {
6508
6830
  }
6509
6831
  }).render().asPng();
6510
6832
  }
6833
+ /**
6834
+ * Result of diagram_export_png: the image unless `returnImage` is false
6835
+ * (an agent refreshing a preview file doesn't need it back), then what was
6836
+ * saved and the diagram's warnings.
6837
+ */
6838
+ async function exportPng(diagram, options) {
6839
+ const { path, background, returnImage = true } = options;
6840
+ if (!returnImage && !path) throw new Error("Nothing to do: give a path to save the PNG, or leave returnImage on.");
6841
+ await diagram.loadUsedIconPacks();
6842
+ const svg = sceneToSVG(diagram.elements, {
6843
+ canvasColor: "#080808",
6844
+ withBackground: (background ?? "dark") === "dark"
6845
+ });
6846
+ if (!svg) return [{
6847
+ type: "text",
6848
+ text: "The diagram is empty: nothing to export."
6849
+ }];
6850
+ const png = svgToPng(svg);
6851
+ if (path) await writeFileAtomic(path, png);
6852
+ const notes = [path ? `Saved PNG to ${path}.` : "", formatWarnings(findWarnings(diagram))].filter(Boolean);
6853
+ return [...returnImage ? [{
6854
+ type: "image",
6855
+ data: png.toString("base64"),
6856
+ mimeType: "image/png"
6857
+ }] : [], ...notes.map((text) => ({
6858
+ type: "text",
6859
+ text
6860
+ }))];
6861
+ }
6511
6862
  //#endregion
6512
6863
  //#region src/server.ts
6513
6864
  /**
@@ -6517,7 +6868,7 @@ function svgToPng(svg, scale = 2) {
6517
6868
  var SERVER_INSTRUCTIONS = `Markasso is a whiteboard for diagrams. Workflow:
6518
6869
  1. diagram_new (or diagram_open / live_join to work on an existing board).
6519
6870
  2. diagram_add_nodes with short keys, then diagram_connect by key.
6520
- 3. diagram_layout to arrange everything (don't compute coordinates yourself).
6871
+ 3. diagram_layout to arrange everything (don't compute coordinates yourself). When it lists Warnings, fix them (each comes with a hint).
6521
6872
  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
6873
  5. diagram_share for a link, or diagram_save / diagram_export_svg for files.
6523
6874
  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 +6982,12 @@ server.registerTool("diagram_open", {
6631
6982
  }));
6632
6983
  server.registerTool("diagram_read", {
6633
6984
  title: "Read diagram",
6634
- description: "Describe the current diagram: nodes (key, kind, label, position, size) and connections.",
6985
+ description: "Describe the current diagram: nodes (key, kind, label, position, size), connections and layout warnings.",
6635
6986
  inputSchema: {},
6636
6987
  annotations: { readOnlyHint: true }
6637
6988
  }, guarded(() => {
6638
6989
  const peers = live?.connected ? `\nPeople in the room: ${live.otherPeers.map((p) => p.name).join(", ") || "none"}` : "";
6639
- return `${describeDiagram(diagram)}${peers}`;
6990
+ return `${describeDiagram(diagram)}${peers}${warningsSuffix(diagram)}`;
6640
6991
  }));
6641
6992
  server.registerTool("diagram_add_nodes", {
6642
6993
  title: "Add nodes",
@@ -6720,7 +7071,7 @@ server.registerTool("diagram_update_edge", {
6720
7071
  }));
6721
7072
  server.registerTool("diagram_layout", {
6722
7073
  title: "Auto layout",
6723
- description: "Arrange nodes in layers following their connections (TB = top to bottom, LR = left to right). Use after adding nodes.",
7074
+ 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
7075
  inputSchema: {
6725
7076
  direction: z.enum(["TB", "LR"]).optional(),
6726
7077
  keys: z.array(z.string()).optional().describe("Only these nodes (default: all)")
@@ -6728,7 +7079,7 @@ server.registerTool("diagram_layout", {
6728
7079
  }, guarded(({ direction, keys }) => {
6729
7080
  const count = diagram.layout(direction ?? "TB", keys);
6730
7081
  if (count === 0) return "Nothing to lay out.";
6731
- return `Arranged ${count} nodes (${direction ?? "TB"}).${liveSuffix()}`;
7082
+ return `Arranged ${count} nodes (${direction ?? "TB"}).${warningsSuffix(diagram)}${liveSuffix()}`;
6732
7083
  }));
6733
7084
  server.registerTool("icons_search", {
6734
7085
  title: "Search icons",
@@ -6777,30 +7128,16 @@ server.registerTool("diagram_export_svg", {
6777
7128
  }));
6778
7129
  server.registerTool("diagram_export_png", {
6779
7130
  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.",
7131
+ 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
7132
  inputSchema: {
6782
7133
  path: z.string().min(1).optional().describe("Absolute path ending in .png (optional)"),
6783
- background: z.enum(["dark", "transparent"]).optional()
7134
+ background: z.enum(["dark", "transparent"]).optional(),
7135
+ returnImage: z.boolean().optional().describe("Return the image (default true). false with a path only writes the file and answers in text.")
6784
7136
  },
6785
7137
  annotations: { readOnlyHint: true }
6786
- }, async ({ path, background }) => {
7138
+ }, async (args) => {
6787
7139
  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
- }] : []] };
7140
+ return { content: await exportPng(diagram, args) };
6804
7141
  } catch (error) {
6805
7142
  return failure(error);
6806
7143
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markasso/mcp",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
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": {