@ikijs/mcp 0.3.1 → 0.4.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.
@@ -0,0 +1,1176 @@
1
+ // src/tools.ts
2
+ import path2 from "path";
3
+ import {
4
+ parseIkiModel,
5
+ loadIkiModel,
6
+ IkiFormatError,
7
+ StandardParameter
8
+ } from "@ikijs/format";
9
+ import {
10
+ EditorDocument,
11
+ packAtlas,
12
+ uvRectFor,
13
+ generateIkiFromLayerSet,
14
+ parseLayerRoles
15
+ } from "@ikijs/editor";
16
+
17
+ // src/node-images.ts
18
+ import sharp from "sharp";
19
+ import { detectAlphaBbox as scanAlphaBbox } from "@ikijs/editor";
20
+
21
+ // src/limits.ts
22
+ import fs from "fs";
23
+ import path from "path";
24
+ var MAX_LAYERS = 64;
25
+ var MAX_LAYER_DIM = 4096;
26
+ var MAX_CANVAS_DIM = 4096;
27
+ var MAX_ATLAS_AREA = 4096 * 4096;
28
+ var MAX_INPUT_PIXELS = 4096 * 4096;
29
+ var MAX_TOTAL_PIXELS = 64 * 1024 * 1024;
30
+ var MAX_OUTPUT_BYTES = 5 * 1024 * 1024;
31
+ var AutoRigInputError = class extends Error {
32
+ constructor(message) {
33
+ super(message);
34
+ this.name = "AutoRigInputError";
35
+ }
36
+ };
37
+ function rejectEmptyOrUrl(inputPath, noun, kind) {
38
+ if (typeof inputPath !== "string" || inputPath.trim() === "") {
39
+ throw new AutoRigInputError(`${noun} is empty`);
40
+ }
41
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(inputPath)) {
42
+ throw new AutoRigInputError(
43
+ `${noun} must be a ${kind}, not a URL: ${inputPath}`
44
+ );
45
+ }
46
+ }
47
+ function resolveInputPath(inputPath) {
48
+ rejectEmptyOrUrl(inputPath, "layer path", "file path");
49
+ const resolved = path.resolve(process.cwd(), inputPath);
50
+ let stat;
51
+ try {
52
+ stat = fs.statSync(resolved);
53
+ } catch {
54
+ throw new AutoRigInputError(`layer file not found: ${resolved}`);
55
+ }
56
+ if (stat.isDirectory()) {
57
+ throw new AutoRigInputError(
58
+ `layer path is a directory, not a file: ${resolved}`
59
+ );
60
+ }
61
+ return resolved;
62
+ }
63
+ function resolveInputDir(dirPath) {
64
+ rejectEmptyOrUrl(dirPath, "layers dir", "directory path");
65
+ const resolved = path.resolve(process.cwd(), dirPath);
66
+ let stat;
67
+ try {
68
+ stat = fs.statSync(resolved);
69
+ } catch {
70
+ throw new AutoRigInputError(`layers dir not found: ${resolved}`);
71
+ }
72
+ if (!stat.isDirectory()) {
73
+ throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);
74
+ }
75
+ return resolved;
76
+ }
77
+ function confineToWorkingDirectory(root, dir, label, original) {
78
+ const realRoot = fs.realpathSync(root);
79
+ const realDir = fs.realpathSync(dir);
80
+ if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {
81
+ throw new AutoRigInputError(
82
+ `${label} escapes the working directory: ${original}`
83
+ );
84
+ }
85
+ return realDir;
86
+ }
87
+ function resolveOutputPath(outputPath) {
88
+ if (typeof outputPath !== "string" || outputPath.trim() === "") {
89
+ throw new AutoRigInputError("output path is empty");
90
+ }
91
+ if (!outputPath.toLowerCase().endsWith(".iki")) {
92
+ throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);
93
+ }
94
+ const root = process.cwd();
95
+ const resolved = path.resolve(root, outputPath);
96
+ const dir = path.dirname(resolved);
97
+ let stat;
98
+ try {
99
+ stat = fs.statSync(dir);
100
+ } catch {
101
+ throw new AutoRigInputError(`output directory does not exist: ${dir}`);
102
+ }
103
+ if (!stat.isDirectory()) {
104
+ throw new AutoRigInputError(`output parent is not a directory: ${dir}`);
105
+ }
106
+ const realDir = confineToWorkingDirectory(
107
+ root,
108
+ dir,
109
+ "output path",
110
+ outputPath
111
+ );
112
+ return path.join(realDir, path.basename(resolved));
113
+ }
114
+ function resolveOutputDir(dirPath) {
115
+ if (typeof dirPath !== "string" || dirPath.trim() === "") {
116
+ throw new AutoRigInputError("output dir is empty");
117
+ }
118
+ const root = process.cwd();
119
+ const resolved = path.resolve(root, dirPath);
120
+ let stat;
121
+ try {
122
+ stat = fs.statSync(resolved);
123
+ } catch {
124
+ throw new AutoRigInputError(`output dir not found: ${resolved}`);
125
+ }
126
+ if (!stat.isDirectory()) {
127
+ throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);
128
+ }
129
+ return confineToWorkingDirectory(root, resolved, "output dir", dirPath);
130
+ }
131
+ function writeFileAtomic(outPath, data) {
132
+ const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;
133
+ try {
134
+ fs.writeFileSync(tmp, data);
135
+ try {
136
+ fs.renameSync(tmp, outPath);
137
+ } catch (e) {
138
+ try {
139
+ fs.rmSync(tmp, { force: true });
140
+ } catch {
141
+ }
142
+ throw e;
143
+ }
144
+ } catch (e) {
145
+ throw new AutoRigInputError(
146
+ `write: ${e instanceof Error ? e.message : String(e)}`
147
+ );
148
+ }
149
+ }
150
+
151
+ // src/node-images.ts
152
+ async function decodePng(filePath) {
153
+ try {
154
+ const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });
155
+ const metadata = await pipeline.metadata();
156
+ if (metadata.format !== "png") {
157
+ throw new AutoRigInputError(
158
+ `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
159
+ );
160
+ }
161
+ const { data, info } = await pipeline.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
162
+ return {
163
+ width: info.width,
164
+ height: info.height,
165
+ rgba: data,
166
+ hasAlpha: metadata.hasAlpha ?? false
167
+ };
168
+ } catch (e) {
169
+ if (e instanceof AutoRigInputError) throw e;
170
+ const msg = e instanceof Error ? e.message : String(e);
171
+ throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);
172
+ }
173
+ }
174
+ function detectAlphaBbox(rgba, width, height) {
175
+ const bbox = scanAlphaBbox(rgba, width, height);
176
+ if (bbox === null) {
177
+ throw new AutoRigInputError("layer is empty after alpha threshold");
178
+ }
179
+ return bbox;
180
+ }
181
+ function cropToBuffer(rgba, width, height, bbox) {
182
+ return sharp(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
183
+ }
184
+ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
185
+ const byId = /* @__PURE__ */ new Map();
186
+ for (const crop of crops) byId.set(crop.id, crop);
187
+ const pad = layout.padding;
188
+ const composites = await Promise.all(
189
+ layout.placements.map(async (placement2) => {
190
+ const crop = byId.get(placement2.id);
191
+ if (crop === void 0) {
192
+ throw new AutoRigInputError(
193
+ `no crop for atlas placement "${placement2.id}"`
194
+ );
195
+ }
196
+ const input = pad > 0 ? await sharp(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
197
+ return { input, left: placement2.x, top: placement2.y };
198
+ })
199
+ );
200
+ const page = await sharp({
201
+ create: {
202
+ width: layout.pageWidth,
203
+ height: layout.pageHeight,
204
+ channels: 4,
205
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
206
+ }
207
+ }).composite(composites).png(
208
+ quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
209
+ ).toBuffer();
210
+ return `data:image/png;base64,${page.toString("base64")}`;
211
+ }
212
+
213
+ // src/tools.ts
214
+ function coerceModel(model) {
215
+ try {
216
+ const parsed = typeof model === "string" ? loadIkiModel(model) : parseIkiModel(model);
217
+ return { ok: true, model: parsed };
218
+ } catch (e) {
219
+ if (e instanceof IkiFormatError) return { ok: false, error: e.message };
220
+ throw e;
221
+ }
222
+ }
223
+ function validateIki(model) {
224
+ const result = coerceModel(model);
225
+ if (!result.ok) return { ok: false, error: result.error };
226
+ return { ok: true };
227
+ }
228
+ function describeIki(model) {
229
+ const result = coerceModel(model);
230
+ if (!result.ok) return { ok: false, error: result.error };
231
+ const m = result.model;
232
+ const parameters = m.parameters.map((p) => ({
233
+ id: p.id,
234
+ min: p.min,
235
+ max: p.max,
236
+ default: p.default
237
+ }));
238
+ const parts = m.parts.map((p) => {
239
+ const entry = {
240
+ id: p.id,
241
+ order: p.order
242
+ };
243
+ if (p.deformer !== void 0) entry.deformer = p.deformer;
244
+ return entry;
245
+ });
246
+ const deformers = (m.deformers ?? []).map(
247
+ (d) => {
248
+ const kind = d.kind === "warp" ? "warp" : "matrix";
249
+ const entry = { id: d.id, kind };
250
+ if (d.parent !== void 0) entry.parent = d.parent;
251
+ if (d.kind === "warp") {
252
+ if (d.warp2d !== void 0) {
253
+ entry.warp = {
254
+ mode: "2d",
255
+ parameterX: d.warp2d.parameter,
256
+ parameterY: d.warp2d.parameterY,
257
+ gridX: d.grid.cols,
258
+ gridY: d.grid.rows
259
+ };
260
+ } else if (d.warps !== void 0 && d.warps.length > 0) {
261
+ entry.warp = {
262
+ mode: "1d",
263
+ parameters: d.warps.map((w) => w.parameter)
264
+ };
265
+ }
266
+ }
267
+ return entry;
268
+ }
269
+ );
270
+ const summary = {
271
+ name: m.name,
272
+ canvas: { width: m.canvas.width, height: m.canvas.height },
273
+ parameters,
274
+ parts,
275
+ deformers
276
+ };
277
+ return { ok: true, summary };
278
+ }
279
+ var STANDARD_PARAMETER_INFO = [
280
+ {
281
+ id: StandardParameter.MouthOpen,
282
+ description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
283
+ },
284
+ {
285
+ id: StandardParameter.MouthForm,
286
+ description: "Mouth form / smile (-1 .. 1)."
287
+ },
288
+ {
289
+ id: StandardParameter.EyeOpenLeft,
290
+ description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
291
+ },
292
+ {
293
+ id: StandardParameter.EyeOpenRight,
294
+ description: "Right eye open (0 closed .. 1 open)."
295
+ },
296
+ {
297
+ id: StandardParameter.EyeballX,
298
+ description: "Eyeball gaze, horizontal (-1 .. 1)."
299
+ },
300
+ {
301
+ id: StandardParameter.EyeballY,
302
+ description: "Eyeball gaze, vertical (-1 .. 1)."
303
+ },
304
+ {
305
+ id: StandardParameter.AngleX,
306
+ description: "Head angle, horizontal degrees."
307
+ },
308
+ {
309
+ id: StandardParameter.AngleY,
310
+ description: "Head angle, vertical degrees."
311
+ },
312
+ {
313
+ id: StandardParameter.AngleZ,
314
+ description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
315
+ },
316
+ {
317
+ id: StandardParameter.Breath,
318
+ description: "Idle breath (0 .. 1), cycled by the host."
319
+ },
320
+ {
321
+ id: StandardParameter.BrowLeftY,
322
+ description: "Left brow raise/lower (-1 .. 1)."
323
+ },
324
+ {
325
+ id: StandardParameter.BrowRightY,
326
+ description: "Right brow raise/lower (-1 .. 1)."
327
+ },
328
+ {
329
+ id: StandardParameter.BrowLeftAngle,
330
+ description: "Left brow tilt/angle (-1 .. 1)."
331
+ },
332
+ {
333
+ id: StandardParameter.BrowRightAngle,
334
+ description: "Right brow tilt/angle (-1 .. 1)."
335
+ },
336
+ {
337
+ id: StandardParameter.HairSwayX,
338
+ description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
339
+ },
340
+ {
341
+ id: StandardParameter.HairSwayZ,
342
+ description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
343
+ }
344
+ ];
345
+ function listStandardParameters() {
346
+ return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
347
+ }
348
+ function expectInput(label, fn) {
349
+ try {
350
+ return fn();
351
+ } catch (e) {
352
+ throw new AutoRigInputError(
353
+ `${label}: ${e instanceof Error ? e.message : String(e)}`
354
+ );
355
+ }
356
+ }
357
+ async function autoRigFromLayers(input) {
358
+ try {
359
+ const layers = input.layers;
360
+ if (!Array.isArray(layers) || layers.length === 0) {
361
+ throw new AutoRigInputError("layers must be a non-empty array");
362
+ }
363
+ if (layers.length > MAX_LAYERS) {
364
+ throw new AutoRigInputError(
365
+ `too many layers: ${layers.length} > ${MAX_LAYERS}`
366
+ );
367
+ }
368
+ const outPath = resolveOutputPath(
369
+ input.outputPath ?? "auto-rigged-model.iki"
370
+ );
371
+ const quantizeColors = input.quantizeColors;
372
+ if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
373
+ throw new AutoRigInputError(
374
+ `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
375
+ );
376
+ }
377
+ const resolvedLayers = layers.map((layer) => {
378
+ const resolved = resolveInputPath(layer.path);
379
+ return { resolved, fileName: layer.fileName ?? path2.basename(resolved) };
380
+ });
381
+ const rolePairs = expectInput(
382
+ "role parsing",
383
+ () => parseLayerRoles(resolvedLayers.map((r) => r.fileName))
384
+ );
385
+ const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
386
+ let canvasW = 0;
387
+ let canvasH = 0;
388
+ let totalPixels = 0;
389
+ const layerInputs = [];
390
+ const crops = [];
391
+ for (let i = 0; i < resolvedLayers.length; i++) {
392
+ const { resolved, fileName } = resolvedLayers[i];
393
+ const png = await decodePng(resolved);
394
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
395
+ throw new AutoRigInputError(
396
+ `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
397
+ );
398
+ }
399
+ totalPixels += png.width * png.height;
400
+ if (totalPixels > MAX_TOTAL_PIXELS) {
401
+ throw new AutoRigInputError(
402
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
403
+ );
404
+ }
405
+ if (i === 0) {
406
+ canvasW = png.width;
407
+ canvasH = png.height;
408
+ if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
409
+ throw new AutoRigInputError(
410
+ `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
411
+ );
412
+ }
413
+ } else if (png.width !== canvasW || png.height !== canvasH) {
414
+ throw new AutoRigInputError(
415
+ `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
416
+ );
417
+ }
418
+ const role = roleByFileName.get(fileName);
419
+ if (role === void 0) {
420
+ throw new AutoRigInputError(`no role resolved for "${fileName}"`);
421
+ }
422
+ let bbox;
423
+ try {
424
+ bbox = detectAlphaBbox(png.rgba, png.width, png.height);
425
+ } catch (e) {
426
+ const msg = e instanceof Error ? e.message : String(e);
427
+ throw new AutoRigInputError(
428
+ `role "${role}" file "${fileName}": ${msg}`
429
+ );
430
+ }
431
+ const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
432
+ layerInputs.push({
433
+ role,
434
+ fileName,
435
+ canvasW,
436
+ canvasH,
437
+ bbox,
438
+ cropW: bbox.w,
439
+ cropH: bbox.h
440
+ });
441
+ crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
442
+ }
443
+ const model = generateIkiFromLayerSet(layerInputs, {
444
+ width: canvasW,
445
+ height: canvasH
446
+ });
447
+ const doc = new EditorDocument(model);
448
+ const layout = packAtlas(
449
+ crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
450
+ );
451
+ if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
452
+ throw new AutoRigInputError(
453
+ `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
454
+ );
455
+ }
456
+ const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
457
+ if (dataUri.length > MAX_OUTPUT_BYTES) {
458
+ throw new AutoRigInputError(
459
+ `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`
460
+ );
461
+ }
462
+ const partTextureAssignments = crops.map((crop) => {
463
+ const placement2 = layout.placements.find((p) => p.id === crop.id);
464
+ if (placement2 === void 0) {
465
+ throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
466
+ }
467
+ return {
468
+ partId: crop.id,
469
+ uv: uvRectFor(placement2, {
470
+ width: layout.pageWidth,
471
+ height: layout.pageHeight
472
+ })
473
+ };
474
+ });
475
+ doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });
476
+ const finalModel = parseIkiModel(doc.getModel());
477
+ writeFileAtomic(outPath, JSON.stringify(finalModel));
478
+ return {
479
+ ok: true,
480
+ path: outPath,
481
+ canvas: { width: canvasW, height: canvasH },
482
+ partCount: finalModel.parts.length,
483
+ atlasBytes: dataUri.length
484
+ };
485
+ } catch (err) {
486
+ if (err instanceof AutoRigInputError)
487
+ return { ok: false, error: err.message };
488
+ throw err;
489
+ }
490
+ }
491
+
492
+ // src/measure.ts
493
+ import fs2 from "fs";
494
+ import path3 from "path";
495
+ var IRIS_RATIO_MIN = 0.45;
496
+ var IRIS_RATIO_MAX = 0.72;
497
+ var EYE_ASPECT_MIN = 0.5;
498
+ var IRIS_OFFSET_MAX_X = 3;
499
+ var IRIS_OFFSET_MAX_Y = 10;
500
+ var EDGE_SOLID_MAX = 0.5;
501
+ var EDGE_RUN_MIN_PX = 40;
502
+ var FLAT_CUT_MAX_FRAC = 0.1;
503
+ var FLAT_CUT_MIN_PX = 40;
504
+ var FLAT_CUT_ALPHA_ABOVE = 120;
505
+ var FLAT_CUT_ALPHA_BELOW = 140;
506
+ async function layerStats(filePath) {
507
+ const { width: W, height: H, rgba } = await decodePng(filePath);
508
+ const alpha = (x, y) => rgba[(y * W + x) * 4 + 3];
509
+ let minX = W;
510
+ let minY = H;
511
+ let maxX = -1;
512
+ let maxY = -1;
513
+ let sumX = 0;
514
+ let sumY = 0;
515
+ let n = 0;
516
+ for (let y = 0; y < H; y++) {
517
+ for (let x = 0; x < W; x++) {
518
+ if (alpha(x, y) > 8) {
519
+ if (x < minX) minX = x;
520
+ if (x > maxX) maxX = x;
521
+ if (y < minY) minY = y;
522
+ if (y > maxY) maxY = y;
523
+ sumX += x;
524
+ sumY += y;
525
+ n++;
526
+ }
527
+ }
528
+ }
529
+ if (maxX < 0) return null;
530
+ const edge = (pts) => pts.filter((v) => v > 200).length / pts.length;
531
+ const top = [];
532
+ const bottom = [];
533
+ const left = [];
534
+ const right = [];
535
+ for (let x = minX; x <= maxX; x++) {
536
+ top.push(alpha(x, minY));
537
+ bottom.push(alpha(x, maxY));
538
+ }
539
+ for (let y = minY; y <= maxY; y++) {
540
+ left.push(alpha(minX, y));
541
+ right.push(alpha(maxX, y));
542
+ }
543
+ let flatCutRun = 0;
544
+ let flatCutY = -1;
545
+ for (let y = minY + 1; y <= maxY; y++) {
546
+ let run = 0;
547
+ for (let x = minX; x <= maxX; x++) {
548
+ if (alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE && alpha(x, y) > FLAT_CUT_ALPHA_BELOW) {
549
+ run++;
550
+ if (run > flatCutRun) {
551
+ flatCutRun = run;
552
+ flatCutY = y;
553
+ }
554
+ } else {
555
+ run = 0;
556
+ }
557
+ }
558
+ }
559
+ return {
560
+ w: maxX - minX + 1,
561
+ h: maxY - minY + 1,
562
+ flatCutRun,
563
+ flatCutY,
564
+ bboxCx: (minX + maxX) / 2,
565
+ bboxCy: (minY + maxY) / 2,
566
+ massCx: sumX / n,
567
+ massCy: sumY / n,
568
+ marginTop: minY,
569
+ marginBottom: H - 1 - maxY,
570
+ marginLeft: minX,
571
+ marginRight: W - 1 - maxX,
572
+ edgeTop: edge(top),
573
+ edgeBottom: edge(bottom),
574
+ edgeLeft: edge(left),
575
+ edgeRight: edge(right),
576
+ canvasW: W,
577
+ canvasH: H
578
+ };
579
+ }
580
+ var pct = (v) => `${(v * 100).toFixed(0)}%`;
581
+ async function measureDir(absDir) {
582
+ const files = fs2.readdirSync(absDir).filter((f) => f.endsWith(".png") && f !== "preview.png").sort();
583
+ if (files.length === 0) {
584
+ throw new AutoRigInputError(`no role layers in ${absDir}`);
585
+ }
586
+ if (files.length > MAX_LAYERS) {
587
+ throw new AutoRigInputError(
588
+ `too many layers in ${absDir}: ${files.length} > ${MAX_LAYERS}`
589
+ );
590
+ }
591
+ const layers = {};
592
+ const empty = [];
593
+ for (const f of files) {
594
+ const role = path3.basename(f, ".png");
595
+ const m = await layerStats(path3.join(absDir, f));
596
+ if (!m) {
597
+ empty.push(role);
598
+ continue;
599
+ }
600
+ layers[role] = m;
601
+ }
602
+ const warnings = [];
603
+ for (const [role, m] of Object.entries(layers)) {
604
+ const edges = [
605
+ ["top", m.edgeTop, m.w],
606
+ ["left", m.edgeLeft, m.h],
607
+ ["right", m.edgeRight, m.h]
608
+ ];
609
+ if (role !== "body") edges.push(["bottom", m.edgeBottom, m.w]);
610
+ for (const [side, v, span] of edges) {
611
+ if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {
612
+ 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.`
614
+ );
615
+ }
616
+ }
617
+ }
618
+ for (const [role, m] of Object.entries(layers)) {
619
+ if (role === "body") continue;
620
+ if (m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w && m.flatCutRun >= FLAT_CUT_MIN_PX) {
621
+ warnings.push(
622
+ `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} (${pct(m.flatCutRun / m.w)} of its width) \u2014 the source art is cut through there. It hides while the head faces front and opens into a seam on turn. Regenerate this part with the whole subject inside the frame.`
623
+ );
624
+ }
625
+ }
626
+ for (const side of ["L", "R"]) {
627
+ const eye = layers[`eye_${side}`];
628
+ const iris = layers[`iris_${side}`];
629
+ const lash = layers[`lash_${side}`];
630
+ if (!eye) continue;
631
+ const aspect = eye.h / eye.w;
632
+ if (aspect < EYE_ASPECT_MIN) {
633
+ 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.`
635
+ );
636
+ }
637
+ if (iris) {
638
+ const ratio = iris.w / eye.w;
639
+ if (ratio < IRIS_RATIO_MIN || ratio > IRIS_RATIO_MAX) {
640
+ warnings.push(
641
+ `iris_${side}: width is ${pct(ratio)} of the sclera (target ${IRIS_RATIO_MIN}-${IRIS_RATIO_MAX}) \u2014 retune layout.iris_${side}.w (keep it a fraction of the eye width), no regeneration needed.`
642
+ );
643
+ }
644
+ const dx = iris.bboxCx - eye.massCx;
645
+ const dy = iris.bboxCy - eye.massCy;
646
+ if (Math.abs(dx) > IRIS_OFFSET_MAX_X || Math.abs(dy) > IRIS_OFFSET_MAX_Y) {
647
+ warnings.push(
648
+ `iris_${side}: sits (${dx.toFixed(1)}, ${dy.toFixed(1)}) px from the white's centre of mass \u2014 retune layout.iris_${side}.cx/cy. The sclera's bbox centre is NOT its visual centre when the lash flick stretches the box.`
649
+ );
650
+ }
651
+ }
652
+ if (lash) {
653
+ const dx = lash.bboxCx - eye.bboxCx;
654
+ const dTop = lash.marginTop - eye.marginTop;
655
+ if (Math.abs(dx) > 0.5 || Math.abs(dTop) > 0.5) {
656
+ warnings.push(
657
+ `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
+ );
659
+ }
660
+ }
661
+ }
662
+ for (const [role, why] of [
663
+ ["body", "without it the character reads as a floating head on head-turn"],
664
+ ["hair_back", "without it the silhouette is flat behind the face"]
665
+ ]) {
666
+ if (layers[role] === void 0) warnings.push(`${role}: missing \u2014 ${why}.`);
667
+ }
668
+ return { layers, empty, warnings };
669
+ }
670
+ async function measureLayers(input) {
671
+ try {
672
+ const layersDir = resolveInputDir(input.layersDir);
673
+ const report = await measureDir(layersDir);
674
+ return {
675
+ ok: true,
676
+ layersDir,
677
+ ...report,
678
+ passed: report.warnings.length === 0
679
+ };
680
+ } catch (err) {
681
+ if (err instanceof AutoRigInputError)
682
+ return { ok: false, error: err.message };
683
+ throw err;
684
+ }
685
+ }
686
+ function formatMeasureReport(result) {
687
+ const lines = [
688
+ `# layers (${result.layersDir})`,
689
+ "",
690
+ "role size bbox-centre mass-centre margins t/b/l/r"
691
+ ];
692
+ for (const role of [...Object.keys(result.layers), ...result.empty].sort()) {
693
+ const m = result.layers[role];
694
+ if (m === void 0) {
695
+ lines.push(`${role.padEnd(13)} EMPTY (fully transparent)`);
696
+ continue;
697
+ }
698
+ lines.push(
699
+ `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`
700
+ );
701
+ }
702
+ lines.push("", "# checks", "");
703
+ if (result.warnings.length === 0) {
704
+ lines.push("all geometry checks passed");
705
+ } else {
706
+ for (const w of result.warnings) lines.push(`- ${w}`);
707
+ }
708
+ return lines.join("\n");
709
+ }
710
+
711
+ // src/compose.ts
712
+ import fs3 from "fs";
713
+ import path4 from "path";
714
+ import sharp2 from "sharp";
715
+ var CANVAS = 1100;
716
+ var EYE_W = 128;
717
+ var IRIS_W = Math.round(EYE_W * 0.5625);
718
+ var EYEWHITE_SRC = "eyewhite.png";
719
+ var EYE_LASH_LUMA = 120;
720
+ var LASH_KEEP_FRACTION = 0.5;
721
+ var DEFAULT_LAYOUT = {
722
+ // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
723
+ // without them still composes (head-only character).
724
+ hair_back: { src: "hair_back.png", cx: 550, cy: 523, w: 800, optional: true },
725
+ // The torso, cut off by the canvas bottom. It rides its own `bodyDeformer`: a
726
+ // light share of the head turn and half its breath bob, so the character is
727
+ // not a floating head.
728
+ body: { src: "body.png", cx: 550, cy: 1017, w: 840, optional: true },
729
+ face: { src: "face.png", cx: 550, cy: 475, w: 400 },
730
+ mouth: { src: "mouth.png", cx: 550, cy: 619, w: 68 },
731
+ // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the
732
+ // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;
733
+ // its top edge (not center) lines up with the closed mouth's top edge since
734
+ // the mouth opens downward from a fixed upper lip — hence the +2 cy nudge
735
+ // rather than sharing cy outright. Optional: composes fine without it.
736
+ mouth_open: {
737
+ src: "mouth_open.png",
738
+ cx: 550,
739
+ cy: 621,
740
+ w: 68,
741
+ optional: true
742
+ },
743
+ // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so
744
+ // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE
745
+ // the sclera center, so on blink it folds DOWN over the eye like the sample
746
+ // model instead of the whole eye shrinking in place. Same cx/cy/w.
747
+ eye_L: { src: "eyewhite_sclera.png", cx: 657, cy: 475, w: EYE_W, mirror: true, noTrim: true },
748
+ // prettier-ignore
749
+ eye_R: { src: "eyewhite_sclera.png", cx: 443, cy: 475, w: EYE_W, mirror: false, noTrim: true },
750
+ // prettier-ignore
751
+ iris_L: { src: "iris.png", cx: 653, cy: 475, w: IRIS_W, mirror: false },
752
+ iris_R: { src: "iris.png", cx: 447, cy: 475, w: IRIS_W, mirror: false },
753
+ lash_L: {
754
+ src: "eyewhite_lash.png",
755
+ cx: 657,
756
+ cy: 475,
757
+ w: EYE_W,
758
+ mirror: true,
759
+ noTrim: true
760
+ },
761
+ lash_R: { src: "eyewhite_lash.png", cx: 443, cy: 475, w: EYE_W, mirror: false, noTrim: true },
762
+ // prettier-ignore
763
+ brow_L: { src: "brow.png", cx: 645, cy: 405, w: 135, mirror: false },
764
+ brow_R: { src: "brow.png", cx: 455, cy: 405, w: 135, mirror: true },
765
+ hair_front: { src: "hair_front.png", cx: 550, cy: 425, w: 660 }
766
+ };
767
+ var ORDER = [
768
+ "hair_back",
769
+ "body",
770
+ "face",
771
+ "mouth",
772
+ "mouth_open",
773
+ "eye_L",
774
+ "eye_R",
775
+ "iris_L",
776
+ "iris_R",
777
+ "lash_L",
778
+ "lash_R",
779
+ "brow_L",
780
+ "brow_R",
781
+ "hair_front"
782
+ ];
783
+ function resolveLayout(overrides) {
784
+ const resolved = { ...DEFAULT_LAYOUT };
785
+ if (overrides === void 0) return resolved;
786
+ for (const [role, override] of Object.entries(overrides)) {
787
+ if (!Object.prototype.hasOwnProperty.call(DEFAULT_LAYOUT, role)) {
788
+ throw new AutoRigInputError(
789
+ `layout.${role}: unknown role \u2014 expected one of ${Object.keys(DEFAULT_LAYOUT).join(", ")}`
790
+ );
791
+ }
792
+ if (override === void 0) continue;
793
+ const next = { ...resolved[role] };
794
+ for (const field of ["cx", "cy"]) {
795
+ const value = override[field];
796
+ if (value === void 0) continue;
797
+ if (!Number.isFinite(value)) {
798
+ throw new AutoRigInputError(
799
+ `layout.${role}.${field} must be a finite number, got ${String(value)}`
800
+ );
801
+ }
802
+ next[field] = value;
803
+ }
804
+ if (override.w !== void 0) {
805
+ if (!Number.isInteger(override.w) || override.w < 1 || override.w > CANVAS) {
806
+ throw new AutoRigInputError(
807
+ `layout.${role}.w must be an integer in 1..${CANVAS}, got ${String(override.w)}`
808
+ );
809
+ }
810
+ next.w = override.w;
811
+ }
812
+ resolved[role] = next;
813
+ }
814
+ return resolved;
815
+ }
816
+ function keyWhiteToAlpha(rgba) {
817
+ const keyed = Buffer.from(rgba);
818
+ for (let i = 0; i < keyed.length; i += 4) {
819
+ if (keyed[i] > 238 && keyed[i + 1] > 238 && keyed[i + 2] > 238) {
820
+ keyed[i + 3] = 0;
821
+ }
822
+ }
823
+ return keyed;
824
+ }
825
+ async function partBuffer(role, cfg, partsDir, inMemory) {
826
+ let img;
827
+ if (inMemory !== void 0) {
828
+ img = sharp2(inMemory);
829
+ } else {
830
+ const srcPath = path4.join(partsDir, cfg.src);
831
+ if (!fs3.existsSync(srcPath)) {
832
+ if (cfg.optional) return null;
833
+ throw new AutoRigInputError(
834
+ `missing part source for role "${role}": ${srcPath}`
835
+ );
836
+ }
837
+ const png = await decodePng(srcPath);
838
+ img = sharp2(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
839
+ raw: { width: png.width, height: png.height, channels: 4 }
840
+ });
841
+ }
842
+ if (!cfg.noTrim) img = img.trim({ threshold: 12 });
843
+ if (cfg.mirror) img = img.flop();
844
+ 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`
851
+ );
852
+ }
853
+ const resized = await sharp2(trimmed.data).resize({ width: cfg.w }).png().toBuffer({ resolveWithObject: true });
854
+ return {
855
+ buf: resized.data,
856
+ w: resized.info.width,
857
+ h: resized.info.height
858
+ };
859
+ }
860
+ function placement(role, cfg, w, h) {
861
+ const left = Math.round(cfg.cx - w / 2);
862
+ const top = Math.round(cfg.cy - h / 2);
863
+ if (left + w <= 0 || top + h <= 0 || left >= CANVAS || top >= CANVAS) {
864
+ throw new AutoRigInputError(
865
+ `layout.${role}.cx/cy: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${CANVAS} canvas`
866
+ );
867
+ }
868
+ return { left, top };
869
+ }
870
+ function blankCanvas() {
871
+ return sharp2({
872
+ create: {
873
+ width: CANVAS,
874
+ height: CANVAS,
875
+ channels: 4,
876
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
877
+ }
878
+ });
879
+ }
880
+ async function prepEyeSplit(partsDir) {
881
+ const srcPath = path4.join(partsDir, EYEWHITE_SRC);
882
+ if (!fs3.existsSync(srcPath)) {
883
+ throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);
884
+ }
885
+ const { width: W, height: H, rgba: data } = await decodePng(srcPath);
886
+ let minX = W;
887
+ let minY = H;
888
+ let maxX = -1;
889
+ let maxY = -1;
890
+ for (let y = 0; y < H; y++) {
891
+ for (let x = 0; x < W; x++) {
892
+ if (data[(y * W + x) * 4 + 3] > 8) {
893
+ if (x < minX) minX = x;
894
+ if (x > maxX) maxX = x;
895
+ if (y < minY) minY = y;
896
+ if (y > maxY) maxY = y;
897
+ }
898
+ }
899
+ }
900
+ if (maxX < 0) {
901
+ throw new AutoRigInputError(`eyewhite is fully transparent: ${srcPath}`);
902
+ }
903
+ const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);
904
+ const sclera = Buffer.from(data);
905
+ const lash = Buffer.from(data);
906
+ for (let y = 0; y < H; y++) {
907
+ for (let x = 0; x < W; x++) {
908
+ const i = (y * W + x) * 4;
909
+ const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
910
+ const isDark = data[i + 3] > 0 && lum < EYE_LASH_LUMA;
911
+ if (isDark) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255;
912
+ if (!(isDark && y <= lashCutoffY)) lash[i + 3] = 0;
913
+ }
914
+ }
915
+ const region = {
916
+ x: minX,
917
+ y: minY,
918
+ w: maxX - minX + 1,
919
+ h: maxY - minY + 1
920
+ };
921
+ return {
922
+ sclera: await cropToBuffer(sclera, W, H, region),
923
+ lash: await cropToBuffer(lash, W, H, region)
924
+ };
925
+ }
926
+ async function composeLayersFromParts(input) {
927
+ try {
928
+ const outDir = resolveOutputDir(input.outDir);
929
+ const partsDir = resolveInputDir(input.partsDir);
930
+ if (fs3.realpathSync(partsDir) === outDir) {
931
+ throw new AutoRigInputError(
932
+ `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`
933
+ );
934
+ }
935
+ const layout = resolveLayout(input.layout);
936
+ const split = await prepEyeSplit(partsDir);
937
+ const splitSources = /* @__PURE__ */ new Map([
938
+ ["eyewhite_sclera.png", split.sclera],
939
+ ["eyewhite_lash.png", split.lash]
940
+ ]);
941
+ const layers = [];
942
+ const skipped = [];
943
+ const preview = [];
944
+ for (const role of ORDER) {
945
+ const cfg = layout[role];
946
+ const part = await partBuffer(
947
+ role,
948
+ cfg,
949
+ partsDir,
950
+ splitSources.get(cfg.src)
951
+ );
952
+ if (part === null) {
953
+ skipped.push(role);
954
+ fs3.rmSync(path4.join(outDir, `${role}.png`), { force: true });
955
+ continue;
956
+ }
957
+ const { left, top } = placement(role, cfg, part.w, part.h);
958
+ const layer = await blankCanvas().composite([{ input: part.buf, left, top }]).png().toBuffer();
959
+ const outPath = path4.join(outDir, `${role}.png`);
960
+ writeFileAtomic(outPath, layer);
961
+ layers.push({
962
+ role,
963
+ path: outPath,
964
+ width: part.w,
965
+ height: part.h,
966
+ left,
967
+ top
968
+ });
969
+ preview.push({ input: part.buf, left, top });
970
+ }
971
+ const previewPng = await sharp2({
972
+ create: {
973
+ width: CANVAS,
974
+ height: CANVAS,
975
+ channels: 4,
976
+ background: { r: 245, g: 245, b: 248, alpha: 1 }
977
+ }
978
+ }).composite(preview).png().toBuffer();
979
+ const previewPath = path4.join(outDir, "preview.png");
980
+ writeFileAtomic(previewPath, previewPng);
981
+ return {
982
+ ok: true,
983
+ outDir,
984
+ layers,
985
+ skipped,
986
+ preview: previewPath,
987
+ measure: await measureDir(outDir)
988
+ };
989
+ } catch (err) {
990
+ if (err instanceof AutoRigInputError)
991
+ return { ok: false, error: err.message };
992
+ throw err;
993
+ }
994
+ }
995
+
996
+ // src/server.ts
997
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
998
+ import { z } from "zod";
999
+ function createIkiMcpServer() {
1000
+ const server = new McpServer({ name: "iki", version: "0.4.0" });
1001
+ server.registerTool(
1002
+ "validate_iki",
1003
+ {
1004
+ description: "Validates a raw .iki model (object or JSON string); fail-fast \u2014 returns at most ONE error, so fix one, re-run.",
1005
+ inputSchema: {
1006
+ model: z.unknown().describe("Raw .iki model JSON (object or JSON string)")
1007
+ }
1008
+ },
1009
+ async ({ model }) => {
1010
+ try {
1011
+ const r = validateIki(model);
1012
+ const text = r.ok ? "OK" : `INVALID: ${r.error}`;
1013
+ return { content: [{ type: "text", text }], structuredContent: r };
1014
+ } catch (err) {
1015
+ const error = err instanceof Error ? err.message : String(err);
1016
+ return {
1017
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
1018
+ structuredContent: { ok: false, error },
1019
+ isError: true
1020
+ };
1021
+ }
1022
+ }
1023
+ );
1024
+ server.registerTool(
1025
+ "describe_iki",
1026
+ {
1027
+ description: "Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.",
1028
+ inputSchema: {
1029
+ model: z.unknown().describe("Raw .iki model JSON (object or JSON string)")
1030
+ }
1031
+ },
1032
+ async ({ model }) => {
1033
+ try {
1034
+ const r = describeIki(model);
1035
+ const text = r.ok ? JSON.stringify(r.summary, null, 2) : `INVALID: ${r.error}`;
1036
+ return { content: [{ type: "text", text }], structuredContent: r };
1037
+ } catch (err) {
1038
+ const error = err instanceof Error ? err.message : String(err);
1039
+ return {
1040
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
1041
+ structuredContent: { ok: false, error },
1042
+ isError: true
1043
+ };
1044
+ }
1045
+ }
1046
+ );
1047
+ server.registerTool(
1048
+ "list_standard_parameters",
1049
+ {
1050
+ description: "Lists the recommended standard parameter ids a host can drive without per-model wiring.",
1051
+ inputSchema: {}
1052
+ },
1053
+ async () => {
1054
+ const params = listStandardParameters();
1055
+ const text = params.map((p) => `${p.id} \u2014 ${p.description}`).join("\n");
1056
+ return {
1057
+ content: [{ type: "text", text }],
1058
+ structuredContent: { parameters: params }
1059
+ };
1060
+ }
1061
+ );
1062
+ server.registerTool(
1063
+ "auto_rig_from_layers",
1064
+ {
1065
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R, mouth required; iris_L/R, brow_L/R, hair_front, etc. optional) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
1066
+ inputSchema: {
1067
+ layers: z.array(
1068
+ z.object({
1069
+ fileName: z.string().optional().describe(
1070
+ "Role-bearing filename; defaults to the basename of `path`."
1071
+ ),
1072
+ path: z.string().describe("PNG file path (resolved against cwd).")
1073
+ })
1074
+ ).describe("Full-canvas PNG layers; all must share the same size."),
1075
+ outputPath: z.string().optional().describe(
1076
+ "Output .iki path (resolved against cwd; parent dir must exist)."
1077
+ ),
1078
+ quantizeColors: z.number().int().min(2).max(256).optional().describe(
1079
+ "Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless."
1080
+ )
1081
+ }
1082
+ },
1083
+ async (args) => {
1084
+ try {
1085
+ const r = await autoRigFromLayers(args);
1086
+ const text = r.ok ? r.path : `INVALID: ${r.error}`;
1087
+ return { content: [{ type: "text", text }], structuredContent: r };
1088
+ } catch (err) {
1089
+ const error = err instanceof Error ? err.message : String(err);
1090
+ return {
1091
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
1092
+ structuredContent: { ok: false, error },
1093
+ isError: true
1094
+ };
1095
+ }
1096
+ }
1097
+ );
1098
+ server.registerTool(
1099
+ "compose_layers_from_parts",
1100
+ {
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.",
1102
+ inputSchema: {
1103
+ partsDir: z.string().describe(
1104
+ "Directory of the source part PNGs (resolved against cwd)."
1105
+ ),
1106
+ outDir: z.string().describe(
1107
+ "Existing directory to write the role layer PNGs + preview.png into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run skips has its stale PNG from an earlier run deleted."
1108
+ ),
1109
+ layout: z.record(
1110
+ z.string(),
1111
+ z.object({ cx: z.number(), cy: z.number(), w: z.number() }).partial()
1112
+ ).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."
1114
+ )
1115
+ }
1116
+ },
1117
+ async (args) => {
1118
+ try {
1119
+ const r = await composeLayersFromParts(args);
1120
+ const text = r.ok ? [
1121
+ ...r.layers.map((l) => l.path),
1122
+ formatMeasureReport({ ...r.measure, layersDir: r.outDir })
1123
+ ].join("\n") : `INVALID: ${r.error}`;
1124
+ return { content: [{ type: "text", text }], structuredContent: r };
1125
+ } catch (err) {
1126
+ const error = err instanceof Error ? err.message : String(err);
1127
+ return {
1128
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
1129
+ structuredContent: { ok: false, error },
1130
+ isError: true
1131
+ };
1132
+ }
1133
+ }
1134
+ );
1135
+ server.registerTool(
1136
+ "measure_layers",
1137
+ {
1138
+ description: "Reports read-only geometry checks over an already-composed layers directory \u2014 the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, missing optional roles). Use to re-check a layers dir without recomposing.",
1139
+ inputSchema: {
1140
+ layersDir: z.string().describe(
1141
+ "Directory of role-named layer PNGs (resolved against cwd)."
1142
+ )
1143
+ }
1144
+ },
1145
+ async ({ layersDir }) => {
1146
+ try {
1147
+ const r = await measureLayers({ layersDir });
1148
+ const text = r.ok ? formatMeasureReport(r) : `INVALID: ${r.error}`;
1149
+ return {
1150
+ content: [{ type: "text", text }],
1151
+ structuredContent: { ...r }
1152
+ };
1153
+ } catch (err) {
1154
+ const error = err instanceof Error ? err.message : String(err);
1155
+ return {
1156
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
1157
+ structuredContent: { ok: false, error },
1158
+ isError: true
1159
+ };
1160
+ }
1161
+ }
1162
+ );
1163
+ return server;
1164
+ }
1165
+
1166
+ export {
1167
+ validateIki,
1168
+ describeIki,
1169
+ listStandardParameters,
1170
+ autoRigFromLayers,
1171
+ measureLayers,
1172
+ formatMeasureReport,
1173
+ composeLayersFromParts,
1174
+ createIkiMcpServer
1175
+ };
1176
+ //# sourceMappingURL=chunk-F5RUDS6T.mjs.map