@ikijs/mcp 0.23.2 → 0.24.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
@@ -6,15 +6,16 @@ A stdio [MCP](https://modelcontextprotocol.io/) server that exposes `.iki` model
6
6
 
7
7
  ## Tools
8
8
 
9
- | Tool | Description |
10
- | --------------------------- | ------------------------------------------------------------------------------------------------------ |
11
- | `validate_iki` | Validate a raw `.iki` model — accepts an object or a JSON string — fail-fast, one error at a time. |
12
- | `describe_iki` | Return a summary of a valid model's canvas, parameters, parts, deformers, expressions, and motions. |
13
- | `list_standard_parameters` | List the recommended standard parameter ids (e.g. `ParamAngleX`, `ParamMouthOpenY`) with descriptions. |
14
- | `auto_rig_from_layers` | Auto-rig role-named PNG layers into a renderable `.iki` written to disk; returns the output path. |
15
- | `compose_layers_from_parts` | Compose generated part PNGs into canvas-aligned, role-named layers, with the geometry report inline. |
16
- | `measure_layers` | Re-run that same geometry report over an already-composed layers directory. |
17
- | `measure_turn_reference` | Measure how far a head turns between a front and a turned image at the same scale, as three ratios. |
9
+ | Tool | Description |
10
+ | --------------------------- | ---------------------------------------------------------------------------------------------------------- |
11
+ | `validate_iki` | Validate a raw `.iki` model — accepts an object or a JSON string — fail-fast, one error at a time. |
12
+ | `describe_iki` | Return a summary of a valid model's canvas, parameters, parts, deformers, expressions, and motions. |
13
+ | `list_standard_parameters` | List the recommended standard parameter ids (e.g. `ParamAngleX`, `ParamMouthOpenY`) with descriptions. |
14
+ | `auto_rig_from_layers` | Auto-rig role-named PNG layers into a renderable `.iki` written to disk; returns the output path. |
15
+ | `compose_layers_from_parts` | Compose generated part PNGs into canvas-aligned, role-named layers, with the geometry report inline. |
16
+ | `measure_layers` | Re-run that same geometry report over an already-composed layers directory. |
17
+ | `measure_turn_reference` | Measure how far a head turns between a front and a turned image at the same scale, as three ratios. |
18
+ | `render_poses` | Render a rigged `.iki` into the character loop's pose PNGs through the installed Chrome, Edge or Chromium. |
18
19
 
19
20
  The `model` input for `validate_iki` and `describe_iki` accepts either a plain JSON object or a JSON string — the server normalises both.
20
21
 
@@ -74,6 +75,15 @@ The head span is the silhouette at the eye row, over a ±10-row band — fixed r
74
75
 
75
76
  The two rules do not agree on the same picture — a near-black outline is silhouette under `alpha` and background under `keyed` — so compare renders with renders and references with references.
76
77
 
78
+ ### `render_poses`
79
+
80
+ Renders a rigged `.iki` into the pose PNGs the character loop reviews, with the real engine, so the render step is one tool call. The engine runs in the Chrome, Edge or Chromium already installed on the machine, headless and driven over DevTools by the server itself: no Playwright and no browser download. Set `CHROME_PATH` to an executable to pick a browser; without it the usual install locations are searched, and with none found the tool returns `INVALID: …` saying so, and a `CHROME_PATH` that is not an executable file is refused the same way. A browser that is found but fails to start is a tool error. It needs Node 22 or newer.
81
+
82
+ - **`modelPath`** — the rigged `.iki` (resolved against the working directory; must sit under it).
83
+ - **`outDir`** — an existing directory under the working directory. One `<pose>.png` per pose is written into it, replacing a same-named file in place.
84
+ - **What is written** — the model decides the set. A bust gets 560 × 560 shots: `rest`, `turn-m30`, `turn-p30`, `turn-15`, `nod-15`, `blink`, `blink-half`, `gaze`, `combined`. A model with a `mouth` or `mouth_inner` adds 720 × 480 mouth crops (`mouth-open-*-form-*`, `mouth-laugh`, `mouth-surprised`, `mouth-turn-p30-half`). A full body (canvas taller than wide) shoots the same squares from the model's top (the head), centred horizontally, and adds whole-canvas `full-*` shots (body, arm and elbow poses) at 1400 px wide; one with a pose forearm (`ParamArmPoseR`) adds the `full-pose-*` shots.
85
+ - **Result** — the text is the written paths, one per line. `failedTextures` lists the atlas pages the engine could not load; their parts are missing from the renders. `structuredContent` is `{ ok: true, outDir, canvas, fullBody, mouth?, failedTextures, poses: [{ name, path }] }`. A missing model, an `outDir` that is missing or outside the working directory, or a file that is not a valid model returns `{ ok: false, error }` with `INVALID: …` text.
86
+
77
87
  ## Usage
78
88
 
79
89
  Run directly with npx (no install needed):
@@ -105,7 +115,7 @@ codex mcp add iki -- npx -y @ikijs/mcp
105
115
 
106
116
  ## Scope note
107
117
 
108
- Current tools cover read/validate, auto-rigging a model from PNG layers (`auto_rig_from_layers`), composing/measuring the role layers a generated character needs (`compose_layers_from_parts`, `measure_layers`), and measuring a rendered head turn against a reference one (`measure_turn_reference`). PSD input and granular model-mutation primitives (add part, bind parameter, export) are deferred to future slices.
118
+ Current tools cover read/validate, auto-rigging a model from PNG layers (`auto_rig_from_layers`), composing/measuring the role layers a generated character needs (`compose_layers_from_parts`, `measure_layers`), measuring a rendered head turn against a reference one (`measure_turn_reference`), and rendering a rigged model's poses (`render_poses`). PSD input and granular model-mutation primitives (add part, bind parameter, export) are deferred to future slices.
109
119
 
110
120
  ## License
111
121
 
@@ -48,18 +48,18 @@ function rejectEmptyOrUrl(inputPath, noun, kind) {
48
48
  );
49
49
  }
