@ajsmonty/adobe-mcp 1.1.2 → 1.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.
@@ -0,0 +1,148 @@
1
+ """
2
+ Creature_Skin_LookDev — Substance 3D Painter look-dev pass for a large reptile/creature.
3
+ Per texture set: optional mesh-map bake (curvature/AO feed the generators), an optional smart
4
+ material, a matte "aged scales" base (high roughness, zero metal), and a cavity-masked wetness
5
+ layer (low roughness where moisture collects). Texture sets whose name matches eye/mouth/teeth/
6
+ tongue get a glossy wet treatment. Everything lands in one undo step. Optional PBR export.
7
+ Override keys in DEFAULTS via PARAMS (run_script params). Sets `result` to a per-set report.
8
+ """
9
+ import substance_painter.colormanagement as sp_cm
10
+ import substance_painter.layerstack as sp_ls
11
+ import substance_painter.project as sp_proj
12
+ import substance_painter.resource as sp_res
13
+ import substance_painter.textureset as sp_ts
14
+
15
+ DEFAULTS = {
16
+ "texture_sets": None, # None = all
17
+ "bake": False, # True kicks off an async bake first (edits queue behind it)
18
+ "smart_material": None, # e.g. "Creature Skin" (searched in the shelf); None = skip
19
+ "base_color": [0.23, 0.2, 0.16], # sRGB 0-1, desaturated olive-brown
20
+ "scale_roughness": 0.78, # matte, sun-dried scales
21
+ "wet_roughness": 0.32, # moisture in folds / cavities
22
+ "wet_generator": "Dirt", # generator used as the cavity mask for wetness
23
+ "gloss_sets": ["eye", "mouth", "teeth", "tongue", "gum"],
24
+ "gloss_roughness": 0.12, # eyes / mouth: wet, specular
25
+ "export_dir": None, # absolute folder -> export PBR Metallic Roughness
26
+ }
27
+ P = dict(DEFAULTS)
28
+ P.update(globals().get("PARAMS") or {})
29
+ CT = sp_ts.ChannelType
30
+
31
+
32
+ def gray(v):
33
+ return sp_cm.Color(v, v, v)
34
+
35
+
36
+ def set_uniform(fill, channel, value):
37
+ """Uniform channel value; some Painter versions want a Color even for scalar channels."""
38
+ try:
39
+ fill.set_source(channel, value)
40
+ except Exception:
41
+ fill.set_source(channel, gray(value) if isinstance(value, float) else value)
42
+
43
+
44
+ def find_resource(query):
45
+ try:
46
+ hits = sp_res.search(query)
47
+ return hits[0] if hits else None
48
+ except Exception:
49
+ return None
50
+
51
+
52
+ def look_dev_set(ts, notes):
53
+ name = ts.name()
54
+ stack = ts.get_stack()
55
+ glossy = any(k in name.lower() for k in P["gloss_sets"])
56
+ pos = sp_ls.InsertPosition.from_textureset_stack(stack)
57
+
58
+ if P["smart_material"] and not glossy:
59
+ res = find_resource("u:smartmaterial " + P["smart_material"])
60
+ if res is None:
61
+ notes.append("smart material %r not found" % P["smart_material"])
62
+ else:
63
+ try:
64
+ sp_ls.insert_smart_material(pos, res.identifier())
65
+ notes.append("smart material: " + P["smart_material"])
66
+ except Exception as e:
67
+ notes.append("smart material failed: %s" % e)
68
+
69
+ base = sp_ls.insert_fill(sp_ls.InsertPosition.from_textureset_stack(stack))
70
+ base.set_name("MCP Base Skin" if not glossy else "MCP Wet Gloss")
71
+ base.active_channels = {CT.BaseColor, CT.Roughness, CT.Metallic}
72
+ if not glossy:
73
+ base.set_source(CT.BaseColor, sp_cm.Color(*P["base_color"]))
74
+ set_uniform(base, CT.Roughness, float(P["gloss_roughness"] if glossy else P["scale_roughness"]))
75
+ set_uniform(base, CT.Metallic, 0.0) # organic dielectric: never metallic
76
+ if glossy:
77
+ # base colour stays whatever the artist painted; only the gloss changes
78
+ base.active_channels = {CT.Roughness, CT.Metallic}
79
+ return {"texture_set": name, "treatment": "wet gloss", "roughness": P["gloss_roughness"]}
80
+
81
+ wet = sp_ls.insert_fill(sp_ls.InsertPosition.from_textureset_stack(stack))
82
+ wet.set_name("MCP Cavity Wetness")
83
+ wet.active_channels = {CT.Roughness}
84
+ set_uniform(wet, CT.Roughness, float(P["wet_roughness"]))
85
+ masked = False
86
+ try:
87
+ wet.add_mask(sp_ls.MaskBackground.Black)
88
+ gen = find_resource("u:generator " + P["wet_generator"])
89
+ if gen is not None:
90
+ sp_ls.insert_generator_effect(
91
+ sp_ls.InsertPosition.inside_node(wet, sp_ls.NodeStack.Mask), gen.identifier())
92
+ masked = True
93
+ else:
94
+ notes.append("generator %r not found; wetness left unmasked at low opacity" % P["wet_generator"])
95
+ except Exception as e:
96
+ notes.append("wetness mask failed: %s" % e)
97
+ if not masked:
98
+ try:
99
+ wet.set_opacity(0.25, CT.Roughness)
100
+ except Exception:
101
+ pass
102
+ return {"texture_set": name, "treatment": "aged scales + cavity wetness",
103
+ "roughness": [P["scale_roughness"], P["wet_roughness"]], "wet_masked": masked}
104
+
105
+
106
+ def run():
107
+ if not sp_proj.is_open():
108
+ raise RuntimeError("No Substance Painter project is open")
109
+ wanted = P["texture_sets"]
110
+ sets = [t for t in sp_ts.all_texture_sets() if wanted is None or t.name() in wanted]
111
+ if not sets:
112
+ raise RuntimeError("No matching texture sets: %s" % wanted)
113
+ notes, report = [], []
114
+ if P["bake"]:
115
+ import substance_painter.baking as sp_bake
116
+ if hasattr(sp_bake, "bake_async"):
117
+ for t in sets:
118
+ sp_bake.bake_async(t)
119
+ notes.append("bake started (async) for %d set(s)" % len(sets))
120
+ else:
121
+ # older builds bake the Baking-window selection, not an arbitrary list
122
+ if wanted is not None and len(sets) < len(sp_ts.all_texture_sets()):
123
+ raise RuntimeError("This Painter version can only bake the texture sets selected in the Baking "
124
+ "window; select them there, or omit texture_sets")
125
+ sp_bake.bake_selected_textures_async()
126
+ notes.append("bake started (async) for the Baking-window selection")
127
+ with sp_ls.ScopedModification("adobe-mcp creature look-dev"):
128
+ for t in sets:
129
+ report.append(look_dev_set(t, notes))
130
+ out = {"texture_sets": report, "notes": notes}
131
+ if P["export_dir"]:
132
+ import os
133
+ import substance_painter.export as sp_exp
134
+ os.makedirs(P["export_dir"], exist_ok=True) # Painter's export fails on a missing folder
135
+ cfg = {
136
+ "exportShaderParams": False,
137
+ "exportPath": P["export_dir"],
138
+ "defaultExportPreset": sp_res.ResourceID(context="starter_assets", name="PBR Metallic Roughness").url(),
139
+ "exportList": [{"rootPath": t.name()} for t in sets],
140
+ "exportParameters": [{"parameters": {"fileFormat": "png", "bitDepth": "16", "paddingAlgorithm": "infinite"}}],
141
+ }
142
+ res = sp_exp.export_project_textures(cfg)
143
+ out["export"] = {"status": str(res.status), "message": res.message,
144
+ "files": [p for paths in (res.textures or {}).values() for p in paths]}
145
+ return out
146
+
147
+
148
+ result = run()
package/server.mjs CHANGED
@@ -1,31 +1,70 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * adobe-mcp — Model Context Protocol server for the Adobe Creative Cloud suite (macOS).
3
+ * adobe-mcp — Model Context Protocol server for Adobe Creative Cloud, Blender and Substance 3D Painter
4
+ * (macOS and Windows).
4
5
  *
