@ikijs/mcp 0.4.0 → 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
@@ -31,8 +31,8 @@ Composes a directory of AI-generated part PNGs into canvas-aligned, role-named l
31
31
 
32
32
  - **`partsDir`** — directory of the source part PNGs (resolved against the server's working directory). Required sources: `face.png`, `eyewhite.png` (split into the sclera + lash layers), `iris.png`, `mouth.png`, `brow.png`, `hair_front.png`. Optional: `hair_back.png`, `body.png`, `mouth_open.png` — a parts dir without them still composes, minus those roles.
33
33
  - **`outDir`** — an existing directory (resolved against the working directory, confined to it exactly like `auto_rig_from_layers`'s `outputPath`; the tool never creates directories) to write the role layer PNGs and a flattened `preview.png` into. Reusing a directory across runs is intentional — a role this run skips (e.g. composing a head-only set that omits `body`) has its stale `<role>.png` from an earlier run deleted, so the directory always holds exactly this run's roles.
34
- - **`layout`** — optional per-role override merged over the built-in defaults, e.g. `{ "eye_L": { "cx": 660 } }`, so a character can be retuned by re-running compose rather than editing a script. Each of `cx`, `cy`, `w` is optional; `w` must be an integer in 1..1100 (the canvas width).
35
- - **Result** — on success the text is the written layer paths (one per line) followed by the same geometry report `measure_layers` returns; `structuredContent` is `{ ok: true, outDir, layers, skipped, preview, measure }`. Invalid input (a missing required part, an unknown `layout` role, an out-of-range `w`, a part that lands entirely off-canvas, a non-existent `outDir`) returns `{ ok: false, error }` with `INVALID: …` text.
34
+ - **`layout`** — optional per-role override merged over the built-in defaults, e.g. `{ "eye_L": { "cx": 660 } }`, so a character can be retuned by re-running compose rather than editing a script. Each of `cx`, `cy`, `w`, `h` is optional; `w` and `h` must be integers in 1..1100 (the canvas size). Omitting `h` keeps the part's own aspect ratio, which is what every role wants until one does not: a generated eyewhite often comes back flatter than its reference, and stretching a flat white lens costs nothing where regenerating it is billed and unreliable. Set `h` on a sclera and its lash together — they share one frame, and the blink fold tears if they diverge.
35
+ - **Result** — on success the text is the written layer paths (one per line) followed by the same geometry report `measure_layers` returns; `structuredContent` is `{ ok: true, outDir, layers, skipped, preview, measure }`. Invalid input (a missing required part, an unknown `layout` role, an out-of-range `w` or `h`, a part that lands entirely off-canvas, a non-existent `outDir`) returns `{ ok: false, error }` with `INVALID: …` text.
36
36
 
37
37
  ### `measure_layers`
38
38
 
@@ -498,6 +498,7 @@ var EYE_ASPECT_MIN = 0.5;
498
498
  var IRIS_OFFSET_MAX_X = 3;
499
499
  var IRIS_OFFSET_MAX_Y = 10;
500
500
  var EDGE_SOLID_MAX = 0.5;
501
+ var LASH_CENTRE_TOL_FRAC = 0.03;
501
502
  var EDGE_RUN_MIN_PX = 40;
502
503
  var FLAT_CUT_MAX_FRAC = 0.1;
503
504
  var FLAT_CUT_MIN_PX = 40;
@@ -602,15 +603,24 @@ async function measureDir(absDir) {
602
603
  const warnings = [];
603
604
  for (const [role, m] of Object.entries(layers)) {
604
605
  const edges = [
605
- ["top", m.edgeTop, m.w],
606
- ["left", m.edgeLeft, m.h],
607
- ["right", m.edgeRight, m.h]
606
+ ["top", m.edgeTop, m.w, m.marginTop],
607
+ ["left", m.edgeLeft, m.h, m.marginLeft],
608
+ ["right", m.edgeRight, m.h, m.marginRight]
608
609
  ];
609
- if (role !== "body") edges.push(["bottom", m.edgeBottom, m.w]);
610
- for (const [side, v, span] of edges) {
610
+ if (role !== "body")
611
+ edges.push(["bottom", m.edgeBottom, m.w, m.marginBottom]);
612
+ for (const [side, v, span, margin] of edges) {
611
613
  if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {
614
+ const remedy = margin === 0 ? (
615
+ // margin 0 is consistent with a clipped placement AND with art
616
+ // already cropped flush that happens to sit on the boundary, and
617
+ // the flattened layer cannot separate them — so name the free
618
+ // move rather than the cause. If moving it inward leaves the
619
+ // edge opaque, the drawing is the one at fault.
620
+ `it sits flush against the canvas ${side}, which a clipped placement and already-cropped art both produce. Move it inward first \u2014 retune layout.${role}.cx/cy/w, free \u2014 and remeasure; regenerate only if the edge is still opaque with margin to spare.`
621
+ ) : `its own drawing runs to the frame ${margin} px inside the canvas \u2014 regenerate that part with empty margin on that side. Billed.`;
612
622
  warnings.push(
613
- `${role}: ${pct(v)} of its ${side} edge is opaque \u2014 the art is cut off there, which shows as a straight seam once the head turns. Regenerate with empty margin on that side.`
623
+ `${role}: ${pct(v)} of its ${side} edge is opaque \u2014 the art is cut off there, which shows as a straight seam once the head turns. Cause: ${remedy}`
614
624
  );
615
625
  }
616
626
  }
@@ -631,7 +641,7 @@ async function measureDir(absDir) {
631
641
  const aspect = eye.h / eye.w;
632
642
  if (aspect < EYE_ASPECT_MIN) {
633
643
  warnings.push(
634
- `eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} \u2014 a round iris cannot sit inside it. Regenerate the eyewhite taller, not the iris smaller.`
644
+ `eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} \u2014 a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) \u2014 stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that distorts the lash.`
635
645
  );
636
646
  }
637
647
  if (iris) {
@@ -652,7 +662,7 @@ async function measureDir(absDir) {
652
662
  if (lash) {
653
663
  const dx = lash.bboxCx - eye.bboxCx;
654
664
  const dTop = lash.marginTop - eye.marginTop;
655
- if (Math.abs(dx) > 0.5 || Math.abs(dTop) > 0.5) {
665
+ if (Math.abs(dx) > eye.w * LASH_CENTRE_TOL_FRAC || Math.abs(dTop) > 0.5) {
656
666
  warnings.push(
657
667
  `lash_${side}: centre is ${dx.toFixed(1)} px and top edge ${dTop.toFixed(1)} px off eye_${side}. They are split from one source and MUST share cx/cy/w in layout, or the blink fold tears. Retune to match.`
658
668
  );
@@ -718,6 +728,13 @@ var IRIS_W = Math.round(EYE_W * 0.5625);
718
728
  var EYEWHITE_SRC = "eyewhite.png";
719
729
  var EYE_LASH_LUMA = 120;
720
730
  var LASH_KEEP_FRACTION = 0.5;
731
+ var NOSE_INK_TOL = 20;
732
+ var NOSE_INK_LOW = 8;
733
+ var NOSE_GROW = 2;
734
+ var NOSE_MIN_PIXELS = 12;
735
+ var NOSE_MAX_CUT_FRACTION = 0.25;
736
+ var NOSE_ROW_MIN_PIXELS = 8;
737
+ var NOSE_FILL_REACH = 8;
721
738
  var DEFAULT_LAYOUT = {
722
739
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
723
740
  // without them still composes (head-only character).
@@ -801,13 +818,15 @@ function resolveLayout(overrides) {
801
818
  }
802
819
  next[field] = value;
803
820
  }
804
- if (override.w !== void 0) {
805
- if (!Number.isInteger(override.w) || override.w < 1 || override.w > CANVAS) {
821
+ for (const field of ["w", "h"]) {
822
+ const value = override[field];
823
+ if (value === void 0) continue;
824
+ if (!Number.isInteger(value) || value < 1 || value > CANVAS) {
806
825
  throw new AutoRigInputError(
807
- `layout.${role}.w must be an integer in 1..${CANVAS}, got ${String(override.w)}`
826
+ `layout.${role}.${field} must be an integer in 1..${CANVAS}, got ${String(value)}`
808
827
  );
809
828
  }
810
- next.w = override.w;
829
+ next[field] = value;
811
830
  }
812
831
  resolved[role] = next;
813
832
  }
@@ -842,15 +861,19 @@ async function partBuffer(role, cfg, partsDir, inMemory) {
842
861
  if (!cfg.noTrim) img = img.trim({ threshold: 12 });
843
862
  if (cfg.mirror) img = img.flop();
844
863
  const trimmed = await img.png().toBuffer({ resolveWithObject: true });
845
- const scaledH = Math.round(
846
- trimmed.info.height * cfg.w / trimmed.info.width
847
- );
848
- if (scaledH > CANVAS) {
849
- throw new AutoRigInputError(
850
- `layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`
864
+ if (cfg.h === void 0) {
865
+ const scaledH = Math.round(
866
+ trimmed.info.height * cfg.w / trimmed.info.width
851
867
  );
868
+ if (scaledH > CANVAS) {
869
+ throw new AutoRigInputError(
870
+ `layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`
871
+ );
872
+ }
852
873
  }
853
- const resized = await sharp2(trimmed.data).resize({ width: cfg.w }).png().toBuffer({ resolveWithObject: true });
874
+ const resized = await sharp2(trimmed.data).resize(
875
+ cfg.h === void 0 ? { width: cfg.w } : { width: cfg.w, height: cfg.h, fit: "fill" }
876
+ ).png().toBuffer({ resolveWithObject: true });
854
877
  return {
855
878
  buf: resized.data,
856
879
  w: resized.info.width,
@@ -923,6 +946,164 @@ async function prepEyeSplit(partsDir) {
923
946
  lash: await cropToBuffer(lash, W, H, region)
924
947
  };
925
948
  }
949
+ function cutNose(rgba, box) {
950
+ const W = CANVAS;
951
+ const x0 = Math.max(0, box.x0);
952
+ const y0 = Math.max(0, box.y0);
953
+ const x1 = Math.min(W, box.x1);
954
+ const y1 = Math.min(W, box.y1);
955
+ if (x1 - x0 < 4 || y1 - y0 < 4) return null;
956
+ const bw = x1 - x0;
957
+ const bh = y1 - y0;
958
+ const at = (x, y) => (y * W + x) * 4;
959
+ const median = (v) => v.sort((a, b) => a - b)[v.length >> 1];
960
+ const all = [[], [], []];
961
+ const rows = [];
962
+ for (let y = y0; y < y1; y++) {
963
+ const row = [[], [], []];
964
+ for (let x = x0; x < x1; x++) {
965
+ const i = at(x, y);
966
+ if (rgba[i + 3] === 0) continue;
967
+ for (let c = 0; c < 3; c++) {
968
+ row[c].push(rgba[i + c]);
969
+ all[c].push(rgba[i + c]);
970
+ }
971
+ }
972
+ rows.push(row);
973
+ }
974
+ const opaqueCount = all[0].length;
975
+ if (opaqueCount === 0) return null;
976
+ const skin = all.map(median);
977
+ const skinRow = rows.map(
978
+ (row) => row[0].length < NOSE_ROW_MIN_PIXELS ? skin : row.map(median)
979
+ );
980
+ const distAt = (i, y) => {
981
+ const ref = skinRow[y - y0];
982
+ return Math.max(
983
+ Math.abs(rgba[i] - ref[0]),
984
+ Math.abs(rgba[i + 1] - ref[1]),
985
+ Math.abs(rgba[i + 2] - ref[2])
986
+ );
987
+ };
988
+ const dist = new Uint8Array(bw * bh);
989
+ const ink = new Uint8Array(bw * bh);
990
+ const queue = [];
991
+ let inkCount = 0;
992
+ for (let y = y0; y < y1; y++) {
993
+ for (let x = x0; x < x1; x++) {
994
+ const i = at(x, y);
995
+ if (rgba[i + 3] === 0) continue;
996
+ const d = distAt(i, y);
997
+ const k = (y - y0) * bw + (x - x0);
998
+ dist[k] = d;
999
+ if (d > NOSE_INK_TOL) {
1000
+ ink[k] = 1;
1001
+ queue.push(k);
1002
+ inkCount++;
1003
+ }
1004
+ }
1005
+ }
1006
+ if (inkCount < NOSE_MIN_PIXELS) return null;
1007
+ while (queue.length > 0) {
1008
+ const k = queue.pop();
1009
+ const kx = k % bw;
1010
+ const ky = (k - kx) / bw;
1011
+ for (let dy = -NOSE_GROW; dy <= NOSE_GROW; dy++) {
1012
+ for (let dx = -NOSE_GROW; dx <= NOSE_GROW; dx++) {
1013
+ const nx = kx + dx;
1014
+ const ny = ky + dy;
1015
+ if (nx < 0 || nx >= bw || ny < 0 || ny >= bh) continue;
1016
+ const n = ny * bw + nx;
1017
+ if (ink[n] === 0 && dist[n] > NOSE_INK_LOW) {
1018
+ ink[n] = 1;
1019
+ queue.push(n);
1020
+ }
1021
+ }
1022
+ }
1023
+ }
1024
+ const cut = new Uint8Array(bw * bh);
1025
+ for (let y = 0; y < bh; y++) {
1026
+ for (let x = 0; x < bw; x++) {
1027
+ if (ink[y * bw + x] === 0) continue;
1028
+ for (let dy = -NOSE_GROW; dy <= NOSE_GROW; dy++) {
1029
+ for (let dx = -NOSE_GROW; dx <= NOSE_GROW; dx++) {
1030
+ const yy = y + dy;
1031
+ const xx = x + dx;
1032
+ if (yy >= 0 && yy < bh && xx >= 0 && xx < bw) cut[yy * bw + xx] = 1;
1033
+ }
1034
+ }
1035
+ }
1036
+ }
1037
+ let cutCount = 0;
1038
+ for (let y = 0; y < bh; y++) {
1039
+ for (let x = 0; x < bw; x++) {
1040
+ if (cut[y * bw + x] === 0) continue;
1041
+ const a = rgba[at(x0 + x, y0 + y) + 3];
1042
+ if (a === 0) continue;
1043
+ if (a < 255) return null;
1044
+ cutCount++;
1045
+ }
1046
+ }
1047
+ if (cutCount > NOSE_MAX_CUT_FRACTION * opaqueCount) return null;
1048
+ const face = Buffer.from(rgba);
1049
+ const nose = Buffer.from(rgba);
1050
+ for (let i = 3; i < nose.length; i += 4) nose[i] = 0;
1051
+ let minX = W;
1052
+ let minY = W;
1053
+ let maxX = -1;
1054
+ let maxY = -1;
1055
+ for (let y = 0; y < bh; y++) {
1056
+ const cy = y0 + y;
1057
+ let x = 0;
1058
+ while (x < bw) {
1059
+ if (cut[y * bw + x] === 0) {
1060
+ x++;
1061
+ continue;
1062
+ }
1063
+ const start = x;
1064
+ while (x < bw && cut[y * bw + x] === 1) x++;
1065
+ const end = x;
1066
+ const skinAt = (bx) => {
1067
+ for (let step = 0; step < NOSE_FILL_REACH && bx >= 0 && bx < bw; step++) {
1068
+ const i = at(x0 + bx, cy);
1069
+ if (rgba[i + 3] > 0 && cut[y * bw + bx] === 0) {
1070
+ if (distAt(i, cy) <= NOSE_INK_TOL / 2) return i;
1071
+ }
1072
+ bx += bx < start ? -1 : 1;
1073
+ }
1074
+ return -1;
1075
+ };
1076
+ const l = skinAt(start - 1);
1077
+ const r = skinAt(end);
1078
+ for (let k = start; k < end; k++) {
1079
+ const cx = x0 + k;
1080
+ const i = at(cx, cy);
1081
+ if (rgba[i + 3] === 0) continue;
1082
+ const t = (k - start + 1) / (end - start + 1);
1083
+ for (let c = 0; c < 3; c++) {
1084
+ const rowSkin = skinRow[y];
1085
+ const lc = l >= 0 ? rgba[l + c] : r >= 0 ? rgba[r + c] : rowSkin[c];
1086
+ const rc = r >= 0 ? rgba[r + c] : l >= 0 ? rgba[l + c] : rowSkin[c];
1087
+ face[i + c] = Math.round(lc * (1 - t) + rc * t);
1088
+ }
1089
+ nose[i] = rgba[i];
1090
+ nose[i + 1] = rgba[i + 1];
1091
+ nose[i + 2] = rgba[i + 2];
1092
+ nose[i + 3] = rgba[i + 3];
1093
+ if (cx < minX) minX = cx;
1094
+ if (cx > maxX) maxX = cx;
1095
+ if (cy < minY) minY = cy;
1096
+ if (cy > maxY) maxY = cy;
1097
+ }
1098
+ }
1099
+ }
1100
+ if (maxX < 0) return null;
1101
+ return {
1102
+ face,
1103
+ nose,
1104
+ bbox: { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 }
1105
+ };
1106
+ }
926
1107
  async function composeLayersFromParts(input) {
927
1108
  try {
928
1109
  const outDir = resolveOutputDir(input.outDir);
@@ -941,6 +1122,7 @@ async function composeLayersFromParts(input) {
941
1122
  const layers = [];
942
1123
  const skipped = [];
943
1124
  const preview = [];
1125
+ let faceRaw;
944
1126
  for (const role of ORDER) {
945
1127
  const cfg = layout[role];
946
1128
  const part = await partBuffer(
@@ -955,9 +1137,15 @@ async function composeLayersFromParts(input) {
955
1137
  continue;
956
1138
  }
957
1139
  const { left, top } = placement(role, cfg, part.w, part.h);
958
- const layer = await blankCanvas().composite([{ input: part.buf, left, top }]).png().toBuffer();
1140
+ const composed = blankCanvas().composite([
1141
+ { input: part.buf, left, top }
1142
+ ]);
959
1143
  const outPath = path4.join(outDir, `${role}.png`);
960
- writeFileAtomic(outPath, layer);
1144
+ if (role === "face") {
1145
+ faceRaw = await composed.raw().toBuffer();
1146
+ } else {
1147
+ writeFileAtomic(outPath, await composed.png().toBuffer());
1148
+ }
961
1149
  layers.push({
962
1150
  role,
963
1151
  path: outPath,
@@ -968,6 +1156,48 @@ async function composeLayersFromParts(input) {
968
1156
  });
969
1157
  preview.push({ input: part.buf, left, top });
970
1158
  }
1159
+ const placed = (role) => layers.find((l) => l.role === role);
1160
+ const eyeL = placed("eye_L");
1161
+ const eyeR = placed("eye_R");
1162
+ const mouth = placed("mouth");
1163
+ const noseCut = cutNose(faceRaw, {
1164
+ x0: eyeR.left + eyeR.width,
1165
+ x1: eyeL.left,
1166
+ y0: Math.round(
1167
+ (eyeL.top + eyeL.height / 2 + eyeR.top + eyeR.height / 2) / 2
1168
+ ),
1169
+ y1: mouth.top - 2
1170
+ });
1171
+ const rawCanvas = {
1172
+ raw: { width: CANVAS, height: CANVAS, channels: 4 }
1173
+ };
1174
+ const facePath = path4.join(outDir, "face.png");
1175
+ const nosePath = path4.join(outDir, "nose.png");
1176
+ if (noseCut === null) {
1177
+ writeFileAtomic(
1178
+ facePath,
1179
+ await sharp2(faceRaw, rawCanvas).png().toBuffer()
1180
+ );
1181
+ fs3.rmSync(nosePath, { force: true });
1182
+ skipped.push("nose");
1183
+ } else {
1184
+ writeFileAtomic(
1185
+ facePath,
1186
+ await sharp2(noseCut.face, rawCanvas).png().toBuffer()
1187
+ );
1188
+ writeFileAtomic(
1189
+ nosePath,
1190
+ await sharp2(noseCut.nose, rawCanvas).png().toBuffer()
1191
+ );
1192
+ layers.splice(layers.findIndex((l) => l.role === "face") + 1, 0, {
1193
+ role: "nose",
1194
+ path: nosePath,
1195
+ width: noseCut.bbox.w,
1196
+ height: noseCut.bbox.h,
1197
+ left: noseCut.bbox.x,
1198
+ top: noseCut.bbox.y
1199
+ });
1200
+ }
971
1201
  const previewPng = await sharp2({
972
1202
  create: {
973
1203
  width: CANVAS,
@@ -997,7 +1227,7 @@ async function composeLayersFromParts(input) {
997
1227
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
998
1228
  import { z } from "zod";
999
1229
  function createIkiMcpServer() {
1000
- const server = new McpServer({ name: "iki", version: "0.4.0" });
1230
+ const server = new McpServer({ name: "iki", version: "0.6.0" });
1001
1231
  server.registerTool(
1002
1232
  "validate_iki",
1003
1233
  {
@@ -1098,7 +1328,7 @@ function createIkiMcpServer() {
1098
1328
  server.registerTool(
1099
1329
  "compose_layers_from_parts",
1100
1330
  {
1101
- description: "Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, mouth, eyewhite, iris, brow, hair_front are required; hair_back, body, mouth_open are optional.",
1331
+ description: "Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, the nose cut out of the face so the rig can lead the turn with it, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, mouth, eyewhite, iris, brow, hair_front are required; hair_back, body, mouth_open are optional; nose.png is cut from face.png when it has a drawn nose (reported under `skipped` otherwise).",
1102
1332
  inputSchema: {
1103
1333
  partsDir: z.string().describe(
1104
1334
  "Directory of the source part PNGs (resolved against cwd)."
@@ -1108,9 +1338,14 @@ function createIkiMcpServer() {
1108
1338
  ),
1109
1339
  layout: z.record(
1110
1340
  z.string(),
1111
- z.object({ cx: z.number(), cy: z.number(), w: z.number() }).partial()
1341
+ z.object({
1342
+ cx: z.number(),
1343
+ cy: z.number(),
1344
+ w: z.number(),
1345
+ h: z.number()
1346
+ }).partial()
1112
1347
  ).optional().describe(
1113
- "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }`; `w` is 1..1100."
1348
+ "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch (set it on a sclera and its lash together, or the blink fold tears)."
1114
1349
  )
1115
1350
  }
1116
1351
  },
@@ -1173,4 +1408,4 @@ export {
1173
1408
  composeLayersFromParts,
1174
1409
  createIkiMcpServer
1175
1410
  };
1176
- //# sourceMappingURL=chunk-F5RUDS6T.mjs.map
1411
+ //# sourceMappingURL=chunk-JTK6HWKT.mjs.map