@ajsmonty/adobe-mcp 1.1.2 → 1.5.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +361 -119
  3. package/SECURITY.md +24 -1
  4. package/adapters/ae_more.mjs +208 -0
  5. package/adapters/an.mjs +96 -0
  6. package/adapters/assets.mjs +194 -0
  7. package/adapters/blender.mjs +230 -0
  8. package/adapters/id.mjs +250 -0
  9. package/adapters/ppro.mjs +4 -3
  10. package/adapters/ppro_more.mjs +393 -0
  11. package/adapters/ps_ai_more.mjs +277 -0
  12. package/adapters/substance.mjs +193 -0
  13. package/adapters/texlib.mjs +193 -0
  14. package/bridges/blender/adobe_mcp_bridge.py +132 -0
  15. package/cep/mcp-bridge/CSXS/manifest.xml +36 -2
  16. package/cep/mcp-bridge/main.js +48 -20
  17. package/cli/doctor.mjs +234 -0
  18. package/cli/index.mjs +67 -0
  19. package/cli/install.mjs +149 -0
  20. package/core/barrows.mjs +16 -0
  21. package/core/blender_pbr.py +148 -0
  22. package/core/bridge.mjs +166 -77
  23. package/core/harness.jsx +11 -6
  24. package/core/harness.py +34 -0
  25. package/core/helpers.mjs +196 -0
  26. package/core/platform.mjs +209 -0
  27. package/core/pybridge.mjs +256 -0
  28. package/core/telemetry.mjs +80 -0
  29. package/core/texlib.mjs +279 -0
  30. package/core/win/run_com.js +33 -0
  31. package/core/workspace.mjs +1 -1
  32. package/knowledge/knowledge.mjs +8 -5
  33. package/knowledge/lessons.jsonl +19 -0
  34. package/package.json +56 -3
  35. package/scripts/ae/Cinematic_3D_Composite.jsx +173 -0
  36. package/scripts/blender/Creature_Walk_Cinematic.py +569 -0
  37. package/scripts/substance/Creature_Skin_LookDev.py +148 -0
  38. package/server.mjs +92 -27
  39. package/workflow/setup.mjs +106 -0
  40. package/workflow/vfx.mjs +136 -0
  41. package/workflow/workflow.mjs +66 -21