50
50
  }
51
- function resolveInputPath(inputPath) {
52
- rejectEmptyOrUrl(inputPath, "layer path", "file path");
51
+ function resolveInputPath(inputPath, what = "layer") {
52
+ rejectEmptyOrUrl(inputPath, `${what} path`, "file path");
53
53
  const resolved = path.resolve(process.cwd(), inputPath);
54
54
  let stat;
55
55
  try {
56
56
  stat = fs.statSync(resolved);
57
57
  } catch {
58
- throw new AutoRigInputError(`layer file not found: ${resolved}`);
58
+ throw new AutoRigInputError(`${what} file not found: ${resolved}`);
59
59
  }
60
60
  if (stat.isDirectory()) {
61
61
  throw new AutoRigInputError(
62
- `layer path is a directory, not a file: ${resolved}`
62
+ `${what} path is a directory, not a file: ${resolved}`
63
63
  );
64
64
  }
65
65
  return resolved;
@@ -3300,11 +3300,504 @@ async function composeLayersFromParts(input) {
3300
3300
  }
3301
3301
  }
3302
3302
 
3303
+ // src/render-poses.ts
3304
+ import { readFileSync } from "fs";
3305
+ import path9 from "path";
3306
+ import {
3307
+ IkiFormatError as IkiFormatError2,
3308
+ StandardParameter as StandardParameter2,
3309
+ loadIkiModel as loadIkiModel2
3310
+ } from "@ikijs/format";
3311
+
3312
+ // src/render-browser.ts
3313
+ import { spawn } from "child_process";
3314
+ import fs4 from "fs";
3315
+ import os from "os";
3316
+ import path8 from "path";
3317
+ var NO_BROWSER_MESSAGE = "render_poses needs a Chromium-based browser and found none. Install Google Chrome, Microsoft Edge or Chromium, or set CHROME_PATH to its executable.";
3318
+ var DARWIN_CANDIDATES = [
3319
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
3320
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
3321
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
3322
+ ];
3323
+ var LINUX_CANDIDATES = [
3324
+ "/usr/bin/google-chrome",
3325
+ "/usr/bin/google-chrome-stable",
3326
+ "/usr/bin/chromium",
3327
+ "/usr/bin/chromium-browser",
3328
+ "/usr/bin/microsoft-edge",
3329
+ "/snap/bin/chromium"
3330
+ ];
3331
+ var WIN32_ROOTS = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"];
3332
+ var WIN32_SUFFIXES = [
3333
+ ["Google", "Chrome", "Application", "chrome.exe"],
3334
+ ["Microsoft", "Edge", "Application", "msedge.exe"]
3335
+ ];
3336
+ var CLOSE_GRACE_MS = 2e3;
3337
+ var DEFAULT_TIMEOUT_MS = 3e4;
3338
+ var BROWSER_CLOSE_MS = 1e3;
3339
+ function isExecutableFile(file) {
3340
+ try {
3341
+ if (!fs4.statSync(file).isFile()) return false;
3342
+ fs4.accessSync(file, fs4.constants.X_OK);
3343
+ return true;
3344
+ } catch {
3345
+ return false;
3346
+ }
3347
+ }
3348
+ function findBrowser({
3349
+ env = process.env,
3350
+ platform = process.platform,
3351
+ isExecutable = isExecutableFile
3352
+ } = {}) {
3353
+ const override = env.CHROME_PATH;
3354
+ if (override) {
3355
+ if (!isExecutable(override)) {
3356
+ throw new AutoRigInputError(
3357
+ `CHROME_PATH is not an executable file: ${override}`
3358
+ );
3359
+ }
3360
+ return override;
3361
+ }
3362
+ let candidates;
3363
+ if (platform === "darwin") candidates = DARWIN_CANDIDATES;
3364
+ else if (platform === "win32") {
3365
+ candidates = [];
3366
+ for (const suffix of WIN32_SUFFIXES) {
3367
+ for (const root of WIN32_ROOTS) {
3368
+ const base = env[root];
3369
+ if (base) candidates.push(path8.win32.join(base, ...suffix));
3370
+ }
3371
+ }
3372
+ } else candidates = LINUX_CANDIDATES;
3373
+ return candidates.find((file) => isExecutable(file));
3374
+ }
3375
+ function within(promise, ms, what, detail) {
3376
+ let timer;
3377
+ const timeout = new Promise((_, reject) => {
3378
+ timer = setTimeout(
3379
+ () => reject(
3380
+ new Error(
3381
+ `${what} timed out after ${ms} ms${detail ? `: ${detail()}` : ""}`
3382
+ )
3383
+ ),
3384
+ ms
3385
+ );
3386
+ });
3387
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
3388
+ }
3389
+ function connectCdp(url, timeoutMs) {
3390
+ const socket = new WebSocket(url);
3391
+ let nextId = 0;
3392
+ let socketClosed = false;
3393
+ const pending = /* @__PURE__ */ new Map();
3394
+ socket.addEventListener("message", (event) => {
3395
+ const message = JSON.parse(String(event.data));
3396
+ const entry = pending.get(message.id);
3397
+ if (!entry) return;
3398
+ pending.delete(message.id);
3399
+ if (message.error) {
3400
+ entry.reject(
3401
+ new Error(`${message.error.message} (${message.error.code})`)
3402
+ );
3403
+ } else entry.resolve(message.result);
3404
+ });
3405
+ socket.addEventListener("close", () => {
3406
+ socketClosed = true;
3407
+ for (const entry of pending.values()) {
3408
+ entry.reject(new Error("DevTools connection closed"));
3409
+ }
3410
+ pending.clear();
3411
+ });
3412
+ const opened = new Promise((resolve, reject) => {
3413
+ socket.addEventListener(
3414
+ "error",
3415
+ () => reject(new Error("DevTools connection failed"))
3416
+ );
3417
+ socket.addEventListener(
3418
+ "open",
3419
+ () => resolve({
3420
+ send(method, callTimeoutMs, params, sessionId) {
3421
+ if (socketClosed) {
3422
+ return Promise.reject(new Error("DevTools connection closed"));
3423
+ }
3424
+ const id = ++nextId;
3425
+ const reply = new Promise((res, rej) => {
3426
+ pending.set(id, {
3427
+ resolve: res,
3428
+ reject: rej
3429
+ });
3430
+ });
3431
+ socket.send(JSON.stringify({ id, method, params, sessionId }));
3432
+ return within(reply, callTimeoutMs, method).finally(
3433
+ () => pending.delete(id)
3434
+ );
3435
+ }
3436
+ })
3437
+ );
3438
+ });
3439
+ return within(opened, timeoutMs, "DevTools connection").catch((error) => {
3440
+ socket.close();
3441
+ throw error;
3442
+ });
3443
+ }
3444
+ function startError(executable, error) {
3445
+ return new Error(
3446
+ `could not start ${executable}: ${error.code ?? error.message}`
3447
+ );
3448
+ }
3449
+ function waitForDevTools(child, closed, getSpawnError, executable, timeoutMs) {
3450
+ let tail = "";
3451
+ return within(
3452
+ new Promise((resolve, reject) => {
3453
+ child.stderr.on("data", (chunk) => {
3454
+ tail = (tail + chunk).slice(-2e3);
3455
+ const match = /DevTools listening on (ws:\/\/\S+)/.exec(tail);
3456
+ if (match) resolve(match[1]);
3457
+ });
3458
+ void closed.then(() => {
3459
+ const spawnError = getSpawnError();
3460
+ reject(
3461
+ spawnError ? startError(executable, spawnError) : new Error(
3462
+ `${executable} exited before DevTools was ready: ${tail.trim()}`
3463
+ )
3464
+ );
3465
+ });
3466
+ }),
3467
+ timeoutMs,
3468
+ "browser startup",
3469
+ () => tail.trim() || "no output"
3470
+ );
3471
+ }
3472
+ async function openPage(cdp, timeoutMs) {
3473
+ const { targetId } = await cdp.send(
3474
+ "Target.createTarget",
3475
+ timeoutMs,
3476
+ { url: "about:blank" }
3477
+ );
3478
+ const { sessionId } = await cdp.send(
3479
+ "Target.attachToTarget",
3480
+ timeoutMs,
3481
+ { targetId, flatten: true }
3482
+ );
3483
+ return async (expression, evalTimeoutMs) => {
3484
+ const { result, exceptionDetails } = await cdp.send(
3485
+ "Runtime.evaluate",
3486
+ evalTimeoutMs,
3487
+ { expression, awaitPromise: true, returnByValue: true },
3488
+ sessionId
3489
+ );
3490
+ if (exceptionDetails) {
3491
+ const thrown = exceptionDetails.exception;
3492
+ throw new Error(
3493
+ thrown?.description ?? (thrown && "value" in thrown ? String(thrown.value) : exceptionDetails.text)
3494
+ );
3495
+ }
3496
+ return result.value;
3497
+ };
3498
+ }
3499
+ function removeProfile(profile) {
3500
+ try {
3501
+ fs4.rmSync(profile, {
3502
+ recursive: true,
3503
+ force: true,
3504
+ maxRetries: 5,
3505
+ retryDelay: 100
3506
+ });
3507
+ } catch (error) {
3508
+ console.error(`could not remove browser profile ${profile}:`, error);
3509
+ }
3510
+ }
3511
+ async function launchBrowser(executable, timeoutMs) {
3512
+ if (typeof globalThis.WebSocket === "undefined") {
3513
+ throw new AutoRigInputError(
3514
+ "render_poses needs Node 22 or newer (the global WebSocket is missing)."
3515
+ );
3516
+ }
3517
+ const profile = fs4.mkdtempSync(path8.join(os.tmpdir(), "iki-render-"));
3518
+ let child;
3519
+ try {
3520
+ child = spawn(
3521
+ executable,
3522
+ [
3523
+ "--headless=new",
3524
+ "--remote-debugging-port=0",
3525
+ `--user-data-dir=${profile}`,
3526
+ "--no-first-run",
3527
+ "--no-default-browser-check",
3528
+ // Output pixel sizes must equal the plan's, whatever the display.
3529
+ "--force-device-scale-factor=1",
3530
+ // WebGL without a GPU; recent Chrome no longer falls back by itself.
3531
+ "--enable-unsafe-swiftshader",
3532
+ "about:blank"
3533
+ ],
3534
+ { stdio: ["ignore", "ignore", "pipe"] }
3535
+ );
3536
+ } catch (error) {
3537
+ fs4.rmSync(profile, { recursive: true, force: true });
3538
+ throw startError(executable, error);
3539
+ }
3540
+ let spawnError;
3541
+ child.on("error", (error) => {
3542
+ spawnError = error;
3543
+ });
3544
+ let exited = false;
3545
+ const closed = new Promise((resolve) => {
3546
+ child.on("close", () => {
3547
+ exited = true;
3548
+ resolve();
3549
+ });
3550
+ });
3551
+ const settle = (ms) => within(closed, ms, "browser close").catch(() => {
3552
+ });
3553
+ const onProcessExit = () => {
3554
+ child.kill("SIGKILL");
3555
+ removeProfile(profile);
3556
+ };
3557
+ process.once("exit", onProcessExit);
3558
+ let shutdownPromise;
3559
+ const shutdown = () => shutdownPromise ??= (async () => {
3560
+ if (!exited) {
3561
+ child.kill();
3562
+ await settle(CLOSE_GRACE_MS);
3563
+ if (!exited) {
3564
+ child.kill("SIGKILL");
3565
+ await settle(CLOSE_GRACE_MS);
3566
+ }
3567
+ }
3568
+ process.removeListener("exit", onProcessExit);
3569
+ removeProfile(profile);
3570
+ })();
3571
+ let cdp;
3572
+ try {
3573
+ const endpoint = await waitForDevTools(
3574
+ child,
3575
+ closed,
3576
+ () => spawnError,
3577
+ executable,
3578
+ timeoutMs
3579
+ );
3580
+ cdp = await connectCdp(endpoint, timeoutMs);
3581
+ } catch (error) {
3582
+ await shutdown();
3583
+ throw error;
3584
+ }
3585
+ return {
3586
+ openPage: () => openPage(cdp, timeoutMs),
3587
+ async close() {
3588
+ if (!exited) {
3589
+ await cdp.send("Browser.close", BROWSER_CLOSE_MS).catch(() => {
3590
+ });
3591
+ }
3592
+ await shutdown();
3593
+ }
3594
+ };
3595
+ }
3596
+ async function withBrowser(executable, fn) {
3597
+ const browser = await launchBrowser(executable, DEFAULT_TIMEOUT_MS);
3598
+ try {
3599
+ return await fn(await browser.openPage());
3600
+ } finally {
3601
+ await browser.close();
3602
+ }
3603
+ }
3604
+
3605
+ // src/render-poses.ts
3606
+ var FULL_BODY_VIEW_WIDTH = 2.5;
3607
+ var BUST_SIZE = 560;
3608
+ function planRenders(model) {
3609
+ const { width: W, height: H } = model.canvas;
3610
+ const fullBody = H > W;
3611
+ const canvas = fullBody ? {
3612
+ width: FULL_BODY_VIEW_WIDTH * BUST_SIZE,
3613
+ height: Math.ceil(BUST_SIZE * H / W)
3614
+ } : { width: BUST_SIZE, height: BUST_SIZE };
3615
+ const view = fullBody ? { x: 0, y: 0, width: FULL_BODY_VIEW_WIDTH * W, height: H } : void 0;
3616
+ const x0 = (canvas.width - BUST_SIZE) / 2;
3617
+ const s = BUST_SIZE / W;
3618
+ const mouthPart = model.parts.find((p) => p.id === "mouth_inner") ?? model.parts.find((p) => p.id === "mouth");
3619
+ const mouth = mouthPart ? { cx: W / 2 + mouthPart.transform.x, cy: H / 2 - mouthPart.transform.y } : void 0;
3620
+ const squareCrop = fullBody ? {
3621
+ sx: x0,
3622
+ sy: 0,
3623
+ sw: BUST_SIZE,
3624
+ sh: BUST_SIZE,
3625
+ dw: BUST_SIZE,
3626
+ dh: BUST_SIZE
3627
+ } : void 0;
3628
+ const square = (name, values = {}) => ({
3629
+ name,
3630
+ values,
3631
+ crop: squareCrop
3632
+ });
3633
+ const whole = (name, values = {}) => ({
3634
+ name,
3635
+ values
3636
+ });
3637
+ const poses = [
3638
+ square("rest"),
3639
+ square("turn-m30", { ParamAngleX: -30 }),
3640
+ square("turn-p30", { ParamAngleX: 30 }),
3641
+ square("turn-15", { ParamAngleX: 15 }),
3642
+ square("nod-15", { ParamAngleY: 15 }),
3643
+ square("blink", { ParamEyeLOpen: 0 }),
3644
+ square("blink-half", { ParamEyeLOpen: 0.5 }),
3645
+ square("gaze", { ParamEyeBallX: 1 }),
3646
+ square("combined", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 })
3647
+ ];
3648
+ if (mouth) {
3649
+ const crop = {
3650
+ sx: x0 + (mouth.cx - 90) * s,
3651
+ sy: (mouth.cy - 60) * s,
3652
+ sw: 180 * s,
3653
+ sh: 120 * s,
3654
+ dw: 720,
3655
+ dh: 480
3656
+ };
3657
+ for (const open of [0, 0.3, 0.6, 1]) {
3658
+ for (const [name, form] of [
3659
+ ["m1", -1],
3660
+ ["0", 0],
3661
+ ["p1", 1]
3662
+ ]) {
3663
+ poses.push({
3664
+ name: `mouth-open-${open}-form-${name}`,
3665
+ values: { ParamMouthOpenY: open, ParamMouthForm: form },
3666
+ crop
3667
+ });
3668
+ }
3669
+ }
3670
+ poses.push(
3671
+ {
3672
+ name: "mouth-laugh",
3673
+ values: { ParamMouthOpenY: 0.8, ParamMouthForm: 1 },
3674
+ crop
3675
+ },
3676
+ { name: "mouth-surprised", values: { ParamMouthOpenY: 0.9 }, crop },
3677
+ {
3678
+ name: "mouth-turn-p30-half",
3679
+ values: { ParamAngleX: 30, ParamMouthOpenY: 0.5 },
3680
+ crop
3681
+ }
3682
+ );
3683
+ }
3684
+ if (fullBody) {
3685
+ poses.push(
3686
+ whole("full-rest"),
3687
+ whole("full-turn-p30", { ParamAngleX: 30 }),
3688
+ whole("full-body-x-m10", { ParamBodyAngleX: -10 }),
3689
+ whole("full-body-x-p10", { ParamBodyAngleX: 10 }),
3690
+ whole("full-body-y-m10", { ParamBodyAngleY: -10 }),
3691
+ whole("full-body-y-p10", { ParamBodyAngleY: 10 }),
3692
+ whole("full-body-z-m10", { ParamBodyAngleZ: -10 }),
3693
+ whole("full-body-z-p10", { ParamBodyAngleZ: 10 }),
3694
+ whole("full-arm-l-16", { ParamArmL: 16 }),
3695
+ whole("full-arm-l-32", { ParamArmL: 32 }),
3696
+ whole("full-arm-r-16", { ParamArmR: 16 }),
3697
+ whole("full-arm-r-32", { ParamArmR: 32 }),
3698
+ whole("full-elbow-l-m10", { ParamElbowL: -10 }),
3699
+ whole("full-elbow-l-45", { ParamElbowL: 45 }),
3700
+ whole("full-elbow-l-90", { ParamElbowL: 90 }),
3701
+ whole("full-elbow-r-m10", { ParamElbowR: -10 }),
3702
+ whole("full-elbow-r-45", { ParamElbowR: 45 }),
3703
+ whole("full-elbow-r-90", { ParamElbowR: 90 })
3704
+ );
3705
+ if (model.parameters.some((p) => p.id === StandardParameter2.ArmPoseRight)) {
3706
+ poses.push(
3707
+ whole("full-pose-l", { ParamArmPoseL: 1 }),
3708
+ whole("full-pose-r", { ParamArmPoseR: 1 }),
3709
+ whole("full-pose-r-angle-m15", {
3710
+ ParamArmPoseR: 1,
3711
+ ParamArmPoseAngleR: -15
3712
+ }),
3713
+ whole("full-pose-r-angle-p15", {
3714
+ ParamArmPoseR: 1,
3715
+ ParamArmPoseAngleR: 15
3716
+ }),
3717
+ whole("full-pose-r-half", { ParamArmPoseR: 0.5 })
3718
+ );
3719
+ }
3720
+ }
3721
+ return { canvas, view, fullBody, mouth, poses };
3722
+ }
3723
+ var PNG_PREFIX = "data:image/png;base64,";
3724
+ var PAGE_SCRIPT_MS = 1e4;
3725
+ var LOAD_MS = 6e4;
3726
+ var CAPTURE_MS = 15e3;
3727
+ function readPageScript() {
3728
+ const url = new URL("../dist/render-page.global.js", import.meta.url);
3729
+ try {
3730
+ return readFileSync(url, "utf8");
3731
+ } catch (cause) {
3732
+ throw new Error(
3733
+ "could not read the render page script; run `pnpm build` in packages/mcp",
3734
+ { cause }
3735
+ );
3736
+ }
3737
+ }
3738
+ async function renderPoses(input) {
3739
+ try {
3740
+ const modelFile = confineToWorkingDirectory(
3741
+ process.cwd(),
3742
+ resolveInputPath(input.modelPath, "model"),
3743
+ "model path",
3744
+ input.modelPath
3745
+ );
3746
+ const outDir = resolveOutputDir(input.outDir);
3747
+ const model = loadIkiModel2(readFileSync(modelFile, "utf8"));
3748
+ const plan = planRenders(model);
3749
+ const browser = findBrowser();
3750
+ if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
3751
+ const pageScript = readPageScript();
3752
+ const { failedTextures, poses } = await withBrowser(
3753
+ browser,
3754
+ async (evaluate) => {
3755
+ await evaluate(pageScript, PAGE_SCRIPT_MS);
3756
+ const loaded = await evaluate(
3757
+ `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
3758
+ LOAD_MS
3759
+ );
3760
+ const written = [];
3761
+ for (const pose of plan.poses) {
3762
+ const url = await evaluate(
3763
+ `window.__ikiRender.capture(${JSON.stringify(pose.values)}, ${JSON.stringify(pose.crop)})`,
3764
+ CAPTURE_MS
3765
+ );
3766
+ if (typeof url !== "string" || !url.startsWith(PNG_PREFIX)) {
3767
+ throw new Error(`pose ${pose.name}: the page returned no PNG`);
3768
+ }
3769
+ const file = path9.join(outDir, `${pose.name}.png`);
3770
+ writeFileAtomic(
3771
+ file,
3772
+ Buffer.from(url.slice(PNG_PREFIX.length), "base64")
3773
+ );
3774
+ written.push({ name: pose.name, path: file });
3775
+ }
3776
+ return { failedTextures: loaded.failedTextures, poses: written };
3777
+ }
3778
+ );
3779
+ return {
3780
+ ok: true,
3781
+ outDir,
3782
+ canvas: plan.canvas,
3783
+ fullBody: plan.fullBody,
3784
+ mouth: plan.mouth,
3785
+ failedTextures,
3786
+ poses
3787
+ };
3788
+ } catch (error) {
3789
+ if (error instanceof AutoRigInputError || error instanceof IkiFormatError2) {
3790
+ return { ok: false, error: error.message };
3791
+ }
3792
+ throw error;
3793
+ }
3794
+ }
3795
+
3303
3796
  // src/server.ts
3304
3797
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3305
3798
  import { z } from "zod";
3306
3799
  function createIkiMcpServer() {
3307
- const server = new McpServer({ name: "iki", version: "0.23.2" });
3800
+ const server = new McpServer({ name: "iki", version: "0.24.0" });
3308
3801
  server.registerTool(
3309
3802
  "validate_iki",
3310
3803
  {
@@ -3534,6 +4027,34 @@ function createIkiMcpServer() {
3534
4027
  }
3535
4028
  }
3536
4029
  );
4030
+ server.registerTool(
4031
+ "render_poses",
4032
+ {
4033
+ description: "Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
4034
+ inputSchema: {
4035
+ modelPath: z.string().describe(
4036
+ "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
4037
+ ),
4038
+ outDir: z.string().describe(
4039
+ "Existing directory to write the pose PNGs into (resolved against cwd; must already exist; confined to the working directory)."
4040
+ )
4041
+ }
4042
+ },
4043
+ async (args) => {
4044
+ try {
4045
+ const r = await renderPoses(args);
4046
+ const text = r.ok ? r.poses.map((p) => p.path).join("\n") : `INVALID: ${r.error}`;
4047
+ return { content: [{ type: "text", text }], structuredContent: r };
4048
+ } catch (err) {
4049
+ const error = err instanceof Error ? err.message : String(err);
4050
+ return {
4051
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
4052
+ structuredContent: { ok: false, error },
4053
+ isError: true
4054
+ };
4055
+ }
4056
+ }
4057
+ );
3537
4058
  return server;
3538
4059
  }
3539
4060
 
@@ -3547,6 +4068,7 @@ export {
3547
4068
  measureLayers,
3548
4069
  formatMeasureReport,
3549
4070
  composeLayersFromParts,
4071
+ renderPoses,
3550
4072
  createIkiMcpServer
3551
4073
  };
3552
- //# sourceMappingURL=chunk-SXLILLB6.mjs.map
4074
+ //# sourceMappingURL=chunk-GEXOSC5O.mjs.map