@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,393 @@
1
+ // Premiere Pro: editing tools + Adobe Media Encoder (driven through Premiere's encoder API).
2
+ // Ported from the Barrows line of adobe-mcp (contributions by Derrin Byrne).
3
+ import { z } from "zod";
4
+ import path from "node:path";
5
+ import { runJSX } from "../core/bridge.mjs";
6
+ import { lit, esPath, walk, resolvePreset } from "../core/helpers.mjs";
7
+
8
+ const PP_LIB = `
9
+ function __q(s) { s = String(s); var o = '"'; for (var i = 0; i < s.length; i++) { var c = s.charAt(i), n = s.charCodeAt(i);
10
+ if (c == '"') o += '\\\\"'; else if (c == '\\\\') o += '\\\\\\\\'; else if (c == '\\n') o += '\\\\n'; else if (c == '\\r') o += '\\\\r';
11
+ else if (n < 32) o += ' '; else o += c; } return o + '"'; }
12
+ function norm(p) { return String(p).replace(/\\\\/g, '/').toLowerCase(); }
13
+ function getSeq(name) {
14
+ if (!name) { if (!app.project.activeSequence) throw new Error('No active sequence. Open one or pass sequence.'); return app.project.activeSequence; }
15
+ var names = [];
16
+ for (var i = 0; i < app.project.sequences.numSequences; i++) { var s = app.project.sequences[i]; if (s.name === name) return s; names.push(s.name); }
17
+ throw new Error('Sequence "' + name + '" not found. Sequences: ' + names.join(', '));
18
+ }
19
+ function walkItems(bin, fn) {
20
+ bin = bin || app.project.rootItem;
21
+ for (var i = 0; i < bin.children.numItems; i++) {
22
+ var c = bin.children[i];
23
+ if (c.type === ProjectItemType.BIN) { var r = walkItems(c, fn); if (r) return r; }
24
+ else if (fn(c)) return c;
25
+ }
26
+ return null;
27
+ }
28
+ function findItem(key) {
29
+ var k = norm(key);
30
+ return walkItems(null, function (c) {
31
+ if (c.name === key) return true;
32
+ try { return c.getMediaPath && norm(c.getMediaPath()) === k; } catch (e) { return false; }
33
+ });
34
+ }
35
+ function itemFor(key) {
36
+ var it = findItem(key);
37
+ if (it) return it;
38
+ var f = new File(key);
39
+ if (!f.exists) throw new Error('No project item named "' + key + '" and no file at that path.');
40
+ app.project.importFiles([f.fsName], true, app.project.rootItem, false);
41
+ it = findItem(f.fsName) || findItem(decodeURI(f.name));
42
+ if (!it) throw new Error('Imported ' + f.fsName + ' but could not find it in the project.');
43
+ return it;
44
+ }
45
+ function T(sec) { var t = new Time(); t.seconds = sec; return t; }
46
+ function trackOf(seq, kind, n) {
47
+ var list = kind === 'audio' ? seq.audioTracks : seq.videoTracks;
48
+ if (n < 1 || n > list.numTracks) throw new Error(kind + ' track ' + n + ' does not exist (sequence has ' + list.numTracks + ').');
49
+ return list[n - 1];
50
+ }
51
+ function clipList(tr) {
52
+ var out = [];
53
+ for (var i = 0; i < tr.clips.numItems; i++) { var c = tr.clips[i];
54
+ out.push({ index: i + 1, name: c.name, start: Math.round(c.start.seconds * 1000) / 1000, end: Math.round(c.end.seconds * 1000) / 1000,
55
+ in_point: Math.round(c.inPoint.seconds * 1000) / 1000, out_point: Math.round(c.outPoint.seconds * 1000) / 1000 }); }
56
+ return out;
57
+ }
58
+ `;
59
+
60
+ const seqArg = z.string().optional().describe("Sequence name (default: the active sequence).");
61
+
62
+ export function register(server, { text, errText }) {
63
+ server.registerTool(
64
+ "ppro_insert_clip",
65
+ {
66
+ title: "Place a clip on a Premiere timeline",
67
+ description:
68
+ "Put a project item (by name) or a media file (by path; imported if needed) onto a sequence track at a " +
69
+ "time, as an overwrite or a ripple insert. Optionally use only part of the source via source in/out.",
70
+ inputSchema: {
71
+ item: z.string().describe("Project item name or absolute media file path."),
72
+ sequence: seqArg,
73
+ track_kind: z.enum(["video", "audio"]).optional().describe("Default video."),
74
+ track: z.number().int().optional().describe("1-based track number (default 1)."),
75
+ time_seconds: z.number().describe("Where on the timeline to place it."),
76
+ mode: z.enum(["overwrite", "insert"]).optional().describe("overwrite (default) or insert (pushes later clips right)."),
77
+ source_in_seconds: z.number().optional(),
78
+ source_out_seconds: z.number().optional(),
79
+ },
80
+ },
81
+ async (a) => {
82
+ try {
83
+ const jsx = `${PP_LIB}
84
+ var seq = getSeq(${lit(a.sequence || null)}), it = itemFor(${lit(esPath(a.item))});
85
+ if (${lit(a.source_in_seconds ?? null)} !== null) it.setInPoint(${lit(a.source_in_seconds ?? 0)}, 4);
86
+ if (${lit(a.source_out_seconds ?? null)} !== null) it.setOutPoint(${lit(a.source_out_seconds ?? 0)}, 4);
87
+ var tr = trackOf(seq, ${lit(a.track_kind || "video")}, ${lit(a.track || 1)});
88
+ if (${lit(a.mode || "overwrite")} === 'insert') tr.insertClip(it, ${lit(a.time_seconds)}); else tr.overwriteClip(it, ${lit(a.time_seconds)});
89
+ return { sequence: seq.name, item: it.name, track_clips: clipList(tr) };`;
90
+ return text(await runJSX("ppro", jsx, 120000));
91
+ } catch (e) {
92
+ return errText(e);
93
+ }
94
+ }
95
+ );
96
+
97
+ server.registerTool(
98
+ "ppro_edit_clip",
99
+ {
100
+ title: "Trim, move, rename, disable or remove a timeline clip",
101
+ description:
102
+ "Edit one clip on a sequence track, found by its 1-based index on that track or by name. Actions: " +
103
+ "set_times (timeline start/end and/or source in/out), move (shift by seconds), remove (optionally " +
104
+ "ripple), rename, enable/disable. Returns the track's clips afterwards — call with action 'list' to see them first.",
105
+ inputSchema: {
106
+ sequence: seqArg,
107
+ track_kind: z.enum(["video", "audio"]).optional(),
108
+ track: z.number().int().optional().describe("1-based (default 1)."),
109
+ action: z.enum(["list", "set_times", "move", "remove", "rename", "disable", "enable"]),
110
+ clip_index: z.number().int().optional().describe("1-based index on the track."),
111
+ clip_name: z.string().optional(),
112
+ start_seconds: z.number().optional(),
113
+ end_seconds: z.number().optional(),
114
+ in_seconds: z.number().optional(),
115
+ out_seconds: z.number().optional(),
116
+ move_by_seconds: z.number().optional(),
117
+ ripple: z.boolean().optional().describe("For remove: close the gap (default false)."),
118
+ new_name: z.string().optional(),
119
+ },
120
+ },
121
+ async (a) => {
122
+ try {
123
+ const jsx = `${PP_LIB}
124
+ var seq = getSeq(${lit(a.sequence || null)}), tr = trackOf(seq, ${lit(a.track_kind || "video")}, ${lit(a.track || 1)});
125
+ var act = ${lit(a.action)};
126
+ if (act !== 'list') {
127
+ var c = null, idx = ${lit(a.clip_index ?? null)}, nm = ${lit(a.clip_name ?? null)};
128
+ if (idx !== null) c = tr.clips[idx - 1];
129
+ else if (nm !== null) for (var i = 0; i < tr.clips.numItems; i++) if (tr.clips[i].name === nm) { c = tr.clips[i]; break; }
130
+ if (!c) throw new Error('Clip not found on that track. Clips: ' + clipList(tr).length);
131
+ if (act === 'set_times') {
132
+ var o = ${lit({ s: a.start_seconds ?? null, e: a.end_seconds ?? null, i: a.in_seconds ?? null, ot: a.out_seconds ?? null })};
133
+ if (o.i !== null) c.inPoint = T(o.i); if (o.ot !== null) c.outPoint = T(o.ot);
134
+ if (o.s !== null) c.start = T(o.s); if (o.e !== null) c.end = T(o.e);
135
+ } else if (act === 'move') c.move(T(${lit(a.move_by_seconds ?? 0)}));
136
+ else if (act === 'remove') c.remove(${a.ripple ? 1 : 0}, 1);
137
+ else if (act === 'rename') c.name = ${lit(a.new_name || "")};
138
+ else if (act === 'disable') c.disabled = true;
139
+ else if (act === 'enable') c.disabled = false;
140
+ }
141
+ return { sequence: seq.name, track_clips: clipList(tr) };`;
142
+ return text(await runJSX("ppro", jsx, 120000));
143
+ } catch (e) {
144
+ return errText(e);
145
+ }
146
+ }
147
+ );
148
+
149
+ server.registerTool(
150
+ "ppro_add_markers",
151
+ {
152
+ title: "Add markers to a Premiere sequence",
153
+ description: "Add sequence markers (time, name, comment, optional duration and colour index 0–7). Good for review notes, chapters or beat points.",
154
+ inputSchema: {
155
+ sequence: seqArg,
156
+ markers: z.array(z.object({
157
+ time_seconds: z.number(),
158
+ name: z.string().optional(),
159
+ comment: z.string().optional(),
160
+ duration_seconds: z.number().optional(),
161
+ color_index: z.number().int().min(0).max(7).optional(),
162
+ })).min(1),
163
+ },
164
+ },
165
+ async ({ sequence, markers }) => {
166
+ try {
167
+ const jsx = `${PP_LIB}
168
+ var seq = getSeq(${lit(sequence || null)}), ms = ${lit(markers)}, n = 0;
169
+ for (var i = 0; i < ms.length; i++) { var m = seq.markers.createMarker(ms[i].time_seconds);
170
+ if (ms[i].name) m.name = ms[i].name; if (ms[i].comment) m.comments = ms[i].comment;
171
+ if (ms[i].duration_seconds) m.end = ms[i].time_seconds + ms[i].duration_seconds;
172
+ if (ms[i].color_index !== undefined && m.setColorByIndex) m.setColorByIndex(ms[i].color_index);
173
+ n++; }
174
+ return { sequence: seq.name, added: n, total_markers: seq.markers.numMarkers };`;
175
+ return text(await runJSX("ppro", jsx, 120000));
176
+ } catch (e) {
177
+ return errText(e);
178
+ }
179
+ }
180
+ );
181
+
182
+ server.registerTool(
183
+ "ppro_import_captions",
184
+ {
185
+ title: "Import captions into a Premiere sequence",
186
+ description: "Import an .srt (or other caption file) and create a caption track on the sequence from it.",
187
+ inputSchema: {
188
+ caption_path: z.string().describe("Absolute path to the .srt file."),
189
+ sequence: seqArg,
190
+ start_seconds: z.number().optional().describe("Where the captions start (default 0)."),
191
+ },
192
+ },
193
+ async ({ caption_path, sequence, start_seconds }) => {
194
+ try {
195
+ const jsx = `${PP_LIB}
196
+ var seq = getSeq(${lit(sequence || null)}), it = itemFor(${lit(esPath(caption_path))});
197
+ var fmt = (typeof Sequence !== 'undefined' && Sequence.CAPTION_FORMAT_SUBTITLE) ? Sequence.CAPTION_FORMAT_SUBTITLE : 'Subtitle Default';
198
+ var ok = seq.createCaptionTrack(it, ${lit(start_seconds ?? 0)}, fmt);
199
+ return { sequence: seq.name, caption_item: it.name, created: !!ok };`;
200
+ return text(await runJSX("ppro", jsx, 120000));
201
+ } catch (e) {
202
+ return errText(e);
203
+ }
204
+ }
205
+ );
206
+
207
+ server.registerTool(
208
+ "ppro_add_mogrt",
209
+ {
210
+ title: "Add a motion graphics template (.mogrt) and set its fields",
211
+ description:
212
+ "Place a .mogrt on the timeline and fill its editable parameters by display name (text fields, " +
213
+ "numbers, checkboxes). If a name doesn't match, the result lists the template's parameter names.",
214
+ inputSchema: {
215
+ mogrt_path: z.string().describe("Absolute path to the .mogrt file."),
216
+ sequence: seqArg,
217
+ time_seconds: z.number().optional().describe("Default 0."),
218
+ video_track: z.number().int().optional().describe("1-based video track (default 2, above the main footage)."),
219
+ fields: z.record(z.union([z.string(), z.number(), z.boolean()])).optional().describe("{ parameterDisplayName: value }"),
220
+ duration_seconds: z.number().optional().describe("Set the clip's length."),
221
+ },
222
+ },
223
+ async (a) => {
224
+ try {
225
+ const jsx = `${PP_LIB}
226
+ var seq = getSeq(${lit(a.sequence || null)});
227
+ var ticks = String(Math.round(${lit(a.time_seconds ?? 0)} * 254016000000));
228
+ var clip = seq.importMGT(${lit(esPath(a.mogrt_path))}, ticks, ${lit((a.video_track ?? 2) - 1)}, 0);
229
+ if (!clip) throw new Error('Premiere did not place the .mogrt (check the path and that video track ' + ${lit(a.video_track ?? 2)} + ' exists).');
230
+ if (${lit(a.duration_seconds ?? null)} !== null) clip.end = T(clip.start.seconds + ${lit(a.duration_seconds ?? 0)});
231
+ var comp = clip.getMGTComponent(), fields = ${lit(a.fields || {})}, set = [], unknown = [], names = [];
232
+ for (var i = 0; comp && i < comp.properties.numItems; i++) names.push(comp.properties[i].displayName);
233
+ for (var key in fields) {
234
+ var p = null;
235
+ for (var j = 0; comp && j < comp.properties.numItems; j++) if (comp.properties[j].displayName === key) { p = comp.properties[j]; break; }
236
+ if (!p) { unknown.push(key); continue; }
237
+ var cur = p.getValue(), val = fields[key];
238
+ if (typeof cur === 'string' && cur.indexOf('textEditValue') >= 0) {
239
+ val = cur.replace(/"textEditValue"\\s*:\\s*"(?:[^"\\\\]|\\\\.)*"/, '"textEditValue":' + __q(val));
240
+ }
241
+ p.setValue(val, true); set.push(key);
242
+ }
243
+ return { clip: clip.name, fields_set: set, unknown_fields: unknown, available_fields: names };`;
244
+ return text(await runJSX("ppro", jsx, 120000));
245
+ } catch (e) {
246
+ return errText(e);
247
+ }
248
+ }
249
+ );
250
+
251
+ server.registerTool(
252
+ "ppro_relink_media",
253
+ {
254
+ title: "Find and relink offline media in Premiere",
255
+ description:
256
+ "List offline (missing) media in the project and search a folder for files with the same names. " +
257
+ "dry_run (default true) only reports the matches; set dry_run false to relink them.",
258
+ inputSchema: {
259
+ search_folder: z.string().optional().describe("Folder to search (recursively). Omit to just list offline media."),
260
+ dry_run: z.boolean().optional(),
261
+ },
262
+ },
263
+ async ({ search_folder, dry_run }) => {
264
+ try {
265
+ const offline = await runJSX("ppro", `${PP_LIB}
266
+ var out = [];
267
+ walkItems(null, function (c) { try { if (c.isOffline && c.isOffline()) out.push({ id: c.nodeId, name: c.name, path: c.getMediaPath() }); } catch (e) {} return false; });
268
+ return out;`, 120000);
269
+ if (!search_folder || !offline.length) return text({ offline_count: offline.length, offline });
270
+ const byName = new Map();
271
+ for (const f of walk(search_folder, { maxDepth: 12, maxFiles: 200000 })) {
272
+ const k = path.basename(f).toLowerCase();
273
+ if (!byName.has(k)) byName.set(k, f);
274
+ }
275
+ const plan = offline.map((o) => {
276
+ const base = (o.path ? o.path.split(/[\\/]/).pop() : o.name).toLowerCase();
277
+ return { ...o, new_path: byName.get(base) || byName.get(o.name.toLowerCase()) || null };
278
+ });
279
+ const matched = plan.filter((p) => p.new_path);
280
+ if (dry_run !== false || !matched.length)
281
+ return text({ dry_run: true, offline: plan.length, matches_found: matched.length, plan, note: "Run again with dry_run: false to relink." });
282
+ const r = await runJSX("ppro", `${PP_LIB}
283
+ var plan = ${lit(matched.map((m) => ({ id: m.id, p: esPath(m.new_path) })))}, done = [], failed = [];
284
+ for (var i = 0; i < plan.length; i++) {
285
+ var it = walkItems(null, function (c) { return c.nodeId === plan[i].id; });
286
+ try { if (it && it.canChangeMediaPath()) { it.changeMediaPath(new File(plan[i].p).fsName, true); done.push(it.name); } else failed.push(plan[i].p); }
287
+ catch (e) { failed.push(plan[i].p + ': ' + e); }
288
+ }
289
+ return { relinked: done.length, failed: failed };`, 300000);
290
+ return text({ ...r, still_missing: plan.filter((p) => !p.new_path).map((p) => p.name) });
291
+ } catch (e) {
292
+ return errText(e);
293
+ }
294
+ }
295
+ );
296
+
297
+ // ---------------- Adobe Media Encoder (via Premiere's encoder API) ----------------
298
+ server.registerTool(
299
+ "ame_queue_sequence",
300
+ {
301
+ title: "Send a Premiere sequence to Media Encoder",
302
+ description:
303
+ "Queue a sequence in Adobe Media Encoder with an encoder preset (a preset name like 'Match Source - " +
304
+ "Adaptive High Bitrate' or a full .epr path), and optionally start encoding. Premiere stays free to keep " +
305
+ "editing. Needs Premiere open (Media Encoder launches automatically).",
306
+ inputSchema: {
307
+ output_path: z.string().describe("Absolute output file path including extension, e.g. .../promo.mp4"),
308
+ preset: z.string().optional().describe("Preset name or .epr path (default: Match Source high bitrate H.264)."),
309
+ sequence: seqArg,
310
+ range: z.enum(["entire", "in_out", "work_area"]).optional().describe("Default entire."),
311
+ start: z.boolean().optional().describe("Start the Media Encoder queue now (default true)."),
312
+ },
313
+ },
314
+ async (a) => {
315
+ try {
316
+ const preset = resolvePreset(a.preset);
317
+ const jsx = `${PP_LIB}
318
+ var seq = getSeq(${lit(a.sequence || null)});
319
+ app.encoder.launchEncoder();
320
+ var r = ${lit(a.range || "entire")}, wa = r === 'in_out' ? app.encoder.ENCODE_IN_TO_OUT : (r === 'work_area' ? app.encoder.ENCODE_WORKAREA : app.encoder.ENCODE_ENTIRE);
321
+ var job = app.encoder.encodeSequence(seq, ${lit(esPath(a.output_path))}, ${lit(esPath(preset))}, wa, 1);
322
+ if (${lit(a.start !== false)}) app.encoder.startBatch();
323
+ return { sequence: seq.name, job_id: job, preset: ${lit(path.basename(preset))}, output: ${lit(a.output_path)}, started: ${lit(a.start !== false)} };`;
324
+ return text(await runJSX("ppro", jsx, 180000));
325
+ } catch (e) {
326
+ return errText(e);
327
+ }
328
+ }
329
+ );
330
+
331
+ server.registerTool(
332
+ "ame_encode_files",
333
+ {
334
+ title: "Batch-encode media files with Media Encoder",
335
+ description:
336
+ "Queue media files (videos, image sequences, audio) in Adobe Media Encoder with one preset — e.g. make " +
337
+ "screen-ready H.264 versions of a folder of renders. Pass files or a folder. Needs Premiere open " +
338
+ "(it's how Claude reaches Media Encoder).",
339
+ inputSchema: {
340
+ files: z.array(z.string()).optional(),
341
+ folder: z.string().optional().describe("Encode every video file in this folder (not recursive)."),
342
+ output_folder: z.string(),
343
+ preset: z.string().optional().describe("Preset name or .epr path."),
344
+ output_extension: z.string().optional().describe("Extension for outputs (default .mp4); should match the preset."),
345
+ suffix: z.string().optional().describe("Added to each output name (default '_encoded')."),
346
+ start: z.boolean().optional().describe("Start the queue now (default true)."),
347
+ },
348
+ },
349
+ async (a) => {
350
+ try {
351
+ const preset = resolvePreset(a.preset);
352
+ let files = a.files || [];
353
+ if (a.folder)
354
+ files = files.concat(walk(a.folder, { maxDepth: 0, filter: (f) => /\.(mov|mp4|m4v|mxf|avi|mkv|wav|aif+|mp3|gif)$/i.test(f) }));
355
+ if (!files.length) throw new Error("No input files.");
356
+ const ext = (a.output_extension || ".mp4").replace(/^(?!\.)/, ".");
357
+ const jobs = files.map((f) => ({
358
+ src: esPath(f),
359
+ out: esPath(path.join(a.output_folder, path.basename(f, path.extname(f)) + (a.suffix ?? "_encoded") + ext)),
360
+ }));
361
+ const jsx = `${PP_LIB}
362
+ var jobs = ${lit(jobs)}, ids = [];
363
+ new Folder(${lit(esPath(a.output_folder))}).create();
364
+ app.encoder.launchEncoder();
365
+ for (var i = 0; i < jobs.length; i++) ids.push(app.encoder.encodeFile(jobs[i].src, jobs[i].out, ${lit(esPath(preset))}, 1));
366
+ if (${lit(a.start !== false)}) app.encoder.startBatch();
367
+ return { queued: jobs.length, job_ids: ids, preset: ${lit(path.basename(preset))}, outputs: jobs };`;
368
+ return text(await runJSX("ppro", jsx, 180000));
369
+ } catch (e) {
370
+ return errText(e);
371
+ }
372
+ }
373
+ );
374
+
375
+ server.registerTool(
376
+ "ame_list_presets",
377
+ {
378
+ title: "List Media Encoder presets",
379
+ description: "List encoder presets (.epr) found in Premiere, Media Encoder and the user's custom preset folders, optionally filtered by name.",
380
+ inputSchema: { filter: z.string().optional() },
381
+ },
382
+ async ({ filter }) => {
383
+ try {
384
+ const { findEprPresets } = await import("../core/helpers.mjs");
385
+ const all = findEprPresets(filter || undefined);
386
+ const uniq = [...new Map(all.map((f) => [path.basename(f, ".epr"), f])).entries()].slice(0, 200);
387
+ return text({ count: uniq.length, presets: uniq.map(([name, p]) => ({ name, path: p })) });
388
+ } catch (e) {
389
+ return errText(e);
390
+ }
391
+ }
392
+ );
393
+ }
@@ -0,0 +1,277 @@
1
+ // Photoshop (registerPS): mockup smart-object replacement, batch resize/export.
2
+ // Illustrator (registerAI): data merge from a spreadsheet, recolour to a palette.
3
+ // Ported from the Barrows line of adobe-mcp (contributions by Derrin Byrne).
4
+ // Illustrator: spreadsheet-driven merges, recolour to a brand palette.
5
+ import { z } from "zod";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { runJSX } from "../core/bridge.mjs";
9
+ import { lit, esPath, loadRows, safeName } from "../core/helpers.mjs";
10
+
11
+ const PS_LIB = `
12
+ function findLayer(container, name) {
13
+ for (var i = 0; i < container.layers.length; i++) {
14
+ var L = container.layers[i];
15
+ if (L.name === name) return L;
16
+ if (L.typename === 'LayerSet') { var r = findLayer(L, name); if (r) return r; }
17
+ }
18
+ return null;
19
+ }
20
+ function smartNames(container, out) {
21
+ out = out || [];
22
+ for (var i = 0; i < container.layers.length; i++) { var L = container.layers[i];
23
+ if (L.typename === 'LayerSet') smartNames(L, out); else if (L.kind == LayerKind.SMARTOBJECT) out.push(L.name); }
24
+ return out;
25
+ }
26
+ function replaceSO(doc, layer, filePath) {
27
+ doc.activeLayer = layer;
28
+ var d = new ActionDescriptor();
29
+ d.putPath(charIDToTypeID('null'), new File(filePath));
30
+ executeAction(stringIDToTypeID('placedLayerReplaceContents'), d, DialogModes.NO);
31
+ }
32
+ function saveOut(doc, outPath, quality) {
33
+ var f = new File(outPath), ext = outPath.split('.').pop().toLowerCase();
34
+ new Folder(f.parent.fsName).create();
35
+ if (ext === 'png') { var o = new PNGSaveOptions(); o.compression = 6; doc.saveAs(f, o, true, Extension.LOWERCASE); }
36
+ else if (ext === 'jpg' || ext === 'jpeg') { var j = new JPEGSaveOptions(); j.quality = quality || 10; j.embedColorProfile = true;
37
+ var dup = doc.duplicate(); dup.flatten(); if (dup.mode != DocumentMode.RGB) dup.changeMode(ChangeMode.RGB);
38
+ dup.saveAs(f, j, true, Extension.LOWERCASE); dup.close(SaveOptions.DONOTSAVECHANGES); }
39
+ else if (ext === 'psd') { doc.saveAs(f, new PhotoshopSaveOptions(), true, Extension.LOWERCASE); }
40
+ else if (ext === 'tif' || ext === 'tiff') { doc.saveAs(f, new TiffSaveOptions(), true, Extension.LOWERCASE); }
41
+ else throw new Error('Unsupported output format: ' + ext);
42
+ return f.fsName;
43
+ }
44
+ `;
45
+
46
+ const AI_LIB = `
47
+ function hexToRGB(h) { h = h.replace('#', ''); if (h.length === 3) h = h.charAt(0)+h.charAt(0)+h.charAt(1)+h.charAt(1)+h.charAt(2)+h.charAt(2);
48
+ return [parseInt(h.substr(0, 2), 16), parseInt(h.substr(2, 2), 16), parseInt(h.substr(4, 2), 16)]; }
49
+ function toRGB(c) {
50
+ if (!c) return null;
51
+ if (c.typename === 'RGBColor') return [c.red, c.green, c.blue];
52
+ if (c.typename === 'CMYKColor') { var k = c.black / 100; return [255 * (1 - c.cyan / 100) * (1 - k), 255 * (1 - c.magenta / 100) * (1 - k), 255 * (1 - c.yellow / 100) * (1 - k)]; }
53
+ if (c.typename === 'GrayColor') { var g = 255 * (1 - c.gray / 100); return [g, g, g]; }
54
+ if (c.typename === 'SpotColor') return toRGB(c.spot.color);
55
+ return null;
56
+ }
57
+ function hex(rgb) { var s = '#'; for (var i = 0; i < 3; i++) { var v = Math.round(rgb[i]).toString(16); s += (v.length < 2 ? '0' : '') + v; } return s.toUpperCase(); }
58
+ function findNamed(doc, name) {
59
+ try { return doc.pageItems.getByName(name); } catch (e) {}
60
+ for (var i = 0; i < doc.textFrames.length; i++) if (doc.textFrames[i].name === name) return doc.textFrames[i];
61
+ return null;
62
+ }
63
+ `;
64
+
65
+ export function registerPS(server, { text, errText, registerAsset }) {
66
+ server.registerTool(
67
+ "ps_replace_smart_object",
68
+ {
69
+ title: "Put artwork into a Photoshop mockup",
70
+ description:
71
+ "Open a mockup PSD, replace the contents of one or more smart-object layers (by layer name) with image " +
72
+ "files — e.g. drop a campaign visual onto a store fixture, screen or poster mockup — then save the result " +
73
+ "(.png/.jpg/.psd/.tif). The mockup file itself is not changed. If a layer name is wrong, the error lists " +
74
+ "the smart-object layers in the file.",
75
+ inputSchema: {
76
+ mockup_psd: z.string(),
77
+ replacements: z.array(z.object({ layer: z.string(), image_path: z.string() })).min(1),
78
+ output_path: z.string().describe("Extension chooses the format."),
79
+ jpg_quality: z.number().int().min(1).max(12).optional(),
80
+ keep_open: z.boolean().optional().describe("Leave the edited mockup open in Photoshop (default false)."),
81
+ },
82
+ },
83
+ async (a) => {
84
+ try {
85
+ const jsx = `${PS_LIB}
86
+ var doc = app.open(new File(${lit(esPath(a.mockup_psd))})), reps = ${lit(a.replacements.map((r) => ({ layer: r.layer, image: esPath(r.image_path) })))}, done = [];
87
+ try {
88
+ for (var i = 0; i < reps.length; i++) {
89
+ var L = findLayer(doc, reps[i].layer);
90
+ if (!L || L.kind != LayerKind.SMARTOBJECT) throw new Error('Smart object layer "' + reps[i].layer + '" not found. Smart objects: ' + smartNames(doc).join(', '));
91
+ if (!new File(reps[i].image).exists) throw new Error('Image not found: ' + reps[i].image);
92
+ replaceSO(doc, L, reps[i].image); done.push(reps[i].layer);
93
+ }
94
+ var out = saveOut(doc, ${lit(esPath(a.output_path))}, ${lit(a.jpg_quality ?? 10)});
95
+ } finally { if (!${lit(!!a.keep_open)}) doc.close(SaveOptions.DONOTSAVECHANGES); }
96
+ return { replaced: done, output: out };`;
97
+ const r = await runJSX("ps", jsx, 600000);
98
+ registerAsset?.({ app: "ps", kind: path.extname(a.output_path).slice(1), path: a.output_path, meta: { mockup: a.mockup_psd } });
99
+ return text(r);
100
+ } catch (e) {
101
+ return errText(e);
102
+ }
103
+ }
104
+ );
105
+
106
+ server.registerTool(
107
+ "ps_batch_export",
108
+ {
109
+ title: "Batch resize and export images in Photoshop",
110
+ description:
111
+ "Open each image/PSD, make sized versions and save them (.png/.jpg/.tif) — e.g. one visual at every " +
112
+ "screen size. fit: 'cover' fills the size and crops the overflow (centred); 'contain' fits inside and pads " +
113
+ "with pad_color; 'width'/'height' scale to that dimension only. Originals are not changed.",
114
+ inputSchema: {
115
+ files: z.array(z.string()).optional(),
116
+ folder: z.string().optional().describe("Use every image/PSD in this folder (not recursive)."),
117
+ sizes: z.array(z.object({
118
+ width: z.number().int(),
119
+ height: z.number().int(),
120
+ fit: z.enum(["cover", "contain", "width", "height"]).optional(),
121
+ suffix: z.string().optional().describe("Default _<w>x<h>."),
122
+ })).min(1),
123
+ format: z.enum(["png", "jpg", "tif"]).optional().describe("Default jpg."),
124
+ jpg_quality: z.number().int().min(1).max(12).optional(),
125
+ pad_color: z.string().optional().describe("Hex colour for 'contain' padding (default #000000)."),
126
+ output_folder: z.string(),
127
+ },
128
+ },
129
+ async (a) => {
130
+ try {
131
+ let files = a.files || [];
132
+ if (a.folder) files = files.concat(fs.readdirSync(a.folder).filter((f) => /\.(psd|psb|png|jpe?g|tiff?|webp)$/i.test(f)).map((f) => path.join(a.folder, f)));
133
+ if (!files.length) throw new Error("No input files.");
134
+ const fmt = a.format || "jpg";
135
+ const jobs = files.map((f) => ({ src: esPath(f), base: path.basename(f, path.extname(f)) }));
136
+ const jsx = `${PS_LIB}
137
+ var jobs = ${lit(jobs)}, sizes = ${lit(a.sizes)}, outDir = ${lit(esPath(a.output_folder))}, outs = [], errs = [];
138
+ var oldUnits = app.preferences.rulerUnits; app.preferences.rulerUnits = Units.PIXELS;
139
+ var pad = ${lit((a.pad_color || "#000000").replace("#", ""))};
140
+ try {
141
+ for (var j = 0; j < jobs.length; j++) {
142
+ var src;
143
+ try { src = app.open(new File(jobs[j].src)); } catch (e) { errs.push(jobs[j].src + ': ' + e); continue; }
144
+ for (var s = 0; s < sizes.length; s++) {
145
+ var S = sizes[s], fit = S.fit || 'cover', d = src.duplicate();
146
+ var w = d.width.as('px'), h = d.height.as('px');
147
+ if (fit === 'width') d.resizeImage(UnitValue(S.width, 'px'), null, null, ResampleMethod.BICUBICAUTOMATIC);
148
+ else if (fit === 'height') d.resizeImage(null, UnitValue(S.height, 'px'), null, ResampleMethod.BICUBICAUTOMATIC);
149
+ else {
150
+ var k = fit === 'cover' ? Math.max(S.width / w, S.height / h) : Math.min(S.width / w, S.height / h);
151
+ d.resizeImage(UnitValue(Math.round(w * k), 'px'), UnitValue(Math.round(h * k), 'px'), null, ResampleMethod.BICUBICAUTOMATIC);
152
+ if (fit === 'contain') { var c = new SolidColor(); c.rgb.hexValue = pad; app.backgroundColor = c; }
153
+ d.resizeCanvas(UnitValue(S.width, 'px'), UnitValue(S.height, 'px'), AnchorPosition.MIDDLECENTER);
154
+ }
155
+ var name = jobs[j].base + (S.suffix !== undefined ? S.suffix : ('_' + S.width + 'x' + S.height)) + '.' + ${lit(fmt)};
156
+ outs.push(saveOut(d, outDir + '/' + name, ${lit(a.jpg_quality ?? 10)}));
157
+ d.close(SaveOptions.DONOTSAVECHANGES);
158
+ }
159
+ src.close(SaveOptions.DONOTSAVECHANGES);
160
+ }
161
+ } finally { app.preferences.rulerUnits = oldUnits; }
162
+ return { written: outs.length, outputs: outs, errors: errs };`;
163
+ return text(await runJSX("ps", jsx, Math.max(300000, files.length * a.sizes.length * 30000)));
164
+ } catch (e) {
165
+ return errText(e);
166
+ }
167
+ }
168
+ );
169
+
170
+ }
171
+
172
+ export function registerAI(server, { text, errText, registerAsset }) {
173
+ server.registerTool(
174
+ "ai_data_merge",
175
+ {
176
+ title: "Make Illustrator versions from a spreadsheet",
177
+ description:
178
+ "For each row of a CSV/TSV (or inline rows): open an Illustrator template, fill named text frames and " +
179
+ "swap named placed images from columns, then export (.pdf/.png/.svg/.ai) — e.g. price cards, shelf " +
180
+ "talkers, store-specific signage. Name items in the Layers panel to target them. Test with max_rows: 1.",
181
+ inputSchema: {
182
+ template: z.string().describe("Absolute path to the .ai template."),
183
+ csv_path: z.string().optional(),
184
+ rows: z.array(z.record(z.string())).optional(),
185
+ text_columns: z.record(z.string()).optional().describe("{ itemName: columnName }"),
186
+ image_columns: z.record(z.string()).optional().describe("{ placedItemName: columnName holding an image path }"),
187
+ name_column: z.string().optional(),
188
+ format: z.enum(["pdf", "png", "svg", "ai"]).optional().describe("Default pdf."),
189
+ png_scale: z.number().optional().describe("PNG scale percent (default 100)."),
190
+ output_folder: z.string(),
191
+ max_rows: z.number().int().optional(),
192
+ },
193
+ },
194
+ async (a) => {
195
+ try {
196
+ let data = loadRows(a);
197
+ if (a.max_rows) data = data.slice(0, a.max_rows);
198
+ const fmt = a.format || "pdf";
199
+ const jobs = data.map((r, i) => ({
200
+ out: esPath(path.join(a.output_folder, `${safeName(a.name_column ? r[a.name_column] : `${path.basename(a.template, ".ai")}_${String(i + 1).padStart(3, "0")}`)}.${fmt}`)),
201
+ text: Object.fromEntries(Object.entries(a.text_columns || {}).map(([k, c]) => [k, r[c] ?? ""])),
202
+ img: Object.fromEntries(Object.entries(a.image_columns || {}).filter(([, c]) => r[c]).map(([k, c]) => [k, esPath(r[c])])),
203
+ }));
204
+ const jsx = `${AI_LIB}
205
+ var jobs = ${lit(jobs)}, tpl = new File(${lit(esPath(a.template))}), fmt = ${lit(fmt)}, outs = [], missing = {};
206
+ if (!tpl.exists) throw new Error('Template not found: ' + tpl.fsName);
207
+ new Folder(${lit(esPath(a.output_folder))}).create();
208
+ app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
209
+ for (var j = 0; j < jobs.length; j++) {
210
+ var doc = app.open(tpl);
211
+ try {
212
+ for (var n in jobs[j].text) { var it = findNamed(doc, n); if (it && it.typename === 'TextFrame') it.contents = jobs[j].text[n]; else missing[n] = true; }
213
+ for (var m in jobs[j].img) { var p = findNamed(doc, m); if (p && p.typename === 'PlacedItem') p.file = new File(jobs[j].img[m]); else missing[m] = true; }
214
+ var f = new File(jobs[j].out);
215
+ if (fmt === 'pdf') { var po = new PDFSaveOptions(); po.preserveEditability = false; doc.saveAs(f, po); }
216
+ else if (fmt === 'ai') doc.saveAs(f, new IllustratorSaveOptions());
217
+ else if (fmt === 'svg') { var so = new ExportOptionsSVG(); so.embedRasterImages = true; doc.exportFile(f, ExportType.SVG, so); }
218
+ else { var pn = new ExportOptionsPNG24(); pn.artBoardClipping = true; pn.horizontalScale = pn.verticalScale = ${lit(a.png_scale ?? 100)}; doc.exportFile(f, ExportType.PNG24, pn); }
219
+ outs.push(f.fsName);
220
+ } finally { doc.close(SaveOptions.DONOTSAVECHANGES); }
221
+ }
222
+ app.userInteractionLevel = UserInteractionLevel.DISPLAYALERTS;
223
+ var miss = []; for (var k in missing) miss.push(k);
224
+ return { written: outs.length, outputs: outs, items_not_found: miss };`;
225
+ return text(await runJSX("ai", jsx, Math.max(300000, jobs.length * 30000)));
226
+ } catch (e) {
227
+ return errText(e);
228
+ }
229
+ }
230
+ );
231
+
232
+ server.registerTool(
233
+ "ai_recolor_to_palette",
234
+ {
235
+ title: "Snap Illustrator colours to a brand palette",
236
+ description:
237
+ "Find every fill/stroke colour in the active document (paths, compound paths, text) and map each to the " +
238
+ "nearest colour in the given palette. dry_run (default true) only reports what would change, with " +
239
+ "off-palette colours and counts — useful as a brand check. Set dry_run false to apply (undoable).",
240
+ inputSchema: {
241
+ palette: z.array(z.string()).min(1).describe("Hex colours, e.g. ['#E30613', '#FFFFFF', '#1D1D1B']."),
242
+ dry_run: z.boolean().optional(),
243
+ tolerance: z.number().optional().describe("Colours within this RGB distance are treated as on-palette (default 6)."),
244
+ },
245
+ },
246
+ async ({ palette, dry_run, tolerance }) => {
247
+ try {
248
+ const jsx = `${AI_LIB}
249
+ if (!app.documents.length) throw new Error('No open document.');
250
+ var doc = app.activeDocument, pal = ${lit(palette)}, P = [], apply = ${lit(dry_run === false)}, tol = ${lit(tolerance ?? 6)};
251
+ for (var i = 0; i < pal.length; i++) P.push(hexToRGB(pal[i]));
252
+ var found = {}, changed = 0;
253
+ function nearest(rgb) { var best = 0, bd = 1e9; for (var i = 0; i < P.length; i++) { var d = Math.sqrt(Math.pow(rgb[0]-P[i][0],2)+Math.pow(rgb[1]-P[i][1],2)+Math.pow(rgb[2]-P[i][2],2)); if (d < bd) { bd = d; best = i; } } return { i: best, d: bd }; }
254
+ function handle(color, setter) {
255
+ var rgb = toRGB(color); if (!rgb) return;
256
+ var n = nearest(rgb), key = hex(rgb);
257
+ if (!found[key]) found[key] = { count: 0, nearest: pal[n.i], distance: Math.round(n.d), on_palette: n.d <= tol };
258
+ found[key].count++;
259
+ if (apply && n.d > 0.5) { var c = new RGBColor(); c.red = P[n.i][0]; c.green = P[n.i][1]; c.blue = P[n.i][2]; setter(c); changed++; }
260
+ }
261
+ for (var p = 0; p < doc.pathItems.length; p++) { var it = doc.pathItems[p]; if (it.locked) continue;
262
+ if (it.filled) handle(it.fillColor, function (c) { it.fillColor = c; });
263
+ if (it.stroked) handle(it.strokeColor, function (c) { it.strokeColor = c; }); }
264
+ var chars = 0;
265
+ for (var t = 0; t < doc.textFrames.length && chars < 20000; t++) { var runs = doc.textFrames[t].textRanges;
266
+ for (var r = 0; r < runs.length && chars < 20000; r++, chars++) { var ca = runs[r].characterAttributes;
267
+ handle(ca.fillColor, function (c) { ca.fillColor = c; }); } }
268
+ var off = [], list = [];
269
+ for (var k in found) { list.push({ color: k, uses: found[k].count, nearest: found[k].nearest, distance: found[k].distance, on_palette: found[k].on_palette }); if (!found[k].on_palette) off.push(k); }
270
+ return { document: doc.name, applied: apply, changes: changed, distinct_colors: list.length, off_palette: off, colors: list };`;
271
+ return text(await runJSX("ai", jsx, 600000));
272
+ } catch (e) {
273
+ return errText(e);
274
+ }
275
+ }
276
+ );
277
+ }