@@ -0,0 +1,193 @@
1
+ // Substance 3D Painter adapter — Python via the remote-scripting HTTP endpoint (port 60041).
2
+ import { z } from "zod";
3
+ import fs from "node:fs";
4
+ import { runPainter } from "../core/pybridge.mjs";
5
+
6
+ const STATE_PY = `
7
+ import substance_painter.project as sp_proj
8
+ import substance_painter.textureset as sp_ts
9
+ import substance_painter.layerstack as sp_ls
10
+ if not sp_proj.is_open():
11
+ result = {"project_open": False}
12
+ else:
13
+ sets = []
14
+ for ts in sp_ts.all_texture_sets():
15
+ rec = {"name": ts.name(), "stacks": []}
16
+ try:
17
+ res = ts.get_resolution(); rec["resolution"] = [res.width, res.height]
18
+ except Exception as e:
19
+ rec["resolution"] = str(e)
20
+ for st in ts.all_stacks():
21
+ srec = {"name": st.name(), "channels": [], "layers": []}
22
+ try:
23
+ srec["channels"] = sorted(str(k).split(".")[-1] for k in st.all_channels().keys())
24
+ except Exception:
25
+ pass
26
+ try:
27
+ srec["layers"] = [n.get_name() for n in sp_ls.get_root_layer_nodes(st)][:100]
28
+ except Exception:
29
+ pass
30
+ rec["stacks"].append(srec)
31
+ sets.append(rec)
32
+ result = {"project_open": True, "name": sp_proj.name(), "file": sp_proj.file_path(),
33
+ "dirty": sp_proj.needs_saving() if hasattr(sp_proj, "needs_saving") else None,
34
+ "texture_sets": sets}
35
+ `;
36
+
37
+ export function register(server, { text, errText, registerAsset }) {
38
+ server.registerTool(
39
+ "substance_run_python",
40
+ {
41
+ title: "Run Python in Substance 3D Painter",
42
+ description:
43
+ "Execute Python inside Substance 3D Painter (modules: substance_painter.project, .textureset, " +
44
+ ".layerstack, .baking, .export, .resource, .colormanagement). Runs as a module body; set " +
45
+ "`result = <value>` to return JSON. Requires Painter launched with --enable-remote-scripting " +
46
+ "(port 60041). ALWAYS guard with substance_painter.project.is_open(). Wrap layer edits in " +
47
+ "`with substance_painter.layerstack.ScopedModification('name'):` so they are one undo step. " +
48
+ "GOTCHAS: baking is ASYNC — bake_*_async() returns immediately; never block/sleep the main thread " +
49
+ "waiting for it (Painter deadlocks). There is no bake_mesh_maps(). More: knowledge_search app=substance.",
50
+ inputSchema: {
51
+ code: z.string().describe("Python source; assign `result` to return data."),
52
+ timeout_seconds: z.number().optional().describe("Max seconds (default 120)."),
53
+ },
54
+ },
55
+ async ({ code, timeout_seconds }) => {
56
+ try {
57
+ return text({ ok: true, ...(await runPainter(code, { timeoutMs: (timeout_seconds ?? 120) * 1000 })) });
58
+ } catch (e) {
59
+ return errText(e);
60
+ }
61
+ }
62
+ );
63
+
64
+ server.registerTool(
65
+ "substance_get_state",
66
+ {
67
+ title: "Inspect the open Substance Painter project",
68
+ description: "Project name/file and every texture set with resolution, stacks, channels and root layers.",
69
+ inputSchema: {},
70
+ },
71
+ async () => {
72
+ try {
73
+ return text((await runPainter(STATE_PY, { timeoutMs: 60000 })).result);
74
+ } catch (e) {
75
+ return errText(e);
76
+ }
77
+ }
78
+ );
79
+
80
+ server.registerTool(
81
+ "substance_bake_mesh_maps",
82
+ {
83
+ title: "Bake mesh maps in Substance Painter",
84
+ description:
85
+ "Start baking mesh maps (normal, AO, curvature, thickness, position, world-space normal, ID) — " +
86
+ "smart materials and generators need curvature/AO to find edges and cavities. Optionally set " +
87
+ "the bake resolution first. Baking is ASYNC: this returns once the bake has STARTED; poll " +
88
+ "substance_get_state or just proceed — Painter queues edits behind the bake.",
89
+ inputSchema: {
90
+ texture_sets: z.array(z.string()).optional().describe("Texture set names (default: all)."),
91
+ size_log2: z.number().int().min(7).max(13).optional().describe("Output size as log2 (11 = 2048)."),
92
+ },
93
+ },
94
+ async ({ texture_sets, size_log2 }) => {
95
+ try {
96
+ const py = `
97
+ import substance_painter.project as sp_proj
98
+ import substance_painter.textureset as sp_ts
99
+ import substance_painter.baking as sp_bake
100
+ if not sp_proj.is_open():
101
+ raise RuntimeError("No Substance Painter project is open")
102
+ wanted = ${JSON.stringify(texture_sets ?? null)}
103
+ targets = [t for t in sp_ts.all_texture_sets() if wanted is None or t.name() in wanted]
104
+ if not targets:
105
+ raise RuntimeError("No matching texture sets: %s" % wanted)
106
+ notes = []
107
+ size_log2 = ${size_log2 ?? "None"}
108
+ if size_log2 is not None:
109
+ for t in targets:
110
+ try:
111
+ params = sp_bake.BakingParameters.from_texture_set(t)
112
+ common = params.common()
113
+ params.set({common["OutputSize"]: (size_log2, size_log2)})
114
+ except Exception as e:
115
+ notes.append("size on %s not set: %s" % (t.name(), e))
116
+ started = []
117
+ if hasattr(sp_bake, "bake_async"):
118
+ for t in targets:
119
+ sp_bake.bake_async(t); started.append(t.name())
120
+ elif hasattr(sp_bake, "bake_selected_textures_async"):
121
+ # older builds bake whatever is selected in the Baking window, not an arbitrary list
122
+ if wanted is not None and len(targets) < len(sp_ts.all_texture_sets()):
123
+ raise RuntimeError("This Painter version can only bake the texture sets selected in the Baking window; "
124
+ "select them there, or omit texture_sets")
125
+ sp_bake.bake_selected_textures_async(); started = ["(Baking window selection)"]
126
+ else:
127
+ raise RuntimeError("This Painter version exposes no async baking API")
128
+ result = {"bake_started": started, "notes": notes}
129
+ `;
130
+ return text((await runPainter(py, { timeoutMs: 60000 })).result);
131
+ } catch (e) {
132
+ return errText(e);
133
+ }
134
+ }
135
+ );
136
+
137
+ server.registerTool(
138
+ "substance_export_textures",
139
+ {
140
+ title: "Export PBR texture maps from Substance Painter",
141
+ description:
142
+ "Export the project's textures with an export preset (default the starter-assets 'PBR Metallic " +
143
+ "Roughness': BaseColor, Metallic, Roughness, Normal, Height/Displacement, AO). Registers each " +
144
+ "written map as a workflow asset so Blender can pick them up for the beauty render.",
145
+ inputSchema: {
146
+ output_dir: z.string().describe("Absolute export folder."),
147
+ preset: z.string().optional().describe("Starter-assets export preset name (default 'PBR Metallic Roughness')."),
148
+ file_format: z.enum(["png", "exr", "tif", "jpeg", "tga"]).optional().describe("Default png."),
149
+ bit_depth: z.enum(["8", "16", "32f"]).optional().describe("Default 16 (8 for jpeg)."),
150
+ size_log2: z.number().int().min(7).max(13).optional().describe("11 = 2048, 12 = 4096 (default: texture set size)."),
151
+ texture_sets: z.array(z.string()).optional().describe("Texture set names (default: all)."),
152
+ },
153
+ },
154
+ async ({ output_dir, preset, file_format, bit_depth, size_log2, texture_sets }) => {
155
+ try {
156
+ fs.mkdirSync(output_dir, { recursive: true });
157
+ const fmt = file_format ?? "png";
158
+ const depth = bit_depth ?? (fmt === "jpeg" ? "8" : "16");
159
+ const py = `
160
+ import substance_painter.project as sp_proj
161
+ import substance_painter.textureset as sp_ts
162
+ import substance_painter.export as sp_exp
163
+ import substance_painter.resource as sp_res
164
+ if not sp_proj.is_open():
165
+ raise RuntimeError("No Substance Painter project is open")
166
+ wanted = ${JSON.stringify(texture_sets ?? null)}
167
+ names = [t.name() for t in sp_ts.all_texture_sets() if wanted is None or t.name() in wanted]
168
+ params = {"fileFormat": ${JSON.stringify(fmt)}, "bitDepth": ${JSON.stringify(depth)}, "dithering": True, "paddingAlgorithm": "infinite"}
169
+ size_log2 = ${size_log2 ?? "None"}
170
+ if size_log2 is not None:
171
+ params["sizeLog2"] = size_log2
172
+ config = {
173
+ "exportShaderParams": False,
174
+ "exportPath": ${JSON.stringify(output_dir)},
175
+ "defaultExportPreset": sp_res.ResourceID(context="starter_assets", name=${JSON.stringify(preset ?? "PBR Metallic Roughness")}).url(),
176
+ "exportList": [{"rootPath": n} for n in names],
177
+ "exportParameters": [{"parameters": params}],
178
+ }
179
+ res = sp_exp.export_project_textures(config)
180
+ files = []
181
+ for _k, paths in (res.textures or {}).items():
182
+ files.extend(paths)
183
+ result = {"status": str(res.status), "message": res.message, "files": files}
184
+ `;
185
+ const r = (await runPainter(py, { timeoutMs: 600000 })).result;
186
+ for (const f of r.files || []) registerAsset({ app: "substance", kind: "texture", path: f, meta: { preset: preset ?? "PBR Metallic Roughness" } });
187
+ return text(r);
188
+ } catch (e) {
189
+ return errText(e);
190
+ }
191
+ }
192
+ );
193
+ }
@@ -0,0 +1,193 @@
1
+ // Free texture libraries (Poly Haven, ambientCG — all CC0) → search, download, apply in Blender.
2
+ import { z } from "zod";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { runBlender, blenderSaveSnippet } from "../core/pybridge.mjs";
7
+ import { searchLibraries, downloadAsset, classifyAmbientFile, TEXTURE_CACHE } from "../core/texlib.mjs";
8
+
9
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
+ const PBR_PY = fs.readFileSync(path.join(__dirname, "..", "core", "blender_pbr.py"), "utf8");
11
+
12
+ const SOURCE = z.enum(["polyhaven", "ambientcg"]).describe("Library the asset id comes from (see texture_search).");
13
+ const RES = z.enum(["1k", "2k", "4k", "8k"]).optional().describe("Resolution (default 2k; 4k+ for hero close-ups).");
14
+ const MODE = z.enum(["auto", "live", "background"]).optional().describe("Blender bridge mode (see blender_run_python).");
15
+
16
+ /** Python that runs a blender_pbr helper with JSON kwargs. */
17
+ function pbrCall(fn, kwargs, saveAs) {
18
+ return (
19
+ `${PBR_PY}\nimport json as __json\n` +
20
+ `result = ${fn}(**__json.loads(${JSON.stringify(JSON.stringify(kwargs))}))\n` +
21
+ (saveAs ? blenderSaveSnippet(saveAs) : "")
22
+ );
23
+ }
24
+
25
+ /** Canonical maps from a local folder (e.g. a Substance export). */
26
+ function mapsFromDir(dir) {
27
+ const maps = {};
28
+ for (const f of fs.readdirSync(dir).sort()) {
29
+ if (!/\.(png|jpe?g|exr|tiff?)$/i.test(f)) continue;
30
+ const canon = classifyAmbientFile(f);
31
+ if (canon && !maps[canon]) maps[canon] = path.join(dir, f);
32
+ }
33
+ if (!Object.keys(maps).length) throw new Error(`No recognisable maps (…_BaseColor, _Roughness, _Normal…) in ${dir}`);
34
+ return maps;
35
+ }
36
+
37
+ export function register(server, { text, errText, registerAsset }) {
38
+ const fetchAsset = async (args) => {
39
+ const a = await downloadAsset(args);
40
+ if (!a.cached)
41
+ for (const [map, p] of Object.entries(a.maps))
42
+ registerAsset({ app: a.source, kind: a.type === "hdri" ? "hdri" : "texture", path: p, meta: { id: a.id, map, resolution: a.resolution, license: a.license } });
43
+ return a;
44
+ };
45
+
46
+ server.registerTool(
47
+ "texture_search",
48
+ {
49
+ title: "Search free CC0 texture & HDRI libraries",
50
+ description:
51
+ "Search Poly Haven and ambientCG, the two big free, CC0 (public domain, no attribution) PBR libraries " +
52
+ "Blender artists use. Returns asset ids, names, tags, preview thumbnails and pages. type=texture for " +
53
+ "materials (rock, bark, scales, ground, concrete…), type=hdri for image-based lighting that matches a plate. " +
54
+ "Poly Haven categories include e.g. rock, terrain, wood, fabric, brick; ambientCG is keyword search.",
55
+ inputSchema: {
56
+ query: z.string().optional().describe("Keywords, e.g. 'wet rock', 'reptile skin', 'forest ground'."),
57
+ type: z.enum(["texture", "hdri"]).optional().describe("Default texture."),
58
+ source: z.enum(["all", "polyhaven", "ambientcg"]).optional().describe("Default all."),
59
+ category: z.string().optional().describe("Optional category filter (Poly Haven category / extra ambientCG keyword)."),
60
+ limit: z.number().int().min(1).max(50).optional().describe("Results per library (default 12)."),
61
+ },
62
+ },
63
+ async ({ query, type, source, category, limit }) => {
64
+ try {
65
+ const r = await searchLibraries({ query, type: type ?? "texture", source: source ?? "all", category, limit: limit ?? 12 });
66
+ return text({ count: r.results.length, ...r, license: "All results are CC0 — free for commercial use, no attribution required." });
67
+ } catch (e) {
68
+ return errText(e);
69
+ }
70
+ }
71
+ );
72
+
73
+ server.registerTool(
74
+ "texture_download",
75
+ {
76
+ title: "Download a library texture or HDRI",
77
+ description:
78
+ "Download one asset at a resolution into the local cache (<workspace>/textures, reused on repeat calls) " +
79
+ "with maps renamed to a common convention (<id>_BaseColor, _Roughness, _Normal (OpenGL), _Height, _AO, " +
80
+ "_Metallic, _ARM, _Opacity; HDRIs as _HDRI). Registers every map as a workflow asset. The folder works " +
81
+ "directly as texture_dir for Creature_Walk_Cinematic.py or blender_apply_texture.",
82
+ inputSchema: {
83
+ source: SOURCE,
84
+ id: z.string().describe("Asset id from texture_search (e.g. 'rock_face' or 'Rock030')."),
85
+ type: z.enum(["texture", "hdri"]).optional().describe("Default texture."),
86
+ resolution: RES,
87
+ format: z.enum(["jpg", "png", "exr", "hdr"]).optional().describe("Textures: jpg (default)/png/exr. HDRIs: hdr (default)/exr."),
88
+ },
89
+ },
90
+ async ({ source, id, type, resolution, format }) => {
91
+ try {
92
+ return text(await fetchAsset({ source, id, type: type ?? "texture", resolution: resolution ?? "2k", format }));
93
+ } catch (e) {
94
+ return errText(e);
95
+ }
96
+ }
97
+ );
98
+
99
+ server.registerTool(
100
+ "blender_apply_texture",
101
+ {
102
+ title: "Apply a library (or local) PBR texture to Blender objects",
103
+ description:
104
+ "Build a Principled BSDF material from a Poly Haven / ambientCG asset (downloaded on demand) or a local " +
105
+ "folder of maps (e.g. a Substance Painter export), and assign it to objects. Colour maps are sRGB, data " +
106
+ "maps Non-Color, normals OpenGL, height drives true displacement (method BOTH), ARM is unpacked when " +
107
+ "separate maps are missing, and baked AO is left out (Cycles computes its own). Meshes without UVs get " +
108
+ "tri-planar box projection. Set tile_m to the real-world size one tile covers so scale reads correctly.",
109
+ inputSchema: {
110
+ objects: z.array(z.string()).min(1).describe("Blender object names to assign the material to."),
111
+ source: SOURCE.optional(),
112
+ id: z.string().optional().describe("Library asset id (with source)."),
113
+ texture_dir: z.string().optional().describe("Alternative: absolute folder of maps named *_BaseColor, *_Roughness, *_Normal…"),
114
+ resolution: RES,
115
+ format: z.enum(["jpg", "png", "exr"]).optional(),
116
+ material_name: z.string().optional().describe("Default: the asset id."),
117
+ tile_m: z.number().positive().optional().describe("Meters covered by one texture tile (default 2)."),
118
+ projection: z.enum(["auto", "uv", "box"]).optional().describe("Default auto (uv if every object has UVs)."),
119
+ displacement_m: z.number().min(0).optional().describe("Height-map displacement in meters (default 0.02; 0 disables)."),
120
+ mode: MODE,
121
+ blend_file: z.string().optional(),
122
+ save_as: z.string().optional().describe("Save the .blend here afterwards (needed in background mode)."),
123
+ },
124
+ },
125
+ async (a) => {
126
+ try {
127
+ let maps, label;
128
+ if (a.texture_dir) {
129
+ maps = mapsFromDir(a.texture_dir);
130
+ label = path.basename(a.texture_dir);
131
+ } else {
132
+ if (!a.source || !a.id) throw new Error("Pass source + id (from texture_search) or texture_dir.");
133
+ const asset = await fetchAsset({ source: a.source, id: a.id, type: "texture", resolution: a.resolution ?? "2k", format: a.format });
134
+ maps = asset.maps;
135
+ label = a.id;
136
+ }
137
+ const kwargs = {
138
+ name: a.material_name ?? label,
139
+ maps,
140
+ objects: a.objects,
141
+ tile_m: a.tile_m ?? 2.0,
142
+ projection: a.projection ?? "auto",
143
+ displacement_m: a.displacement_m ?? 0.02,
144
+ };
145
+ const r = await runBlender(pbrCall("build_pbr_material", kwargs, a.save_as), { mode: a.mode, blendFile: a.blend_file, timeoutMs: 180000 });
146
+ return text({ ...r.result, bridge_mode: r.mode, saved: a.save_as ?? null });
147
+ } catch (e) {
148
+ return errText(e);
149
+ }
150
+ }
151
+ );
152
+
153
+ server.registerTool(
154
+ "blender_set_hdri",
155
+ {
156
+ title: "Light the Blender scene with a library HDRI",
157
+ description:
158
+ "Download a Poly Haven / ambientCG HDRI (or use a local .hdr/.exr) and set it as the world light. Pick " +
159
+ "an HDRI whose sun height, colour and cloud cover match the live-action plate, then rotate it " +
160
+ "(rotation_deg) until CG shadows line up with the plate's. This is the biggest single win for photo-real " +
161
+ "integration.",
162
+ inputSchema: {
163
+ source: SOURCE.optional(),
164
+ id: z.string().optional().describe("HDRI asset id from texture_search type=hdri."),
165
+ hdri_path: z.string().optional().describe("Alternative: absolute path to a local .hdr/.exr."),
166
+ resolution: RES,
167
+ strength: z.number().min(0).optional().describe("Background strength (default 1)."),
168
+ rotation_deg: z.number().optional().describe("Rotate the environment around Z (default 0)."),
169
+ mode: MODE,
170
+ blend_file: z.string().optional(),
171
+ save_as: z.string().optional(),
172
+ },
173
+ },
174
+ async (a) => {
175
+ try {
176
+ let hdri = a.hdri_path;
177
+ if (!hdri) {
178
+ if (!a.source || !a.id) throw new Error("Pass source + id (texture_search type=hdri) or hdri_path.");
179
+ const asset = await fetchAsset({ source: a.source, id: a.id, type: "hdri", resolution: a.resolution ?? "2k" });
180
+ hdri = asset.maps.HDRI;
181
+ }
182
+ if (!fs.existsSync(hdri)) throw new Error(`HDRI not found: ${hdri}`);
183
+ const kwargs = { path: hdri, strength: a.strength ?? 1.0, rotation_deg: a.rotation_deg ?? 0 };
184
+ const r = await runBlender(pbrCall("set_world_hdri", kwargs, a.save_as), { mode: a.mode, blendFile: a.blend_file, timeoutMs: 120000 });
185
+ return text({ ...r.result, path: hdri, bridge_mode: r.mode, saved: a.save_as ?? null });
186
+ } catch (e) {
187
+ return errText(e);
188
+ }
189
+ }
190
+ );
191
+ }
192
+
193
+ export { TEXTURE_CACHE };
@@ -0,0 +1,132 @@
1
+ # adobe-mcp live bridge for Blender.
2
+ #
3
+ # Install: Edit → Preferences → Add-ons → (dropdown) Install from Disk… → pick this file, then
4
+ # enable "adobe-mcp Bridge". It listens on 127.0.0.1:9877 (override with the BLENDER_MCP_PORT
5
+ # environment variable before launching Blender) and executes Python sent by the adobe-mcp
6
+ # server on Blender's MAIN thread (bpy is not thread-safe), one request at a time.
7
+ #
8
+ # Protocol: one JSON line in {"code": "..."} → one JSON line out
9
+ # {"ok": true, "result": <value of `result`>, "stdout": "..."} or
10
+ # {"ok": false, "error": "...", "line": n, "traceback": "..."}
11
+ # Localhost only, no auth: anything that can reach the port can run Python in Blender.
12
+ # Disable the add-on when you are not using it.
13
+
14
+ bl_info = {
15
+ "name": "adobe-mcp Bridge",
16
+ "author": "AJ Montgomery",
17
+ "version": (1, 0, 0),
18
+ "blender": (4, 2, 0),
19
+ "location": "Runs in the background (127.0.0.1:9877)",
20
+ "description": "Lets the adobe-mcp MCP server run Python in this Blender session",
21
+ "category": "System",
22
+ }
23
+
24
+ import contextlib
25
+ import io
26
+ import json
27
+ import os
28
+ import queue
29
+ import socket
30
+ import threading
31
+ import traceback
32
+
33
+ import bpy
34
+
35
+ PORT = int(os.environ.get("BLENDER_MCP_PORT", "9877"))
36
+ _requests = queue.Queue()
37
+ _server = {"sock": None, "thread": None, "stop": False}
38
+
39
+
40
+ def _execute(code):
41
+ ns = {"__name__": "__adobe_mcp__"}
42
+ out = io.StringIO()
43
+ try:
44
+ with contextlib.redirect_stdout(out):
45
+ exec(compile(code, "<adobe-mcp>", "exec"), ns)
46
+ return {"ok": True, "result": ns.get("result"), "stdout": out.getvalue()[-8000:]}
47
+ except BaseException as e:
48
+ line = e.lineno if isinstance(e, SyntaxError) and e.filename == "<adobe-mcp>" else None
49
+ for fr in traceback.extract_tb(e.__traceback__):
50
+ if fr.filename == "<adobe-mcp>":
51
+ line = fr.lineno
52
+ return {
53
+ "ok": False,
54
+ "error": "%s: %s" % (type(e).__name__, e),
55
+ "line": line,
56
+ "traceback": traceback.format_exc()[-4000:],
57
+ "stdout": out.getvalue()[-4000:],
58
+ }
59
+
60
+
61
+ def _pump():
62
+ """Timer callback on the main thread: run queued requests."""
63
+ while True:
64
+ try:
65
+ code, reply = _requests.get_nowait()
66
+ except queue.Empty:
67
+ break
68
+ reply(_execute(code))
69
+ return None if _server["stop"] else 0.05
70
+
71
+
72
+ def _serve_client(conn):
73
+ with conn:
74
+ buf = b""
75
+ while b"\n" not in buf:
76
+ chunk = conn.recv(65536)
77
+ if not chunk:
78
+ return
79
+ buf += chunk
80
+ try:
81
+ code = json.loads(buf.split(b"\n", 1)[0].decode("utf-8"))["code"]
82
+ except Exception as e:
83
+ conn.sendall((json.dumps({"ok": False, "error": "Bad request: %s" % e}) + "\n").encode())
84
+ return
85
+ done = threading.Event()
86
+ box = {}
87
+
88
+ def reply(res):
89
+ box["res"] = res
90
+ done.set()
91
+
92
+ _requests.put((code, reply))
93
+ done.wait()
94
+ conn.sendall((json.dumps(box["res"], default=str) + "\n").encode("utf-8"))
95
+
96
+
97
+ def _accept_loop(sock):
98
+ while not _server["stop"]:
99
+ try:
100
+ conn, _ = sock.accept()
101
+ except OSError:
102
+ break
103
+ threading.Thread(target=_serve_client, args=(conn,), daemon=True).start()
104
+
105
+
106
+ def register():
107
+ _server["stop"] = False
108
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
109
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
110
+ sock.bind(("127.0.0.1", PORT))
111
+ sock.listen(4)
112
+ _server["sock"] = sock
113
+ _server["thread"] = threading.Thread(target=_accept_loop, args=(sock,), daemon=True)
114
+ _server["thread"].start()
115
+ bpy.app.timers.register(_pump, persistent=True)
116
+ print("adobe-mcp bridge listening on 127.0.0.1:%d" % PORT)
117
+
118
+
119
+ def unregister():
120
+ _server["stop"] = True
121
+ if _server["sock"]:
122
+ try:
123
+ _server["sock"].close()
124
+ except OSError:
125
+ pass
126
+ _server["sock"] = None
127
+ if bpy.app.timers.is_registered(_pump):
128
+ bpy.app.timers.unregister(_pump)
129
+
130
+
131
+ if __name__ == "__main__":
132
+ register()
@@ -1,11 +1,17 @@
1
1
  <?xml version="1.0" encoding="UTF-8"?>