5
6
  * Bridges MCP tool calls into each app's scripting engine:
6
- * AE / Photoshop / Illustrator → osascript (DoScript / do javascript) → ExtendScript
7
- * Premiere Pro → mcp-bridge CEP panel (command-file handoff)
8
- * Character Animator → integrated around (PSD puppet authoring via Photoshop)
7
+ * AE → macOS: osascript DoScript · Windows: AfterFX.exe -r → ExtendScript
8
+ * Photoshop / Illus. → macOS: osascript do javascript · Windows: COM DoJavaScriptFile → ExtendScript
9
+ * Premiere Pro → mcp-bridge CEP panel (command-file handoff, both OSes)
10
+ * Character Animator → integrated around (PSD puppet authoring via Photoshop)
11
+ * Blender → Python (bpy) via live add-on socket or headless background process
12
+ * Substance 3D Painter → Python via remote scripting (HTTP, port 60041)
13
+ * Poly Haven / ambientCG → free CC0 texture + HDRI libraries (HTTPS APIs, local cache)
9
14
  *
10
- * Adapters register namespaced tools (ae_*, ps_*, ai_*, ppro_*, ch_*), plus cross-app
11
- * workflow tools (asset registry, layered handoffs, per-app script libraries).
15
+ * `npx @ajsmonty/adobe-mcp doctor|install|--help` runs the CLI instead of the server.
16
+ * ADOBE_MCP_APPS=ae,ps,... limits which app tool sets are registered (default: all).
12
17
  */
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import { fileURLToPath } from "node:url";
13
21
 
