@ikijs/mcp 0.1.0 → 0.3.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/dist/{chunk-WAWSLTKU.mjs → chunk-2WIV4YEU.mjs} +21 -6
- package/dist/chunk-2WIV4YEU.mjs.map +1 -0
- package/dist/cli.js +20 -5
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +20 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +19 -5
- package/dist/chunk-WAWSLTKU.mjs.map +0 -1
|
@@ -115,7 +115,7 @@ function detectAlphaBbox(rgba, width, height) {
|
|
|
115
115
|
function cropToBuffer(rgba, width, height, bbox) {
|
|
116
116
|
return sharp(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
|
|
117
117
|
}
|
|
118
|
-
async function renderAtlasToDataUri(crops, layout) {
|
|
118
|
+
async function renderAtlasToDataUri(crops, layout, quantizeColors) {
|
|
119
119
|
const byId = /* @__PURE__ */ new Map();
|
|
120
120
|
for (const crop of crops) byId.set(crop.id, crop);
|
|
121
121
|
const pad = layout.padding;
|
|
@@ -138,7 +138,9 @@ async function renderAtlasToDataUri(crops, layout) {
|
|
|
138
138
|
channels: 4,
|
|
139
139
|
background: { r: 0, g: 0, b: 0, alpha: 0 }
|
|
140
140
|
}
|
|
141
|
-
}).composite(composites).png(
|
|
141
|
+
}).composite(composites).png(
|
|
142
|
+
quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
|
|
143
|
+
).toBuffer();
|
|
142
144
|
return `data:image/png;base64,${page.toString("base64")}`;
|
|
143
145
|
}
|
|
144
146
|
|
|
@@ -243,7 +245,7 @@ var STANDARD_PARAMETER_INFO = [
|
|
|
243
245
|
},
|
|
244
246
|
{
|
|
245
247
|
id: StandardParameter.AngleZ,
|
|
246
|
-
description: "Head tilt / roll degrees."
|
|
248
|
+
description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
|
|
247
249
|
},
|
|
248
250
|
{
|
|
249
251
|
id: StandardParameter.Breath,
|
|
@@ -268,6 +270,10 @@ var STANDARD_PARAMETER_INFO = [
|
|
|
268
270
|
{
|
|
269
271
|
id: StandardParameter.HairSwayX,
|
|
270
272
|
description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
id: StandardParameter.HairSwayZ,
|
|
276
|
+
description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
|
|
271
277
|
}
|
|
272
278
|
];
|
|
273
279
|
function listStandardParameters() {
|
|
@@ -296,6 +302,12 @@ async function autoRigFromLayers(input) {
|
|
|
296
302
|
const outPath = resolveOutputPath(
|
|
297
303
|
input.outputPath ?? "auto-rigged-model.iki"
|
|
298
304
|
);
|
|
305
|
+
const quantizeColors = input.quantizeColors;
|
|
306
|
+
if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
|
|
307
|
+
throw new AutoRigInputError(
|
|
308
|
+
`quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
|
|
309
|
+
);
|
|
310
|
+
}
|
|
299
311
|
const resolvedLayers = layers.map((layer) => {
|
|
300
312
|
const resolved = resolveInputPath(layer.path);
|
|
301
313
|
return { resolved, fileName: layer.fileName ?? path2.basename(resolved) };
|
|
@@ -375,7 +387,7 @@ async function autoRigFromLayers(input) {
|
|
|
375
387
|
`atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
|
|
376
388
|
);
|
|
377
389
|
}
|
|
378
|
-
const dataUri = await renderAtlasToDataUri(crops, layout);
|
|
390
|
+
const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
|
|
379
391
|
if (dataUri.length > MAX_OUTPUT_BYTES) {
|
|
380
392
|
throw new AutoRigInputError(
|
|
381
393
|
`atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`
|
|
@@ -427,7 +439,7 @@ async function autoRigFromLayers(input) {
|
|
|
427
439
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
428
440
|
import { z } from "zod";
|
|
429
441
|
function createIkiMcpServer() {
|
|
430
|
-
const server = new McpServer({ name: "iki", version: "0.
|
|
442
|
+
const server = new McpServer({ name: "iki", version: "0.3.0" });
|
|
431
443
|
server.registerTool(
|
|
432
444
|
"validate_iki",
|
|
433
445
|
{
|
|
@@ -504,6 +516,9 @@ function createIkiMcpServer() {
|
|
|
504
516
|
).describe("Full-canvas PNG layers; all must share the same size."),
|
|
505
517
|
outputPath: z.string().optional().describe(
|
|
506
518
|
"Output .iki path (resolved against cwd; parent dir must exist)."
|
|
519
|
+
),
|
|
520
|
+
quantizeColors: z.number().int().min(2).max(256).optional().describe(
|
|
521
|
+
"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."
|
|
507
522
|
)
|
|
508
523
|
}
|
|
509
524
|
},
|
|
@@ -532,4 +547,4 @@ export {
|
|
|
532
547
|
autoRigFromLayers,
|
|
533
548
|
createIkiMcpServer
|
|
534
549
|
};
|
|
535
|
-
//# sourceMappingURL=chunk-
|
|
550
|
+
//# sourceMappingURL=chunk-2WIV4YEU.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/server.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n generateIkiFromLayerSet,\n parseLayerRoles,\n type LayerInput,\n type AtlasAssignment,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n detectAlphaBbox,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_AREA,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n resolveOutputPath,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: { id: string; order: number; deformer?: string }[];\n deformers: DeformerSummary[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const parts = m.parts.map((p) => {\n const entry: { id: string; order: number; deformer?: string } = {\n id: p.id,\n order: p.order,\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n };\n\n return { ok: true, summary };\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description:\n \"Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Horizontal hair-sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairSwayZ,\n description:\n \"Hair-sway driver behind a head tilt. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n /** Palette-quantize the atlas PNG to this many colours (integer, 2..256).\n * Omitted = lossless. See renderAtlasToDataUri for the size/quality trade. */\n quantizeColors?: number;\n}\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n atlasBytes: number;\n }\n | { ok: false; error: string };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n const quantizeColors = input.quantizeColors;\n if (\n quantizeColors !== undefined &&\n (!Number.isInteger(quantizeColors) ||\n quantizeColors < 2 ||\n quantizeColors > 256)\n ) {\n throw new AutoRigInputError(\n `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`,\n );\n }\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n const layerInputs: LayerInput[] = [];\n const crops: AtlasCrop[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n let bbox: { x: number; y: number; w: number; h: number };\n try {\n bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n } catch (e) {\n // Enrich the empty-layer error with role + file context.\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": ${msg}`,\n );\n }\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n layerInputs.push({\n role,\n fileName,\n canvasW,\n canvasH,\n bbox,\n cropW: bbox.w,\n cropH: bbox.h,\n });\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError`.\n const model = generateIkiFromLayerSet(layerInputs, {\n width: canvasW,\n height: canvasH,\n });\n const doc = new EditorDocument(model);\n\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n if (dataUri.length > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n const partTextureAssignments: AtlasAssignment[] = crops.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n });\n\n doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(doc.getModel());\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target. `rename` REPLACES the destination entry rather\n // than following it, so an existing `.iki` symlink at outPath cannot\n // redirect the write outside the working tree (and the write is atomic).\n expectInput(\"write\", () => {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(finalModel));\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n });\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes: dataUri.length,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return { width: info.width, height: info.height, rgba: data };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n *\n * `quantizeColors` palette-quantizes the page PNG (libimagequant via sharp).\n * Flat-shaded character art keeps its look at 256 colours while the atlas\n * drops to roughly a quarter of its lossless size — the hero demo went from\n * 3.5MB to 0.9MB at a mean channel delta of 1.5/255 — which is what makes a\n * generated model shippable on a page. Omitted = lossless, as before.\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n quantizeColors?: number,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png(\n quantizeColors === undefined\n ? {}\n : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 },\n )\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Resource guards + fail-fast path resolution for the Node auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max area (px²) of the packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which composes its layers in\n * a scratch directory (`/tmp/iki-char/layers/…`) and rigs them into a model\n * under the project. Revisit only if this server ever runs with wider\n * privileges than the person driving it.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(\"layer path is empty\");\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `layer path must be a file path, not a URL: ${inputPath}`,\n );\n }\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n // Confine on REAL paths (statSync/writeFileSync follow symlinks, so a lexical\n // startsWith check can be bypassed by a symlinked dir under cwd). Compare the\n // symlink-resolved parent against the symlink-resolved root.\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `output path escapes the working directory: ${outputPath}`,\n );\n }\n return path.join(realDir, path.basename(resolved));\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"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.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"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.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers(args);\n const text = r.ok ? r.path : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";AAAA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACJP,OAAO,WAAW;AAElB,SAAS,mBAAmB,qBAAqB;;;ACLjD,OAAO,QAAQ;AACf,OAAO,UAAU;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB,OAAO;AAE9B,IAAM,mBAAmB,OAAO;AAGhC,IAAM,mBAAmB,KAAK,OAAO;AAErC,IAAM,mBAAmB,IAAI,OAAO;AAOpC,IAAM,oBAAN,cAA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D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["fs","path","path","fs"]}
|
package/dist/cli.js
CHANGED
|
@@ -133,7 +133,7 @@ function detectAlphaBbox(rgba, width, height) {
|
|
|
133
133
|
function cropToBuffer(rgba, width, height, bbox) {
|
|
134
134
|
return (0, import_sharp.default)(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
|
|
135
135
|
}
|
|
136
|
-
async function renderAtlasToDataUri(crops, layout) {
|
|
136
|
+
async function renderAtlasToDataUri(crops, layout, quantizeColors) {
|
|
137
137
|
const byId = /* @__PURE__ */ new Map();
|
|
138
138
|
for (const crop of crops) byId.set(crop.id, crop);
|
|
139
139
|
const pad = layout.padding;
|
|
@@ -156,7 +156,9 @@ async function renderAtlasToDataUri(crops, layout) {
|
|
|
156
156
|
channels: 4,
|
|
157
157
|
background: { r: 0, g: 0, b: 0, alpha: 0 }
|
|
158
158
|
}
|
|
159
|
-
}).composite(composites).png(
|
|
159
|
+
}).composite(composites).png(
|
|
160
|
+
quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
|
|
161
|
+
).toBuffer();
|
|
160
162
|
return `data:image/png;base64,${page.toString("base64")}`;
|
|
161
163
|
}
|
|
162
164
|
|
|
@@ -261,7 +263,7 @@ var STANDARD_PARAMETER_INFO = [
|
|
|
261
263
|
},
|
|
262
264
|
{
|
|
263
265
|
id: import_format.StandardParameter.AngleZ,
|
|
264
|
-
description: "Head tilt / roll degrees."
|
|
266
|
+
description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
|
|
265
267
|
},
|
|
266
268
|
{
|
|
267
269
|
id: import_format.StandardParameter.Breath,
|
|
@@ -286,6 +288,10 @@ var STANDARD_PARAMETER_INFO = [
|
|
|
286
288
|
{
|
|
287
289
|
id: import_format.StandardParameter.HairSwayX,
|
|
288
290
|
description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
|
|
291
|
+
},
|
|
292
|
+
{
|
|
293
|
+
id: import_format.StandardParameter.HairSwayZ,
|
|
294
|
+
description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
|
|
289
295
|
}
|
|
290
296
|
];
|
|
291
297
|
function listStandardParameters() {
|
|
@@ -314,6 +320,12 @@ async function autoRigFromLayers(input) {
|
|
|
314
320
|
const outPath = resolveOutputPath(
|
|
315
321
|
input.outputPath ?? "auto-rigged-model.iki"
|
|
316
322
|
);
|
|
323
|
+
const quantizeColors = input.quantizeColors;
|
|
324
|
+
if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
|
|
325
|
+
throw new AutoRigInputError(
|
|
326
|
+
`quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
|
|
327
|
+
);
|
|
328
|
+
}
|
|
317
329
|
const resolvedLayers = layers.map((layer) => {
|
|
318
330
|
const resolved = resolveInputPath(layer.path);
|
|
319
331
|
return { resolved, fileName: layer.fileName ?? import_node_path2.default.basename(resolved) };
|
|
@@ -393,7 +405,7 @@ async function autoRigFromLayers(input) {
|
|
|
393
405
|
`atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
|
|
394
406
|
);
|
|
395
407
|
}
|
|
396
|
-
const dataUri = await renderAtlasToDataUri(crops, layout);
|
|
408
|
+
const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
|
|
397
409
|
if (dataUri.length > MAX_OUTPUT_BYTES) {
|
|
398
410
|
throw new AutoRigInputError(
|
|
399
411
|
`atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`
|
|
@@ -443,7 +455,7 @@ async function autoRigFromLayers(input) {
|
|
|
443
455
|
|
|
444
456
|
// src/server.ts
|
|
445
457
|
function createIkiMcpServer() {
|
|
446
|
-
const server = new import_mcp.McpServer({ name: "iki", version: "0.
|
|
458
|
+
const server = new import_mcp.McpServer({ name: "iki", version: "0.3.0" });
|
|
447
459
|
server.registerTool(
|
|
448
460
|
"validate_iki",
|
|
449
461
|
{
|
|
@@ -520,6 +532,9 @@ function createIkiMcpServer() {
|
|
|
520
532
|
).describe("Full-canvas PNG layers; all must share the same size."),
|
|
521
533
|
outputPath: import_zod.z.string().optional().describe(
|
|
522
534
|
"Output .iki path (resolved against cwd; parent dir must exist)."
|
|
535
|
+
),
|
|
536
|
+
quantizeColors: import_zod.z.number().int().min(2).max(256).optional().describe(
|
|
537
|
+
"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."
|
|
523
538
|
)
|
|
524
539
|
}
|
|
525
540
|
},
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/cli.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"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.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers(args);\n const text = r.ok ? r.path : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n generateIkiFromLayerSet,\n parseLayerRoles,\n type LayerInput,\n type AtlasAssignment,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n detectAlphaBbox,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_AREA,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n resolveOutputPath,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: { id: string; order: number; deformer?: string }[];\n deformers: DeformerSummary[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const parts = m.parts.map((p) => {\n const entry: { id: string; order: number; deformer?: string } = {\n id: p.id,\n order: p.order,\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n };\n\n return { ok: true, summary };\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description: \"Head tilt / roll degrees.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Horizontal hair-sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n}\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n atlasBytes: number;\n }\n | { ok: false; error: string };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n const layerInputs: LayerInput[] = [];\n const crops: AtlasCrop[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n let bbox: { x: number; y: number; w: number; h: number };\n try {\n bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n } catch (e) {\n // Enrich the empty-layer error with role + file context.\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": ${msg}`,\n );\n }\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n layerInputs.push({\n role,\n fileName,\n canvasW,\n canvasH,\n bbox,\n cropW: bbox.w,\n cropH: bbox.h,\n });\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError`.\n const model = generateIkiFromLayerSet(layerInputs, {\n width: canvasW,\n height: canvasH,\n });\n const doc = new EditorDocument(model);\n\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n\n const dataUri = await renderAtlasToDataUri(crops, layout);\n if (dataUri.length > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n const partTextureAssignments: AtlasAssignment[] = crops.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n });\n\n doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(doc.getModel());\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target. `rename` REPLACES the destination entry rather\n // than following it, so an existing `.iki` symlink at outPath cannot\n // redirect the write outside the working tree (and the write is atomic).\n expectInput(\"write\", () => {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(finalModel));\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n });\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes: dataUri.length,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return { width: info.width, height: info.height, rgba: data };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png()\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Resource guards + fail-fast path resolution for the Node auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max area (px²) of the packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which composes its layers in\n * a scratch directory (`/tmp/iki-char/layers/…`) and rigs them into a model\n * under the project. Revisit only if this server ever runs with wider\n * privileges than the person driving it.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(\"layer path is empty\");\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `layer path must be a file path, not a URL: ${inputPath}`,\n );\n }\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n // Confine on REAL paths (statSync/writeFileSync follow symlinks, so a lexical\n // startsWith check can be bypassed by a symlinked dir under cwd). Compare the\n // symlink-resolved parent against the symlink-resolved root.\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `output path escapes the working directory: ${outputPath}`,\n );\n }\n return path.join(realDir, path.basename(resolved));\n}\n","#!/usr/bin/env node\nimport { createIkiMcpServer } from \"./server\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\nasync function main() {\n const server = createIkiMcpServer();\n await server.connect(new StdioServerTransport());\n}\n\nmain().catch((err) => {\n console.error(err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iBAA0B;AAC1B,iBAAkB;;;ACDlB,IAAAA,kBAAe;AACf,IAAAC,oBAAiB;AACjB,oBAOO;AACP,IAAAC,iBAQO;;;ACJP,mBAAkB;AAElB,oBAAiD;;;ACLjD,qBAAe;AACf,uBAAiB;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iB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EA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_node_fs","import_node_path","import_editor","path","fs","sharp","scanAlphaBbox","path","fs"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/cli.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"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.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"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.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers(args);\n const text = r.ok ? r.path : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n generateIkiFromLayerSet,\n parseLayerRoles,\n type LayerInput,\n type AtlasAssignment,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n detectAlphaBbox,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_AREA,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n resolveOutputPath,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: { id: string; order: number; deformer?: string }[];\n deformers: DeformerSummary[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const parts = m.parts.map((p) => {\n const entry: { id: string; order: number; deformer?: string } = {\n id: p.id,\n order: p.order,\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n };\n\n return { ok: true, summary };\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description:\n \"Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Horizontal hair-sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairSwayZ,\n description:\n \"Hair-sway driver behind a head tilt. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n /** Palette-quantize the atlas PNG to this many colours (integer, 2..256).\n * Omitted = lossless. See renderAtlasToDataUri for the size/quality trade. */\n quantizeColors?: number;\n}\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n atlasBytes: number;\n }\n | { ok: false; error: string };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n const quantizeColors = input.quantizeColors;\n if (\n quantizeColors !== undefined &&\n (!Number.isInteger(quantizeColors) ||\n quantizeColors < 2 ||\n quantizeColors > 256)\n ) {\n throw new AutoRigInputError(\n `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`,\n );\n }\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n const layerInputs: LayerInput[] = [];\n const crops: AtlasCrop[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n let bbox: { x: number; y: number; w: number; h: number };\n try {\n bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n } catch (e) {\n // Enrich the empty-layer error with role + file context.\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": ${msg}`,\n );\n }\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n layerInputs.push({\n role,\n fileName,\n canvasW,\n canvasH,\n bbox,\n cropW: bbox.w,\n cropH: bbox.h,\n });\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError`.\n const model = generateIkiFromLayerSet(layerInputs, {\n width: canvasW,\n height: canvasH,\n });\n const doc = new EditorDocument(model);\n\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n if (dataUri.length > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n const partTextureAssignments: AtlasAssignment[] = crops.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n });\n\n doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(doc.getModel());\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target. `rename` REPLACES the destination entry rather\n // than following it, so an existing `.iki` symlink at outPath cannot\n // redirect the write outside the working tree (and the write is atomic).\n expectInput(\"write\", () => {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(finalModel));\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n });\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes: dataUri.length,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return { width: info.width, height: info.height, rgba: data };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n *\n * `quantizeColors` palette-quantizes the page PNG (libimagequant via sharp).\n * Flat-shaded character art keeps its look at 256 colours while the atlas\n * drops to roughly a quarter of its lossless size — the hero demo went from\n * 3.5MB to 0.9MB at a mean channel delta of 1.5/255 — which is what makes a\n * generated model shippable on a page. Omitted = lossless, as before.\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n quantizeColors?: number,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png(\n quantizeColors === undefined\n ? {}\n : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 },\n )\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Resource guards + fail-fast path resolution for the Node auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max area (px²) of the packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which composes its layers in\n * a scratch directory (`/tmp/iki-char/layers/…`) and rigs them into a model\n * under the project. Revisit only if this server ever runs with wider\n * privileges than the person driving it.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(\"layer path is empty\");\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `layer path must be a file path, not a URL: ${inputPath}`,\n );\n }\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n // Confine on REAL paths (statSync/writeFileSync follow symlinks, so a lexical\n // startsWith check can be bypassed by a symlinked dir under cwd). Compare the\n // symlink-resolved parent against the symlink-resolved root.\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `output path escapes the working directory: ${outputPath}`,\n );\n }\n return path.join(realDir, path.basename(resolved));\n}\n","#!/usr/bin/env node\nimport { createIkiMcpServer } from \"./server\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\nasync function main() {\n const server = createIkiMcpServer();\n await server.connect(new StdioServerTransport());\n}\n\nmain().catch((err) => {\n console.error(err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iBAA0B;AAC1B,iBAAkB;;;ACDlB,IAAAA,kBAAe;AACf,IAAAC,oBAAiB;AACjB,oBAOO;AACP,IAAAC,iBAQO;;;ACJP,mBAAkB;AAElB,oBAAiD;;;ACLjD,qBAAe;AACf,uBAAiB;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB,OAAO;AAE9B,IAAM,mBAAmB,OAAO;AAGhC,IAAM,mBAAmB,KAAK,OAAO;AAErC,IAAM,mBAAmB,IAAI,OAAO;AAOpC,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAkBO,SAAS,iBAAiB,WAA2B;AAC1D,MAAI,OAAO,cAAc,YAAY,UAAU,KAAK,MAAM,IAAI;AAC5D,UAAM,IAAI,kBAAkB,qBAAqB;AAAA,EACnD;AACA,MAAI,2BAA2B,KAAK,SAAS,GAAG;AAC9C,UAAM,IAAI;AAAA,MACR,8CAA8C,SAAS;AAAA,IACzD;AAAA,EACF;AACA,QAAM,WAAW,iBAAAC,QAAK,QAAQ,QAAQ,IAAI,GAAG,SAAS;AACtD,MAAI;AACJ,MAAI;AACF,WAAO,eAAAC,QAAG,SAAS,QAAQ;AAAA,EAC7B,QAAQ;AACN,UAAM,IAAI,kBAAkB,yBAAyB,QAAQ,EAAE;AAAA,EACjE;AACA,MAAI,KAAK,YAAY,GAAG;AACtB,UAAM,IAAI;AAAA,MACR,0CAA0C,QAAQ;AAAA,IACpD;AAAA,EACF;AACA,SAAO;AACT;AAeO,SAAS,kBAAkB,YAA4B;AAC5D,MAAI,OAAO,eAAe,YAAY,WAAW,KA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AA,QACH,EACC,SAAS,uDAAuD;AAAA,QACnE,YAAY,aACT,OAAO,EACP,SAAS,EACT;AAAA,UACC;AAAA,QACF;AAAA,QACF,gBAAgB,aACb,OAAO,EACP,IAAI,EACJ,IAAI,CAAC,EACL,IAAI,GAAG,EACP,SAAS,EACT;AAAA,UACC;AAAA,QACF;AAAA,MACJ;AAAA,IACF;AAAA,IACA,OAAO,SAAS;AACd,UAAI;AACF,cAAM,IAAI,MAAM,kBAAkB,IAAI;AACtC,cAAM,OAAO,EAAE,KAAK,EAAE,OAAO,YAAY,EAAE,KAAK;AAChD,eAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC,GAAG,mBAAmB,EAAE;AAAA,MACnE,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC7D,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qBAAqB,KAAK,GAAG,CAAC;AAAA,UAC9D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;;;AI7IA,mBAAqC;AAErC,eAAe,OAAO;AACpB,QAAM,SAAS,mBAAmB;AAClC,QAAM,OAAO,QAAQ,IAAI,kCAAqB,CAAC;AACjD;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_node_fs","import_node_path","import_editor","path","fs","sharp","scanAlphaBbox","path","fs"]}
|
package/dist/cli.mjs
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -63,6 +63,9 @@ interface AutoRigInput {
|
|
|
63
63
|
layers: AutoRigLayerInput[];
|
|
64
64
|
/** Output `.iki` path (relative paths resolve against the process cwd). */
|
|
65
65
|
outputPath?: string;
|
|
66
|
+
/** Palette-quantize the atlas PNG to this many colours (integer, 2..256).
|
|
67
|
+
* Omitted = lossless. See renderAtlasToDataUri for the size/quality trade. */
|
|
68
|
+
quantizeColors?: number;
|
|
66
69
|
}
|
|
67
70
|
type AutoRigResult = {
|
|
68
71
|
ok: true;
|
package/dist/index.d.ts
CHANGED
|
@@ -63,6 +63,9 @@ interface AutoRigInput {
|
|
|
63
63
|
layers: AutoRigLayerInput[];
|
|
64
64
|
/** Output `.iki` path (relative paths resolve against the process cwd). */
|
|
65
65
|
outputPath?: string;
|
|
66
|
+
/** Palette-quantize the atlas PNG to this many colours (integer, 2..256).
|
|
67
|
+
* Omitted = lossless. See renderAtlasToDataUri for the size/quality trade. */
|
|
68
|
+
quantizeColors?: number;
|
|
66
69
|
}
|
|
67
70
|
type AutoRigResult = {
|
|
68
71
|
ok: true;
|
package/dist/index.js
CHANGED
|
@@ -144,7 +144,7 @@ function detectAlphaBbox(rgba, width, height) {
|
|
|
144
144
|
function cropToBuffer(rgba, width, height, bbox) {
|
|
145
145
|
return (0, import_sharp.default)(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
|
|
146
146
|
}
|
|
147
|
-
async function renderAtlasToDataUri(crops, layout) {
|
|
147
|
+
async function renderAtlasToDataUri(crops, layout, quantizeColors) {
|
|
148
148
|
const byId = /* @__PURE__ */ new Map();
|
|
149
149
|
for (const crop of crops) byId.set(crop.id, crop);
|
|
150
150
|
const pad = layout.padding;
|
|
@@ -167,7 +167,9 @@ async function renderAtlasToDataUri(crops, layout) {
|
|
|
167
167
|
channels: 4,
|
|
168
168
|
background: { r: 0, g: 0, b: 0, alpha: 0 }
|
|
169
169
|
}
|
|
170
|
-
}).composite(composites).png(
|
|
170
|
+
}).composite(composites).png(
|
|
171
|
+
quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
|
|
172
|
+
).toBuffer();
|
|
171
173
|
return `data:image/png;base64,${page.toString("base64")}`;
|
|
172
174
|
}
|
|
173
175
|
|
|
@@ -272,7 +274,7 @@ var STANDARD_PARAMETER_INFO = [
|
|
|
272
274
|
},
|
|
273
275
|
{
|
|
274
276
|
id: import_format.StandardParameter.AngleZ,
|
|
275
|
-
description: "Head tilt / roll degrees."
|
|
277
|
+
description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
|
|
276
278
|
},
|
|
277
279
|
{
|
|
278
280
|
id: import_format.StandardParameter.Breath,
|
|
@@ -297,6 +299,10 @@ var STANDARD_PARAMETER_INFO = [
|
|
|
297
299
|
{
|
|
298
300
|
id: import_format.StandardParameter.HairSwayX,
|
|
299
301
|
description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
|
|
302
|
+
},
|
|
303
|
+
{
|
|
304
|
+
id: import_format.StandardParameter.HairSwayZ,
|
|
305
|
+
description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
|
|
300
306
|
}
|
|
301
307
|
];
|
|
302
308
|
function listStandardParameters() {
|
|
@@ -325,6 +331,12 @@ async function autoRigFromLayers(input) {
|
|
|
325
331
|
const outPath = resolveOutputPath(
|
|
326
332
|
input.outputPath ?? "auto-rigged-model.iki"
|
|
327
333
|
);
|
|
334
|
+
const quantizeColors = input.quantizeColors;
|
|
335
|
+
if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
|
|
336
|
+
throw new AutoRigInputError(
|
|
337
|
+
`quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
|
|
338
|
+
);
|
|
339
|
+
}
|
|
328
340
|
const resolvedLayers = layers.map((layer) => {
|
|
329
341
|
const resolved = resolveInputPath(layer.path);
|
|
330
342
|
return { resolved, fileName: layer.fileName ?? import_node_path2.default.basename(resolved) };
|
|
@@ -404,7 +416,7 @@ async function autoRigFromLayers(input) {
|
|
|
404
416
|
`atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
|
|
405
417
|
);
|
|
406
418
|
}
|
|
407
|
-
const dataUri = await renderAtlasToDataUri(crops, layout);
|
|
419
|
+
const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
|
|
408
420
|
if (dataUri.length > MAX_OUTPUT_BYTES) {
|
|
409
421
|
throw new AutoRigInputError(
|
|
410
422
|
`atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`
|
|
@@ -456,7 +468,7 @@ async function autoRigFromLayers(input) {
|
|
|
456
468
|
var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
457
469
|
var import_zod = require("zod");
|
|
458
470
|
function createIkiMcpServer() {
|
|
459
|
-
const server = new import_mcp.McpServer({ name: "iki", version: "0.
|
|
471
|
+
const server = new import_mcp.McpServer({ name: "iki", version: "0.3.0" });
|
|
460
472
|
server.registerTool(
|
|
461
473
|
"validate_iki",
|
|
462
474
|
{
|
|
@@ -533,6 +545,9 @@ function createIkiMcpServer() {
|
|
|
533
545
|
).describe("Full-canvas PNG layers; all must share the same size."),
|
|
534
546
|
outputPath: import_zod.z.string().optional().describe(
|
|
535
547
|
"Output .iki path (resolved against cwd; parent dir must exist)."
|
|
548
|
+
),
|
|
549
|
+
quantizeColors: import_zod.z.number().int().min(2).max(256).optional().describe(
|
|
550
|
+
"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."
|
|
536
551
|
)
|
|
537
552
|
}
|
|
538
553
|
},
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/server.ts"],"sourcesContent":["export {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n type ValidateResult,\n type DescribeResult,\n type IkiSummary,\n type DeformerSummary,\n type StandardParameterInfo,\n type AutoRigInput,\n type AutoRigLayerInput,\n type AutoRigResult,\n} from \"./tools\";\nexport { createIkiMcpServer } from \"./server\";\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n generateIkiFromLayerSet,\n parseLayerRoles,\n type LayerInput,\n type AtlasAssignment,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n detectAlphaBbox,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_AREA,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n resolveOutputPath,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: { id: string; order: number; deformer?: string }[];\n deformers: DeformerSummary[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const parts = m.parts.map((p) => {\n const entry: { id: string; order: number; deformer?: string } = {\n id: p.id,\n order: p.order,\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n };\n\n return { ok: true, summary };\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description: \"Head tilt / roll degrees.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Horizontal hair-sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n}\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n atlasBytes: number;\n }\n | { ok: false; error: string };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n const layerInputs: LayerInput[] = [];\n const crops: AtlasCrop[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n let bbox: { x: number; y: number; w: number; h: number };\n try {\n bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n } catch (e) {\n // Enrich the empty-layer error with role + file context.\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": ${msg}`,\n );\n }\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n layerInputs.push({\n role,\n fileName,\n canvasW,\n canvasH,\n bbox,\n cropW: bbox.w,\n cropH: bbox.h,\n });\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError`.\n const model = generateIkiFromLayerSet(layerInputs, {\n width: canvasW,\n height: canvasH,\n });\n const doc = new EditorDocument(model);\n\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n\n const dataUri = await renderAtlasToDataUri(crops, layout);\n if (dataUri.length > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n const partTextureAssignments: AtlasAssignment[] = crops.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n });\n\n doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(doc.getModel());\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target. `rename` REPLACES the destination entry rather\n // than following it, so an existing `.iki` symlink at outPath cannot\n // redirect the write outside the working tree (and the write is atomic).\n expectInput(\"write\", () => {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(finalModel));\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n });\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes: dataUri.length,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return { width: info.width, height: info.height, rgba: data };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png()\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Resource guards + fail-fast path resolution for the Node auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max area (px²) of the packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which composes its layers in\n * a scratch directory (`/tmp/iki-char/layers/…`) and rigs them into a model\n * under the project. Revisit only if this server ever runs with wider\n * privileges than the person driving it.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(\"layer path is empty\");\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `layer path must be a file path, not a URL: ${inputPath}`,\n );\n }\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n // Confine on REAL paths (statSync/writeFileSync follow symlinks, so a lexical\n // startsWith check can be bypassed by a symlinked dir under cwd). Compare the\n // symlink-resolved parent against the symlink-resolved root.\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `output path escapes the working directory: ${outputPath}`,\n );\n }\n return path.join(realDir, path.basename(resolved));\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"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.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers(args);\n const text = r.ok ? r.path : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,kBAAe;AACf,IAAAC,oBAAiB;AACjB,oBAOO;AACP,IAAAC,iBAQO;;;ACJP,mBAAkB;AAElB,oBAAiD;;;ACLjD,qBAAe;AACf,uBAAiB;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB,OAAO;AAE9B,IAAM,mBAAmB,OAAO;AAGhC,IAAM,mBAAmB,KAAK,OAAO;AAErC,IAAM,mBAAmB,IAAI,OAAO;AAOpC,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAkBO,SAAS,iBAAiB,WAA2B;AAC1D,MAAI,OAAO,cAAc,YAAY,UAAU,KAAK,MAAM,IAAI;AAC5D,UAAM,IAAI,kBAAkB,qBAAqB;AAAA,EACnD;AACA,MAAI,2BAA2B,KAAK,SAAS,GAAG;AAC9C,UAAM,IAAI;AAAA,MACR,8CAA8C,SAAS;AAAA,IACzD;AAAA,EACF;AACA,QAAM,WAAW,iBAAAC,QAAK,QAAQ,QAAQ,IAAI,GAAG,SAAS;AACtD,MAAI;AACJ,MAAI;AACF,WAAO,eAAAC,QAAG,SAAS,QAAQ;AAAA,EAC7B,QAAQ;AACN,UAAM,IAAI,kBAAkB,yBAAyB,QAAQ,EAAE;AAAA,EACjE;AACA,MAAI,KAAK,YAAY,GAAG;AACtB,UAAM,IAAI;AAAA,MACR,0CAA0C,QAAQ;AAAA,IACpD;AAAA,EACF;AACA,SAAO;AACT;AAeO,S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,EAAE,MAAM,QAAQ,KAAK,CAAC,GAAG,mBAAmB,EAAE;AAAA,MACnE,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC7D,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qBAAqB,KAAK,GAAG,CAAC;AAAA,UAC9D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_node_fs","import_node_path","import_editor","path","fs","sharp","scanAlphaBbox","path","fs"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/server.ts"],"sourcesContent":["export {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n type ValidateResult,\n type DescribeResult,\n type IkiSummary,\n type DeformerSummary,\n type StandardParameterInfo,\n type AutoRigInput,\n type AutoRigLayerInput,\n type AutoRigResult,\n} from \"./tools\";\nexport { createIkiMcpServer } from \"./server\";\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n generateIkiFromLayerSet,\n parseLayerRoles,\n type LayerInput,\n type AtlasAssignment,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n detectAlphaBbox,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_AREA,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n resolveOutputPath,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: { id: string; order: number; deformer?: string }[];\n deformers: DeformerSummary[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const parts = m.parts.map((p) => {\n const entry: { id: string; order: number; deformer?: string } = {\n id: p.id,\n order: p.order,\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n };\n\n return { ok: true, summary };\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description:\n \"Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Horizontal hair-sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairSwayZ,\n description:\n \"Hair-sway driver behind a head tilt. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n /** Palette-quantize the atlas PNG to this many colours (integer, 2..256).\n * Omitted = lossless. See renderAtlasToDataUri for the size/quality trade. */\n quantizeColors?: number;\n}\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n atlasBytes: number;\n }\n | { ok: false; error: string };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n const quantizeColors = input.quantizeColors;\n if (\n quantizeColors !== undefined &&\n (!Number.isInteger(quantizeColors) ||\n quantizeColors < 2 ||\n quantizeColors > 256)\n ) {\n throw new AutoRigInputError(\n `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`,\n );\n }\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n const layerInputs: LayerInput[] = [];\n const crops: AtlasCrop[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n let bbox: { x: number; y: number; w: number; h: number };\n try {\n bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n } catch (e) {\n // Enrich the empty-layer error with role + file context.\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": ${msg}`,\n );\n }\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n layerInputs.push({\n role,\n fileName,\n canvasW,\n canvasH,\n bbox,\n cropW: bbox.w,\n cropH: bbox.h,\n });\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError`.\n const model = generateIkiFromLayerSet(layerInputs, {\n width: canvasW,\n height: canvasH,\n });\n const doc = new EditorDocument(model);\n\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n if (dataUri.length > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n const partTextureAssignments: AtlasAssignment[] = crops.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n });\n\n doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(doc.getModel());\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target. `rename` REPLACES the destination entry rather\n // than following it, so an existing `.iki` symlink at outPath cannot\n // redirect the write outside the working tree (and the write is atomic).\n expectInput(\"write\", () => {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(finalModel));\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n });\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes: dataUri.length,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return { width: info.width, height: info.height, rgba: data };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n *\n * `quantizeColors` palette-quantizes the page PNG (libimagequant via sharp).\n * Flat-shaded character art keeps its look at 256 colours while the atlas\n * drops to roughly a quarter of its lossless size — the hero demo went from\n * 3.5MB to 0.9MB at a mean channel delta of 1.5/255 — which is what makes a\n * generated model shippable on a page. Omitted = lossless, as before.\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n quantizeColors?: number,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png(\n quantizeColors === undefined\n ? {}\n : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 },\n )\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Resource guards + fail-fast path resolution for the Node auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max area (px²) of the packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which composes its layers in\n * a scratch directory (`/tmp/iki-char/layers/…`) and rigs them into a model\n * under the project. Revisit only if this server ever runs with wider\n * privileges than the person driving it.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(\"layer path is empty\");\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `layer path must be a file path, not a URL: ${inputPath}`,\n );\n }\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n // Confine on REAL paths (statSync/writeFileSync follow symlinks, so a lexical\n // startsWith check can be bypassed by a symlinked dir under cwd). Compare the\n // symlink-resolved parent against the symlink-resolved root.\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `output path escapes the working directory: ${outputPath}`,\n );\n }\n return path.join(realDir, path.basename(resolved));\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"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.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"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.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers(args);\n const text = r.ok ? r.path : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,kBAAe;AACf,IAAAC,oBAAiB;AACjB,oBAOO;AACP,IAAAC,iBAQO;;;ACJP,mBAAkB;AAElB,oBAAiD;;;ACLjD,qBAAe;AACf,uBAAiB;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB,OAAO;AAE9B,IAAM,mBAAmB,OAAO;AAGhC,IAAM,mBAAmB,KAAK,OAAO;AAErC,IAAM,mBAAmB,IAAI,OAAO;AAOpC,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAkBO,SAAS,iBAAiB,WAA2B;AAC1D,MAAI,OAAO,cAAc,YAAY,UAAU,KAAK,MAAM,IAAI;AAC5D,UAAM,IAAI,kBAAkB,qBAAqB;AAAA,EACnD;AACA,MAAI,2BAA2B,KAAK,SAAS,GAAG;AAC9C,UAAM,IAAI;AAAA,MACR,8CAA8C,SAAS;AAAA,IACzD;AAAA,EACF;AACA,QAAM,WAAW,iBAAAC,QAAK,QAAQ,QAAQ,IAAI,GAAG,SAAS;AACtD,MAAI;AACJ,MAAI;AACF,WAAO,eA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QAChC,mBAAmB,EAAE,YAAY,OAAO;AAAA,MAC1C;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,aACE;AAAA,MACF,aAAa;AAAA,QACX,QAAQ,aACL;AAAA,UACC,aAAE,OAAO;AAAA,YACP,UAAU,aACP,OAAO,EACP,SAAS,EACT;AAAA,cACC;AAAA,YACF;AAAA,YACF,MAAM,aACH,OAAO,EACP,SAAS,uCAAuC;AAAA,UACrD,CAAC;AAAA,QACH,EACC,SAAS,uDAAuD;AAAA,QACnE,YAAY,aACT,OAAO,EACP,SAAS,EACT;AAAA,UACC;AAAA,QACF;AAAA,QACF,gBAAgB,aACb,OAAO,EACP,IAAI,EACJ,IAAI,CAAC,EACL,IAAI,GAAG,EACP,SAAS,EACT;AAAA,UACC;AAAA,QACF;AAAA,MACJ;AAAA,IACF;AAAA,IACA,OAAO,SAAS;AACd,UAAI;AACF,cAAM,IAAI,MAAM,kBAAkB,IAAI;AACtC,cAAM,OAAO,EAAE,KAAK,EAAE,OAAO,YAAY,EAAE,KAAK;AAChD,eAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC,GAAG,mBAAmB,EAAE;AAAA,MACnE,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC7D,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qBAAqB,KAAK,GAAG,CAAC;AAAA,UAC9D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_node_fs","import_node_path","import_editor","path","fs","sharp","scanAlphaBbox","path","fs"]}
|
package/dist/index.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ikijs/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "MCP server that lets AI agents read, validate and auto-rig .iki 2D puppet models from role-named PNG layers",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"iki",
|
|
7
|
+
"mcp",
|
|
8
|
+
"model-context-protocol",
|
|
9
|
+
"ai",
|
|
10
|
+
"agent",
|
|
11
|
+
"claude",
|
|
12
|
+
"live2d",
|
|
13
|
+
"vtuber",
|
|
14
|
+
"2d-animation",
|
|
15
|
+
"puppet",
|
|
16
|
+
"auto-rig",
|
|
17
|
+
"rigging"
|
|
18
|
+
],
|
|
5
19
|
"main": "dist/index.js",
|
|
6
20
|
"module": "dist/index.mjs",
|
|
7
21
|
"types": "dist/index.d.ts",
|
|
@@ -20,11 +34,11 @@
|
|
|
20
34
|
"!dist/metafile-*.json"
|
|
21
35
|
],
|
|
22
36
|
"dependencies": {
|
|
37
|
+
"@ikijs/editor": "^0.2.1",
|
|
38
|
+
"@ikijs/format": "^0.2.0",
|
|
23
39
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
24
40
|
"sharp": "^0.33.5",
|
|
25
|
-
"zod": "^3.25"
|
|
26
|
-
"@ikijs/editor": "^0.1.0",
|
|
27
|
-
"@ikijs/format": "^0.1.0"
|
|
41
|
+
"zod": "^3.25"
|
|
28
42
|
},
|
|
29
43
|
"devDependencies": {
|
|
30
44
|
"tsup": "^8.5.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/server.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n generateIkiFromLayerSet,\n parseLayerRoles,\n type LayerInput,\n type AtlasAssignment,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n detectAlphaBbox,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_AREA,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n resolveOutputPath,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: { id: string; order: number; deformer?: string }[];\n deformers: DeformerSummary[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const parts = m.parts.map((p) => {\n const entry: { id: string; order: number; deformer?: string } = {\n id: p.id,\n order: p.order,\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n };\n\n return { ok: true, summary };\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description: \"Head tilt / roll degrees.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Horizontal hair-sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n}\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n atlasBytes: number;\n }\n | { ok: false; error: string };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n const layerInputs: LayerInput[] = [];\n const crops: AtlasCrop[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n let bbox: { x: number; y: number; w: number; h: number };\n try {\n bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n } catch (e) {\n // Enrich the empty-layer error with role + file context.\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": ${msg}`,\n );\n }\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n layerInputs.push({\n role,\n fileName,\n canvasW,\n canvasH,\n bbox,\n cropW: bbox.w,\n cropH: bbox.h,\n });\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError`.\n const model = generateIkiFromLayerSet(layerInputs, {\n width: canvasW,\n height: canvasH,\n });\n const doc = new EditorDocument(model);\n\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n\n const dataUri = await renderAtlasToDataUri(crops, layout);\n if (dataUri.length > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n const partTextureAssignments: AtlasAssignment[] = crops.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n });\n\n doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(doc.getModel());\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target. `rename` REPLACES the destination entry rather\n // than following it, so an existing `.iki` symlink at outPath cannot\n // redirect the write outside the working tree (and the write is atomic).\n expectInput(\"write\", () => {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(finalModel));\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n });\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes: dataUri.length,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return { width: info.width, height: info.height, rgba: data };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png()\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Resource guards + fail-fast path resolution for the Node auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max area (px²) of the packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which composes its layers in\n * a scratch directory (`/tmp/iki-char/layers/…`) and rigs them into a model\n * under the project. Revisit only if this server ever runs with wider\n * privileges than the person driving it.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(\"layer path is empty\");\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `layer path must be a file path, not a URL: ${inputPath}`,\n );\n }\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n // Confine on REAL paths (statSync/writeFileSync follow symlinks, so a lexical\n // startsWith check can be bypassed by a symlinked dir under cwd). Compare the\n // symlink-resolved parent against the symlink-resolved root.\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `output path escapes the working directory: ${outputPath}`,\n );\n }\n return path.join(realDir, path.basename(resolved));\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"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.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers(args);\n const text = r.ok ? r.path : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";AAAA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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