2
- <ExtensionManifest Version="7.0" ExtensionBundleId="com.ajsmonty.adobemcp" ExtensionBundleVersion="1.0.0" ExtensionBundleName="MCP Bridge" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
2
+ <!-- adobe-mcp bridge for Premiere Pro (PPRO) and After Effects (AEFT).
3
+ .background starts invisibly when the app opens, so nothing has to be opened by hand;
4
+ .panel (Window → Extensions → MCP Bridge) shows status and also works if auto-start is off.
5
+ Both run main.js; a command is claimed by an atomic rename, so it runs exactly once. -->
6
+ <ExtensionManifest Version="7.0" ExtensionBundleId="com.ajsmonty.adobemcp" ExtensionBundleVersion="1.2.0" ExtensionBundleName="MCP Bridge" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
3
7
  <ExtensionList>
4
- <Extension Id="com.ajsmonty.adobemcp.panel" Version="1.0.0" />
8
+ <Extension Id="com.ajsmonty.adobemcp.panel" Version="1.2.0" />
9
+ <Extension Id="com.ajsmonty.adobemcp.background" Version="1.2.0" />
5
10
  </ExtensionList>
6
11
  <ExecutionEnvironment>
7
12
  <HostList>
8
13
  <Host Name="PPRO" Version="[13.0,99.9]" />