14
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
15
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
22
+ const ROOT = path.dirname(fileURLToPath(import.meta.url));
23
+ const PKG = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"));
16
24
 
17
- import { register as registerAE } from "./adapters/ae.mjs";
18
- import { register as registerPS } from "./adapters/ps.mjs";
19
- import { register as registerAI } from "./adapters/ai.mjs";
20
- import { register as registerPPRO } from "./adapters/ppro.mjs";
21
- import { register as registerCH } from "./adapters/ch.mjs";
22
- import { register as registerWorkflow, makeRegisterAsset } from "./workflow/workflow.mjs";
23
- import { register as registerKnowledge, instructionsDigest } from "./knowledge/knowledge.mjs";
25
+ // ---- CLI mode --------------------------------------------------------------------------
26
+ const { CLI_COMMANDS, main } = await import("./cli/index.mjs");
27
+ const cmd = process.argv[2];
28
+ if (cmd && CLI_COMMANDS.has(cmd)) process.exit(await main(process.argv.slice(2)));
24
29
 
25
- const server = new McpServer(
26
- { name: "adobe-mcp", version: "1.1.0" },
27
- { instructions: instructionsDigest() }
28
- );
30
+ // ---- server mode -----------------------------------------------------------------------
31
+ const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
32
+ const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
33
+ const { register: registerWorkflow, makeRegisterAsset } = await import("./workflow/workflow.mjs");
34
+ const { register: registerKnowledge, instructionsDigest } = await import("./knowledge/knowledge.mjs");
35
+ const { instrument } = await import("./core/telemetry.mjs");
36
+
37
+ /** Tool sets that can be switched with ADOBE_MCP_APPS. Workflow + knowledge are always on. */
38
+ export const MODULES = {
39
+ ae: "./adapters/ae.mjs",
40
+ ps: "./adapters/ps.mjs",
41
+ ai: "./adapters/ai.mjs",
42
+ ppro: "./adapters/ppro.mjs",
43
+ ch: "./adapters/ch.mjs",
44
+ blender: "./adapters/blender.mjs",
45
+ substance: "./adapters/substance.mjs",
46
+ textures: "./adapters/texlib.mjs",
47
+ vfx: "./workflow/vfx.mjs",
48
+ };
49
+ const ALIASES = { aftereffects: "ae", photoshop: "ps", illustrator: "ai", premiere: "ppro", characteranimator: "ch", texlib: "textures" };
50
+
51
+ function enabledModules(spec = process.env.ADOBE_MCP_APPS) {
52
+ if (!spec || !spec.trim() || spec.trim() === "all") return Object.keys(MODULES);
53
+ const wanted = new Set();
54
+ for (const raw of spec.split(/[\s,]+/).filter(Boolean)) {
55
+ const k = ALIASES[raw.toLowerCase().replace(/[-_ ]/g, "")] || raw.toLowerCase();
56
+ if (MODULES[k]) wanted.add(k);
57
+ else console.error(`adobe-mcp: ignoring unknown app "${raw}" in ADOBE_MCP_APPS (valid: ${Object.keys(MODULES).join(", ")})`);
58
+ }
59
+ // Character Animator puppets are authored in Photoshop; Blender texturing uses the texture libraries.
60
+ if (wanted.has("ch")) wanted.add("ps");
61
+ if (wanted.has("blender")) wanted.add("textures");
62
+ return Object.keys(MODULES).filter((k) => wanted.has(k));
63
+ }
64
+
65
+ const enabled = enabledModules();
66
+ const server = new McpServer({ name: "adobe-mcp", version: PKG.version }, { instructions: instructionsDigest() });
67
+ const flush = instrument(server, { version: PKG.version, apps: enabled });
29
68
 