14
+ <Host Name="AEFT" Version="[22.0,99.9]" />
9
15
  </HostList>
10
16
  <LocaleList>
11
17
  <Locale Code="All" />
@@ -40,5 +46,33 @@
40
46
  </UI>
41
47
  </DispatchInfo>
42
48
  </Extension>
49
+ <Extension Id="com.ajsmonty.adobemcp.background">
50
+ <DispatchInfo>
51
+ <Resources>
52
+ <MainPath>./index.html</MainPath>
53
+ <CEFCommandLine>
54
+ <Parameter>--allow-file-access-from-files</Parameter>
55
+ <Parameter>--enable-nodejs</Parameter>
56
+ <Parameter>--mixed-context</Parameter>
57
+ </CEFCommandLine>
58
+ </Resources>
59
+ <Lifecycle>
60
+ <AutoVisible>false</AutoVisible>
61
+ <StartOn>
62
+ <Event>com.adobe.csxs.events.ApplicationActivate</Event>
63
+ <Event>applicationActivate</Event>
64
+ </StartOn>
65
+ </Lifecycle>
66
+ <UI>
67
+ <Type>Custom</Type>
68
+ <Geometry>
69
+ <Size>
70
+ <Height>1</Height>
71
+ <Width>1</Width>
72
+ </Size>
73
+ </Geometry>
74
+ </UI>
75
+ </DispatchInfo>
76
+ </Extension>
43
77
  </DispatchInfoList>