30
69
  const ctx = {
31
70
  text: (obj) => ({
@@ -38,14 +77,17 @@ const ctx = {
38
77
  registerAsset: makeRegisterAsset(),
39
78
  };
40
79
 
41
- registerAE(server, ctx);
42
- registerPS(server, ctx);
43
- registerAI(server, ctx);
44
- registerPPRO(server, ctx);
45
- registerCH(server, ctx);
80
+ for (const k of enabled) (await import(MODULES[k])).register(server, ctx);
46
81
  registerWorkflow(server, ctx);
47
82
  registerKnowledge(server, ctx);
48
83
 
49
- const transport = new StdioServerTransport();
50
- await server.connect(transport);
51
- console.error("adobe-mcp ready (ae, ps, ai, ppro, ch + workflow + knowledge)");
84
+ const shutdown = async () => {
85
+ await flush();
86
+ process.exit(0);
87
+ };
88
+ process.once("SIGINT", shutdown);
89
+ process.once("SIGTERM", shutdown);
90
+ process.stdin.once("end", shutdown);
91
+
92
+ await server.connect(new StdioServerTransport());
93
+ console.error(`adobe-mcp ${PKG.version} ready on ${process.platform} (${enabled.join(", ")} + workflow + knowledge)`);
@@ -0,0 +1,136 @@
1
+ // VFX pipeline planner: turns a creature-shot brief into physically derived timing and the
2
+ // ordered Blender → Substance → Blender → After Effects tool calls that execute it.
3
+ import { z } from "zod";
4
+ import path from "node:path";
5
+ import { WORKSPACE } from "../core/workspace.mjs";
6
+
7
+ const G = 9.81;
8
+
9
+ /** Same gait model as scripts/blender/Creature_Walk_Cinematic.py (keep in sync). */
10
+ export function deriveGait({ hip_height_m = 3.1, froude = 0.055, mass_kg = 8000, fps = 24 }) {
11
+ const v = Math.sqrt(froude * G * hip_height_m);
12
+ const stride = 2.3 * froude ** 0.3 * hip_height_m; // Alexander (1976)
13
+ const cycle_s = stride / v;
14
+ return {
15
+ speed_mps: +v.toFixed(3),
16
+ speed_kmh: +(v * 3.6).toFixed(2),
17
+ stride_m: +stride.toFixed(3),
18
+ cycle_s: +cycle_s.toFixed(3),
19
+ cycle_frames: +(cycle_s * fps).toFixed(1),
20
+ step_frames: +((cycle_s * fps) / 2).toFixed(1),
21
+ breath_s: +(4.0 * (mass_kg / 70) ** 0.26 * 0.5).toFixed(2),
22
+ gait: froude < 0.5 ? "walk" : froude < 1 ? "fast walk / trot transition" : "run",
23
+ };
24
+ }
25
+
26
+ export function register(server, { text, errText }) {
27
+ server.registerTool(
28
+ "vfx_plan_creature_shot",
29
+ {
30
+ title: "Plan a photo-real creature shot (Blender → Substance → AE)",
31
+ description:
32
+ "For briefs like 'a photo-real dinosaur walking past the camera while turning its neck'. Derives " +
33
+ "physical timing from size and mass (Froude-scaled speed, Alexander stride, steps per frame, " +
34
+ "breathing period) and returns the four-stage pipeline as concrete tool calls: 1) block + animate " +
35
+ "in Blender (run_script Creature_Walk_Cinematic.py), 2) look-dev in Substance Painter " +
36
+ "(Creature_Skin_LookDev.py + export), 3) bind textures and render passes in Blender, " +
37
+ "4) composite in After Effects (Cinematic_3D_Composite.jsx). Call this first, then run each step, " +
38
+ "verifying visually (blender_render_frame / ae_save_frame) between steps.",
39
+ inputSchema: {
40
+ brief: z.string().optional().describe("The shot description, echoed into the plan."),
41
+ hip_height_m: z.number().optional().describe("Hip height in meters (default 3.1, adult T. rex)."),
42
+ mass_kg: z.number().optional().describe("Body mass (default 8000)."),
43
+ froude: z.number().optional().describe("Gait intensity v²/(g·h): 0.05 plodding, 0.25 brisk, 0.5 walk→run (default 0.055)."),
44
+ fps: z.number().optional().describe("Frame rate (default 24)."),
45
+ duration_s: z.number().optional().describe("Shot length in seconds (default 10)."),
46
+ lens_mm: z.number().optional().describe("Focal length on a 36 mm sensor (default 35)."),
47
+ cam_distance_m: z.number().optional().describe("Camera distance from the walk line (default 14)."),
48
+ hero_mesh: z.string().optional().describe("Existing Blender object to drive (default: proxy blocking rig only)."),
49
+ shot_dir: z.string().optional().describe("Absolute folder for renders/textures (default <workspace>/shots/creature)."),
50
+ },
51
+ },
52
+ async (a) => {
53
+ try {
54
+ const fps = a.fps ?? 24;
55
+ const g = deriveGait({ hip_height_m: a.hip_height_m, froude: a.froude, mass_kg: a.mass_kg, fps });
56
+ const shot = a.shot_dir ?? path.join(WORKSPACE, "shots", "creature");
57
+ const blend = path.join(shot, "creature_shot.blend");
58
+ const params = {
59
+ fps,
60
+ duration_s: a.duration_s ?? 10,
61
+ hip_height_m: a.hip_height_m ?? 3.1,
62
+ mass_kg: a.mass_kg ?? 8000,
63
+ froude: a.froude ?? 0.055,
64
+ lens_mm: a.lens_mm ?? 35,
65
+ cam_distance_m: a.cam_distance_m ?? 14,
66
+ output_dir: path.join(shot, "render"),
67
+ ...(a.hero_mesh ? { bind: { [a.hero_mesh]: "Hips" } } : {}),
68
+ };
69
+ const plan = {
70
+ brief: a.brief ?? null,
71
+ physics: {
72
+ ...g,
73
+ notes: [
74
+ `A ${params.mass_kg} kg animal with ${params.hip_height_m} m hips walks at ${g.speed_kmh} km/h: one step every ${g.step_frames} frames at ${fps} fps.`,
75
+ "Feet are planted for 62% of each cycle (duty factor) — heavy walkers never have an airborne phase.",
76
+ "Hips drop just after each contact (weight acceptance), sway over the stance foot and roll toward the swing side.",
77
+ "Neck and tail lag the hips by 3 frames per joint (overlapping action); the head is gaze-stabilised and leads the look-turn.",
78
+ "Every footfall puts a mass- and distance-scaled impact shake into the handheld camera; timeline markers mark contacts.",
79
+ ],
80
+ },
81
+ stages: [
82
+ {
83
+ stage: "1. Analyze & block + 2. Animate (Blender)",
84
+ tool: "run_script",
85
+ args: { app: "blender", name: "Creature_Walk_Cinematic.py", mode: "background", params, save_as: blend },
86
+ verify: { tool: "blender_render_frame", args: { blend_file: blend, frame: Math.round(params.duration_s * fps * 0.55) } },
87
+ },
88
+ {
89
+ stage: "2b. Light & dress to match the plate (free CC0 libraries)",
90
+ tool: "texture_search",
91
+ args: { type: "hdri", query: "<sky that matches the plate: e.g. 'partly cloudy afternoon'>" },
92
+ then: [
93
+ { tool: "blender_set_hdri", args: { source: "<from search>", id: "<from search>", blend_file: blend, save_as: blend, mode: "background", rotation_deg: 0 } },
94
+ { tool: "blender_apply_texture", args: { objects: ["<set-dressing objects>"], source: "<from texture_search query='forest ground'>", id: "<id>", blend_file: blend, save_as: blend, mode: "background", tile_m: 2 } },
95
+ ],
96
+ note: "Rotate the HDRI until CG shadow direction matches the plate. The ground is a shadow catcher, so only texture set-dressing and props.",
97
+ },
98
+ {
99
+ stage: "3. Texture & materialize (Substance 3D Painter, project with the hero mesh open)",
100
+ tool: "run_script",
101
+ args: {
102
+ app: "substance",
103
+ name: "Creature_Skin_LookDev.py",
104
+ params: { bake: true, export_dir: path.join(shot, "textures") },
105
+ },
106
+ note: "Bake is async: if the export runs before the bake finishes, re-run substance_export_textures afterwards.",
107
+ },
108
+ {
109
+ stage: "3b. Bind textures + render passes (Blender)",
110
+ tool: "run_script",
111
+ args: {
112
+ app: "blender",
113
+ name: "Creature_Walk_Cinematic.py",
114
+ mode: "background",
115
+ blend_file: blend,
116
+ save_as: blend,
117
+ params: { ...params, texture_dir: path.join(shot, "textures") },
118
+ },
119
+ then: { tool: "blender_render_animation", args: { blend_file: blend, mode: "background" } },
120
+ note: a.hero_mesh ? undefined : "No hero_mesh given: proxies render as the creature (blocking pass).",
121
+ },
122
+ {
123
+ stage: "4. Composite & polish (After Effects, plate layer named BG_Plate in the active comp)",
124
+ tool: "run_script",
125
+ args: { app: "ae", name: "Cinematic_3D_Composite.jsx", params: { render_dir: params.output_dir, fps } },
126
+ verify: { tool: "ae_save_frame", args: { comp_name: "<your comp>" } },
127
+ },
128
+ ],
129
+ };
130
+ return text(plan);
131
+ } catch (e) {
132
+ return errText(e);
133
+ }
134
+ }
135
+ );
136
+ }
@@ -4,10 +4,15 @@ import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { runJSX, WORKSPACE, APPS } from "../core/bridge.mjs";
7
+ import { runBlender, runPainter, blenderSaveSnippet } from "../core/pybridge.mjs";
7
8
 
8
9
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
10
  const SCRIPTS_ROOT = path.join(__dirname, "..", "scripts");
10
11
  const MANIFEST = path.join(WORKSPACE, "assets.json");
12
+ // Python-scripted apps: library scripts are .py, run through the Python bridges.
13
+ const PY_APPS = { blender: runBlender, substance: runPainter };
14
+ const scriptApps = () => [...Object.keys(APPS), ...Object.keys(PY_APPS)];
15
+ const SCRIPT_EXT = (a) => (PY_APPS[a] ? /\.py$/i : /\.(jsx|jsxbin)$/i);
11
16
 
12
17
  function loadManifest() {
13
18
  try { return JSON.parse(fs.readFileSync(MANIFEST, "utf8")); } catch { return []; }
@@ -30,8 +35,8 @@ export function register(server, { text, errText, registerAsset }) {
30
35
  "The shared cross-app asset registry. Every export/render from any adapter registers here " +
31
36
  "with {id, app, kind, path}. Use it to pull one app's output into another.",
32
37
  inputSchema: {
33
- app: z.string().optional().describe("Filter by app (ae/ps/ai/ppro)."),
34
- kind: z.string().optional().describe("Filter by kind (png/svg/psd/ai/video...)."),
38
+ app: z.string().optional().describe("Filter by app (ae/ps/ai/ppro/blender/substance)."),
39
+ kind: z.string().optional().describe("Filter by kind (png/svg/psd/ai/video/texture/image-sequence/blend...)."),
35
40
  },
36
41
  },
37
42
  async ({ app, kind }) => {
@@ -55,21 +60,34 @@ export function register(server, { text, errText, registerAsset }) {
55
60
  description:
56
61
  "Import a file into the AE project. Layered .psd (Photoshop) and .ai (Illustrator) files can " +
57
62
  "import as a COMP — every source layer becomes an animatable AE layer. This is the design→" +
58
- "motion handoff.",
63
+ "motion handoff. For Blender renders pass the first frame of a sequence (or its folder) with " +
64
+ "sequence=true and the render fps.",
59
65
  inputSchema: {
60
- file_path: z.string().describe("Absolute path (.psd/.ai for layered import, or any footage)."),
66
+ file_path: z.string().describe("Absolute path (.psd/.ai for layered import, any footage, or a sequence folder/first frame)."),
61
67
  import_as: z.enum(["comp", "footage"]).optional().describe("Default comp for .psd/.ai, else footage."),
68
+ sequence: z.boolean().optional().describe("Import as a numbered image sequence (default: true when file_path is a folder)."),
69
+ fps: z.number().optional().describe("Conform the sequence frame rate (e.g. 24)."),
62
70
  },
63
71
  },
64
- async ({ file_path, import_as }) => {
72
+ async ({ file_path, import_as, sequence, fps }) => {
65
73
  try {
66
- const ext = path.extname(file_path).toLowerCase();
74
+ let target = file_path;
75
+ let isSeq = sequence ?? false;
76
+ if (fs.existsSync(file_path) && fs.statSync(file_path).isDirectory()) {
77
+ const first = fs.readdirSync(file_path).filter((f) => /\.(png|exr|tif|tiff|jpg|dpx)$/i.test(f)).sort()[0];
78
+ if (!first) throw new Error(`No image frames in ${file_path}`);
79
+ target = path.join(file_path, first);
80
+ isSeq = sequence ?? true;
81
+ }
82
+ const ext = path.extname(target).toLowerCase();
67
83
  const asComp = import_as ? import_as === "comp" : ext === ".psd" || ext === ".ai";
68
84
  const jsx = `
69
- var io = new ImportOptions(new File(${JSON.stringify(file_path)}));
70
- if (!io.file.exists) throw new Error('File not found: ' + ${JSON.stringify(file_path)});
85
+ var io = new ImportOptions(new File(${JSON.stringify(target)}));
86
+ if (!io.file.exists) throw new Error('File not found: ' + ${JSON.stringify(target)});
71
87
  ${asComp ? "if (io.canImportAs(ImportAsType.COMP)) io.importAs = ImportAsType.COMP;" : ""}
88
+ ${isSeq ? "io.sequence = true;" : ""}
72
89
  var item = app.project.importFile(io);
90
+ ${fps ? `if (item.mainSource && item.mainSource.conformFrameRate !== undefined) item.mainSource.conformFrameRate = ${Number(fps)};` : ""}
73
91
  return { imported: item.name, type: item.typeName,
74
92
  isComp: item instanceof CompItem,
75
93
  numLayers: (item instanceof CompItem) ? item.numLayers : null };`;
@@ -113,27 +131,29 @@ return { placed: ${JSON.stringify(path.basename(file_path))}, layer: app.activeD
113
131
  {
114
132
  title: "List installed script tools",
115
133
  description:
116
- "List .jsx/.jsxbin tools in the per-app scripts library (scripts/{ae,ps,ai,ppro}/), with " +
117
- "descriptions from header comments.",
134
+ "List tools in the per-app scripts library (scripts/{ae,ps,ai,ppro}/*.jsx, " +
135
+ "scripts/{blender,substance}/*.py), with descriptions from header comments/docstrings.",
118
136
  inputSchema: {
119
- app: z.string().optional().describe("Filter to one app (ae/ps/ai/ppro)."),
137
+ app: z.string().optional().describe("Filter to one app (ae/ps/ai/ppro/blender/substance)."),
120
138
  },
121
139
  },
122
140
  async ({ app }) => {
123
141
  try {
124
- const apps = app ? [app] : Object.keys(APPS);
142
+ const apps = app ? [app] : scriptApps();
125
143
  const out = {};
126
144
  for (const a of apps) {
127
145
  const dir = path.join(SCRIPTS_ROOT, a);
128
146
  let entries = [];
129
- try { entries = fs.readdirSync(dir).filter((f) => /\.(jsx|jsxbin)$/i.test(f)); } catch { /* none */ }
147
+ try { entries = fs.readdirSync(dir).filter((f) => SCRIPT_EXT(a).test(f)); } catch { /* none */ }
130
148
  out[a] = entries.map((f) => {
131
149
  let description = "[compiled .jsxbin]";
132
- if (/\.jsx$/i.test(f)) {
150
+ if (/\.(jsx|py)$/i.test(f)) {
133
151
  try {
134
152
  const head = fs.readFileSync(path.join(dir, f), "utf8").slice(0, 1500);
135
- const m = head.match(/\/\*+([\s\S]*?)\*\//) || head.match(/^((?:\s*\/\/[^\n]*\n)+)/);
136
- description = m ? m[1].replace(/^\s*(\/\/|\*)?\s?/gm, "").replace(/\s+/g, " ").trim().slice(0, 250) : "(no header)";
153
+ const m = /\.py$/i.test(f)
154
+ ? head.match(/^\s*(?:"""|''')([\s\S]*?)(?:"""|''')/) || head.match(/^((?:\s*#[^\n]*\n)+)/)
155
+ : head.match(/\/\*+([\s\S]*?)\*\//) || head.match(/^((?:\s*\/\/[^\n]*\n)+)/);
156
+ description = m ? m[1].replace(/^\s*(\/\/|\*|#)?\s?/gm, "").replace(/\s+/g, " ").trim().slice(0, 250) : "(no header)";
137
157
  } catch { description = "(unreadable)"; }
138
158
  }
139
159
  return { name: f, description };
@@ -153,24 +173,44 @@ return { placed: ${JSON.stringify(path.basename(file_path))}, layer: app.activeD
153
173
  description:
154
174
  "Execute a script from the library in its app (like File → Scripts → Run Script File). Action " +
155
175
  "scripts run immediately; ScriptUI panels open for the user. Set up selections first via the " +
156
- "app's run_extendscript.",
176
+ "app's run_extendscript. `params` is exposed to the script as PARAMS (JSX: $.global.PARAMS; " +
177
+ "Python: a PARAMS dict) — each script's header lists its keys. Scripts that report back " +
178
+ "(JSX: $.global.MCP_RESULT, Python: result) return that value.",
157
179
  inputSchema: {
158
- app: z.string().describe("Which app: ae/ps/ai/ppro."),
180
+ app: z.string().describe("Which app: ae/ps/ai/ppro/blender/substance."),
159
181
  name: z.string().describe("Script filename from list_scripts (case-insensitive)."),
160
- timeout_seconds: z.number().optional().describe("Max seconds (default 120)."),
182
+ params: z.record(z.any()).optional().describe("Parameters passed to the script as PARAMS."),
183
+ mode: z.enum(["auto", "live", "background"]).optional().describe("Blender only: bridge mode."),
184
+ blend_file: z.string().optional().describe("Blender only: .blend to open in background mode."),
185
+ save_as: z.string().optional().describe("Blender only: save the .blend here after the script runs."),
186
+ timeout_seconds: z.number().optional().describe("Max seconds (default 120; 600 for Blender)."),
161
187
  },
162
188
  },
163
- async ({ app, name, timeout_seconds }) => {
189
+ async ({ app, name, params, mode, blend_file, save_as, timeout_seconds }) => {
164
190
  try {
165
191
  const dir = path.join(SCRIPTS_ROOT, app);
166
192
  const match = fs.readdirSync(dir).find((f) => f.toLowerCase() === name.toLowerCase());
167
193
  if (!match) throw new Error(`No script "${name}" in scripts/${app}/.`);
168
194
  const full = path.join(dir, match);
195
+ if (PY_APPS[app]) {
196
+ let py = `PARAMS = ${JSON.stringify(JSON.stringify(params ?? {}))}\nimport json as __json\nPARAMS = __json.loads(PARAMS)\n`;
197
+ py += fs.readFileSync(full, "utf8");
198
+ if (app === "blender" && save_as)
199
+ py += blenderSaveSnippet(save_as);
200
+ const timeoutMs = (timeout_seconds ?? (app === "blender" ? 600 : 120)) * 1000;
201
+ const r = await PY_APPS[app](py, { mode, blendFile: blend_file, timeoutMs });
202
+ if (app === "blender" && save_as) registerAsset({ app: "blender", kind: "blend", path: save_as, meta: { script: match } });
203
+ return text({ ran: match, ...r });
204
+ }
169
205
  const jsx = `
170
206
  var __sf = new File(${JSON.stringify(full)});
171
207
  if (!__sf.exists) throw new Error('Script not found: ' + __sf.fsName);
208
+ $.global.PARAMS = ${params ? toES3Literal(params) : "undefined"};
209
+ $.global.MCP_RESULT = undefined;
172
210
  $.evalFile(__sf);
173
- return 'Ran ' + ${JSON.stringify(match)};`;
211
+ var __r = $.global.MCP_RESULT;
212
+ $.global.PARAMS = undefined; $.global.MCP_RESULT = undefined;
213
+ return __r === undefined ? 'Ran ' + ${JSON.stringify(match)} : __r;`;
174
214
  return text(await runJSX(app, jsx, (timeout_seconds ?? 120) * 1000));
175
215
  } catch (e) {
176
216
  return errText(e);
@@ -178,3 +218,8 @@ return 'Ran ' + ${JSON.stringify(match)};`;
178
218
  }
179
219
  );
180
220
  }
221
+
222
+ // JSON is a valid ES3 object literal as long as it has no U+2028/2029 line separators.
223
+ function toES3Literal(v) {
224
+ return JSON.stringify(v).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
225
+ }