44
78
  </ExtensionManifest>
@@ -1,24 +1,43 @@
1
- // adobe-mcp Premiere bridge panel.
2
- // Polls <workspace>/ppro-bridge for cmd_*.json files ({jsx: "/path/to/script.jsx"}),
3
- // evalFiles them in Premiere's ExtendScript engine (the harnessed JSX writes its own
4
- // result file), and maintains a heartbeat so the MCP server knows the panel is alive.
1
+ // adobe-mcp bridge panel for Premiere Pro and After Effects.
2
+ //
3
+ // Watches ~/AdobeMCP/<app>-bridge (ppro-bridge or ae-bridge; a fixed location because the panel
4
+ // cannot read the MCP server's environment) for cmd_*.json files: {jsx: "<script path>", result:
5
+ // "<result path>"}. It evalFiles the script in the app's ExtendScript engine and writes the string
6
+ // the harness returns to the result path, so the app itself never needs file-write permission. A
7
+ // heartbeat file tells the server the panel is alive.
8
+ //
9
+ // The visible panel and the invisible background copy both run this file; each command is claimed
10
+ // with an atomic rename first, so it runs exactly once.
5
11
  (function () {
6
12
  var nodeRequire = (typeof cep_node !== "undefined" && cep_node.require) ? cep_node.require : (typeof require !== "undefined" ? require : null);
7
- var statusEl = document.getElementById("status");
8
- var countEl = document.getElementById("count");
9
- var lastEl = document.getElementById("last");
13
+ var el = function (id) { return (typeof document !== "undefined" && document.getElementById(id)) || { set textContent(v) {}, set className(v) {} }; };
14
+ var statusEl = el("status"), countEl = el("count"), lastEl = el("last");
10
15
  if (!nodeRequire) { statusEl.textContent = "Node disabled — check --enable-nodejs"; return; }
11
16
 
12
17
  var fs = nodeRequire("fs");
13
18
  var pathMod = nodeRequire("path");
14
19
  var os = nodeRequire("os");
15
- var BRIDGE = pathMod.join(os.homedir(), "AdobeMCP", "ppro-bridge");
20
+
21
+ var host = "PPRO";
22
+ try { host = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appName || host; } catch (e) {}
23
+ var DIRS = { PPRO: "ppro-bridge", AEFT: "ae-bridge" };
24
+ var BRIDGE = pathMod.join(os.homedir(), "AdobeMCP", DIRS[host] || (String(host).toLowerCase() + "-bridge"));
16
25
  try { fs.mkdirSync(BRIDGE, { recursive: true }); } catch (e) {}
17
26
 
18
27
  var count = 0;
19
28
  statusEl.textContent = "listening: " + BRIDGE;
20
29
  statusEl.className = "ok";
21
30
 
31
+ function writeResult(path, text) {
32
+ if (!path) return;
33
+ try {
34
+ if (fs.existsSync(path) && fs.readFileSync(path, "utf8").length) return; // already reported
35
+ fs.writeFileSync(path + ".tmp", text, "utf8");
36
+ fs.renameSync(path + ".tmp", path); // the server never sees a half-written result
37
+ } catch (e) {}
38
+ }
39
+ function fail(path, msg) { writeResult(path, JSON.stringify({ ok: false, error: msg, line: 0 })); }
40
+
22
41
  setInterval(function heartbeat() {
23
42
  try { fs.writeFileSync(pathMod.join(BRIDGE, "heartbeat"), String(Date.now())); } catch (e) {}
24
43
  }, 1000);
@@ -29,21 +48,30 @@
29
48
  for (var i = 0; i < entries.length; i++) {
30
49
  var name = entries[i];
31
50
  if (name.indexOf("cmd_") !== 0 || !/\.json$/.test(name)) continue;
32
- var full = pathMod.join(BRIDGE, name);
51
+ var full = pathMod.join(BRIDGE, name), mine = full + ".run";
52
+ try { fs.renameSync(full, mine); } catch (e) { continue; } // the other copy took it
33
53
  var cmd = null;
34
- try { cmd = JSON.parse(fs.readFileSync(full, "utf8")); } catch (e) { continue; } // may still be writing
35
- try { fs.unlinkSync(full); } catch (e) {}
54
+ try { cmd = JSON.parse(fs.readFileSync(mine, "utf8")); } catch (e) {}
55
+ try { fs.unlinkSync(mine); } catch (e) {}
36
56
  if (!cmd || !cmd.jsx) continue;
37
57
  count++;
38
58
  countEl.textContent = String(count);
39
- lastEl.textContent = "last: " + cmd.jsx.split("/").pop();
40
- var esc = cmd.jsx.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
41
- window.__adobe_cep__.evalScript("$.evalFile(new File('" + esc + "'))", function (r) {
42
- if (r === "EvalScript error.") {
43
- lastEl.textContent = "last: evalScript ERROR";
44
- lastEl.className = "err";
45
- }
46
- });
59
+ lastEl.textContent = "last: " + String(cmd.jsx).split(/[\\/]/).pop();
60
+ (function (cmd) {
61
+ var esc = String(cmd.jsx).replace(/\\/g, "\\\\").replace(/'/g, "\\'");
62
+ window.__adobe_cep__.evalScript("$.evalFile(new File('" + esc + "'))", function (r) {
63
+ if (r === "EvalScript error.") {
64
+ lastEl.textContent = "last: script error";
65
+ lastEl.className = "err";
66
+ fail(cmd.result, "The script could not run in " + host + " (a syntax error, or an error outside the harness).");
67
+ } else if (typeof r === "string" && r.charAt(0) === "{") {
68
+ writeResult(cmd.result, r);
69
+ } else {
70
+ // Older harnesses write their own result file; give them a moment before reporting.
71
+ setTimeout(function () { fail(cmd.result, "No result came back from " + host + " (got: " + String(r).slice(0, 200) + ")."); }, 1500);
72
+ }
73
+ });
74
+ })(cmd);
47
75
  }
48
- }, 250);
76
+ }, 200);
49
77
  })();