@ajsmonty/adobe-mcp 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AJ Montgomery
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,180 @@
1
+ # adobe-mcp — Adobe Creative Cloud MCP server (macOS)
2
+
3
+ Drives After Effects, Photoshop, Illustrator, Premiere Pro (and Character Animator puppet authoring) from Claude. See ROADMAP.md for the full tool matrix and what is next.
4
+ Bridge: MCP client → this server → AppleScript `DoScript` → AE → temp result file → back.
5
+
6
+ ## Tools
7
+
8
+ | Tool | Purpose |
9
+ |---|---|
10
+ | `run_extendscript` | Run arbitrary JSX; `return <value>` comes back as JSON. Auto undo-grouped. |
11
+ | `get_project_state` | Project item tree, or one comp's layers in detail (`comp_name`). |
12
+ | `save_frame` | Render a comp frame to PNG, returned inline so Claude can *see* its work. |
13
+ | `list_ae_scripts` | List `.jsx`/`.jsxbin` tools in `scripts/` with descriptions from header comments. |
14
+ | `run_ae_script` | Execute a library script, like File → Scripts → Run Script File. |
15
+
16
+ ## Knowledge system (the server learns as it goes)
17
+
18
+ The server ships with a curated knowledge base (`knowledge/lessons.jsonl`) seeded from real
19
+ production sessions — matchName gotchas, API quirks, parameter-type traps, and techniques
20
+ (blueprint line extraction, seamless wind loops, QE transitions, Auto Reframe...).
21
+
22
+ Three mechanisms keep it useful and growing:
23
+
24
+ 1. **Auto-surfaced gotchas** — every failed `*_run_extendscript` call is matched against the
25
+ lesson keywords; hits are appended to the error message the client sees (e.g. hit
26
+ `Illegal Parameter type` in Premiere and the fix for `autoReframeSequence`'s string preset
27
+ arrives with the error). Failures are also logged to `$WORKSPACE/error-log.jsonl` as raw
28
+ material for new lessons.
29
+ 2. **`knowledge_search` / `knowledge_add` tools** — agents consult lessons before attempting
30
+ unusual scripting, and record new gotchas when they solve one that wasn't auto-suggested.
31
+ Runtime lessons persist to `$WORKSPACE/learned.jsonl` (survives repo updates, per-install).
32
+ 3. **Server instructions + tool descriptions** — the highest-value rules (explicit document
33
+ targeting, visual verification, render-timeout handling, ES3 limits) are baked into the MCP
34
+ instructions and the per-tool descriptions, so a fresh install starts smart.
35
+
36
+ The `scripts/` per-app libraries are the executable side of the same idea — distilled,
37
+ reusable skills (`list_scripts` / `run_script`): blueprint line extraction (PS), seamless
38
+ wind loops and kinetic typography rigs (AE), one-call vertical Auto Reframe (Premiere).
39
+
40
+ ## Install (once)
41
+
42
+ 1. Clone somewhere permanent:
43
+ ```bash
44
+ git clone https://github.com/AJSMonty/adobe-mcp.git ~/tools/adobe-mcp
45
+ ```
46
+ 2. **Node 18+** required: `node -v` (else `brew install node`).
47
+ 3. In the folder: `npm install`
48
+ 4. **In After Effects**: Preferences → Scripting & Expressions → enable **"Allow Scripts to Write Files and Access Network"**. Without this, results can't come back.
49
+ 5. First tool call will trigger a macOS **Automation** permission prompt (your terminal/Claude controlling After Effects) — click Allow. If you missed it: System Settings → Privacy & Security → Automation.
50
+
51
+ ## Hook up to your MCP client
52
+
53
+ This is a standard **stdio MCP server** — any MCP-capable client can drive it (Claude Code,
54
+ Claude Desktop, Cursor, Windsurf, VS Code Copilot agent mode, Zed, Cline, Goose, ...).
55
+ Everything below is the same one-liner expressed in each client's config format:
56
+ run `node /ABSOLUTE/PATH/tools/adobe-mcp/server.mjs` over stdio. Use absolute paths —
57
+ most clients do not expand `~`.
58
+
59
+ ### Claude Code
60
+
61
+ ```bash
62
+ claude mcp add --scope user adobe -- node ~/tools/adobe-mcp/server.mjs
63
+ ```
64
+
65
+ `--scope user` = available in all projects; use `--scope project` from inside a repo to share via `.mcp.json` with your team. Verify: `claude mcp list`.
66
+
67
+ ### Claude Desktop
68
+
69
+ Settings → Developer → Edit Config, add to `claude_desktop_config.json`:
70
+
71
+ ```json
72
+ {
73
+ "mcpServers": {
74
+ "adobe": {
75
+ "command": "node",
76
+ "args": ["/Users/YOUR_USER/tools/adobe-mcp/server.mjs"]
77
+ }
78
+ }
79
+ }
80
+ ```
81
+
82
+ Fully quit and reopen Claude Desktop.
83
+
84
+ ### Cursor
85
+
86
+ Settings → MCP → Add server, or edit `~/.cursor/mcp.json` (global) / `.cursor/mcp.json` (per-project):
87
+
88
+ ```json
89
+ {
90
+ "mcpServers": {
91
+ "adobe": {
92
+ "command": "node",
93
+ "args": ["/Users/YOUR_USER/tools/adobe-mcp/server.mjs"]
94
+ }
95
+ }
96
+ }
97
+ ```
98
+
99
+ Enable it under Settings → MCP, then use Agent mode (composer) — tool calls appear with approval prompts.
100
+
101
+ ### VS Code (Copilot agent mode)
102
+
103
+ `.vscode/mcp.json` in the workspace (or user `mcp.json` via the "MCP: Add Server" command):
104
+
105
+ ```json
106
+ {
107
+ "servers": {
108
+ "adobe": {
109
+ "type": "stdio",
110
+ "command": "node",
111
+ "args": ["/Users/YOUR_USER/tools/adobe-mcp/server.mjs"]
112
+ }
113
+ }
114
+ }
115
+ ```
116
+
117
+ ### Windsurf
118
+
119
+ `~/.codeium/windsurf/mcp_config.json` — same `mcpServers` shape as Claude Desktop/Cursor above.
120
+
121
+ ### Anything else
122
+
123
+ If the client supports MCP over stdio, point it at `node .../server.mjs` and you are done.
124
+
125
+ ### Client caveats
126
+
127
+ - **macOS Automation permission is per host app.** The first tool call from each new client
128
+ (Cursor, VS Code, a different terminal) triggers its own Automation prompt for controlling
129
+ the Adobe apps — approve it once per host in System Settings → Privacy & Security → Automation.
130
+ - **Inline image previews** (`ae_save_frame`, `ps_save_preview`, `ai_save_preview`,
131
+ `ppro_save_frame`) return MCP image content. Claude clients and Cursor render these inline;
132
+ clients without image rendering still get the metadata text, and the model can fall back to
133
+ exporting a file and reading it from disk.
134
+ - **Server instructions** (the working rules + knowledge-base pointers) are sent via the MCP
135
+ `instructions` field; most clients pass them to the model, but if yours does not, the same
136
+ rules are baked into the tool descriptions and `knowledge_search`.
137
+
138
+ ## Script library ("skills")
139
+
140
+ Drop `.jsx` / `.jsxbin` files into `scripts/` — they're immediately available via `list_ae_scripts` / `run_ae_script`.
141
+
142
+ - **Action scripts** (operate on the current selection, no UI) run headlessly — set up selection first via `run_extendscript`.
143
+ - **ScriptUI panel scripts** open their palette in the AE window for a human to click.
144
+ - Plain `.jsx` panels with a separable core function can often be driven headlessly by evaluating the source with the UI kickoff stripped.
145
+
146
+ > ⚠️ `scripts/` may contain third-party/purchased tools. Keep this repo **private** unless you've cleared redistribution rights, or add `scripts/` to `.gitignore`.
147
+
148
+ ## Notes
149
+
150
+ - AE app auto-detected from `/Applications` (newest "Adobe After Effects *"). Override with env var `AE_APP_NAME`, e.g. `"env": {"AE_APP_NAME": "Adobe After Effects 2025"}` in the Desktop config or `--env AE_APP_NAME=...` in `claude mcp add`.
151
+ - **AE must be open** with a project (the empty default project is fine).
152
+ - Timeouts usually mean AE is showing a modal dialog — dismiss it.
153
+ - `save_frame` needs AE 2022+.
154
+
155
+ ## ExtendScript gotchas (learned the hard way)
156
+
157
+ - ExtendScript is **ES3**: no arrow functions, template literals, `let`/`const`, `JSON`, `Array.map`.
158
+ - Collections (`project.items`, `comp.layers`, property groups) are **1-indexed**.
159
+ - Address effect params by **matchName** (`"ADBE Glo2-0002"`), not display name — display names collide.
160
+ - A `.property()` miss throws a **native error whose own stringification throws** — wrap `e.toString()` in its own try/catch or your error handler dies too.
161
+ - Text layers auto-rename to their source text — rename them if you need stable lookups.
162
+ - Cameras: Point of Interest lives in the **Anchor Point** slot (`ADBE Anchor Point`).
163
+ - Spatial properties need **1-element** ease arrays in `setTemporalEaseAtKey`, regardless of dimensions.
164
+ - Parenting a child to a rotated layer bakes compensation into the child's transform — zero the child's rotation *after* parenting if it should inherit orientation.
165
+ - Grid effect: set **Size From** (`ADBE Grid-0002 = 3`) before animating the anchor, or your "scroll" resizes cells instead.
166
+
167
+ ## Smoke test
168
+
169
+ With AE open, ask Claude: *"Use get_project_state to show me what's in my AE project, then create a 1920x1080 comp called 'Test' with a headline text layer and show me a frame."*
170
+
171
+ ## Contributing & governance
172
+
173
+ PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). All merges to `main` and `dev` require
174
+ maintainer approval (branch protection + CODEOWNERS). Lessons for the knowledge base are the
175
+ easiest high-value contribution. Read [SECURITY.md](SECURITY.md) before installing: this
176
+ server executes scripts in your Adobe apps by design.
177
+
178
+ ## License
179
+
180
+ [MIT](LICENSE)
package/SECURITY.md ADDED
@@ -0,0 +1,24 @@
1
+ # Security
2
+
3
+ ## Threat model — read this before installing
4
+
5
+ adobe-mcp executes **arbitrary ExtendScript inside your Adobe apps** on behalf of an AI
6
+ agent. That is the product, not a vulnerability: ExtendScript can read/write files, access
7
+ the network (if the app preference is enabled), and control the host applications. Treat
8
+ any MCP client you connect as having **code execution on your machine**, and only connect
9
+ clients/models you trust. Review what your agent is doing when it runs scripts — the tools
10
+ echo every script body in the conversation.
11
+
12
+ Additional notes:
13
+
14
+ - The server binds to **stdio only** — it opens no network ports and has no remote surface.
15
+ - The workspace (`~/AdobeMCP` by default) collects rendered assets, an error log
16
+ (`error-log.jsonl`, includes failed script snippets) and learned lessons. Nothing is
17
+ transmitted anywhere by this server.
18
+ - Library scripts under `scripts/` run with the same privileges; only add scripts you trust.
19
+
20
+ ## Reporting a vulnerability
21
+
22
+ If you find something that breaks the model above (e.g. a way for a *non-connected* process
23
+ to drive the bridge, or command injection through tool parameters), please use GitHub's
24
+ **private vulnerability reporting** on this repo rather than a public issue.
@@ -0,0 +1,201 @@
1
+ // After Effects adapter.
2
+ import { z } from "zod";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { runJSX, downscalePng } from "../core/bridge.mjs";
7
+
8
+ const FIND_COMP = `
9
+ function __findComp(name) {
10
+ for (var i = 1; i <= app.project.numItems; i++) {
11
+ var it = app.project.items[i];
12
+ if (it instanceof CompItem && it.name === name) return it;
13
+ }
14
+ return null;
15
+ }
16
+ `;
17
+
18
+ export function register(server, { text, errText, registerAsset }) {
19
+ server.registerTool(
20
+ "ae_run_extendscript",
21
+ {
22
+ title: "Run ExtendScript in After Effects",
23
+ description:
24
+ "Execute ExtendScript (JSX) inside After Effects and return the result. Runs as a function " +
25
+ "body: end with `return <value>` (JSON-serialized). ES3 only — no arrow functions, template " +
26
+ "literals, let/const, JSON, Array.map. Collections are 1-indexed. Wrapped in one undo group. " +
27
+ "GOTCHAS: text wiggly selector matchName is 'ADBE Text Wiggly Selector'; seamless noise loops = " +
28
+ "Evolution expression time*(360/duration) + Cycle Evolution on; PSD-imported comps need nested " +
29
+ "durations extended and anchors re-placed from PS pixel bounds. More: knowledge_search.",
30
+ inputSchema: {
31
+ code: z.string().describe("ExtendScript function body; `return` sends back a result."),
32
+ timeout_seconds: z.number().optional().describe("Max seconds (default 120)."),
33
+ },
34
+ },
35
+ async ({ code, timeout_seconds }) => {
36
+ try {
37
+ const r = await runJSX("ae", code, (timeout_seconds ?? 120) * 1000);
38
+ return text({ ok: true, result: r === undefined ? null : r });
39
+ } catch (e) {
40
+ return errText(e);
41
+ }
42
+ }
43
+ );
44
+
45
+ server.registerTool(
46
+ "ae_get_state",
47
+ {
48
+ title: "Inspect the open AE project",
49
+ description:
50
+ "Project item tree (comps, footage, folders) with sizes/durations/layer counts, or one comp's " +
51
+ "layers in detail (kind, timing, transform, text, effects) via comp_name.",
52
+ inputSchema: {
53
+ comp_name: z.string().optional().describe("Comp to inspect in layer-level detail."),
54
+ },
55
+ },
56
+ async ({ comp_name }) => {
57
+ try {
58
+ const jsx =
59
+ comp_name == null
60
+ ? `
61
+ var proj = app.project;
62
+ var out = { projectFile: proj.file ? String(proj.file.fsName) : null,
63
+ activeComp: (proj.activeItem && proj.activeItem instanceof CompItem) ? proj.activeItem.name : null,
64
+ numItems: proj.numItems, items: [] };
65
+ for (var i = 1; i <= proj.numItems; i++) {
66
+ var it = proj.items[i];
67
+ var rec = { index: i, name: it.name, type: it.typeName };
68
+ if (it.parentFolder && it.parentFolder.name !== 'Root') rec.folder = it.parentFolder.name;
69
+ if (it instanceof CompItem) { rec.width = it.width; rec.height = it.height; rec.duration = it.duration; rec.frameRate = it.frameRate; rec.numLayers = it.numLayers; }
70
+ else if (it instanceof FootageItem) { if (it.file) rec.file = String(it.file.fsName); rec.width = it.width; rec.height = it.height; }
71
+ else if (it instanceof FolderItem) { rec.numItems = it.numItems; }
72
+ out.items.push(rec);
73
+ }
74
+ return out;`
75
+ : `
76
+ ${FIND_COMP}
77
+ var comp = __findComp(${JSON.stringify(comp_name)});
78
+ if (!comp) throw new Error('No comp named ' + ${JSON.stringify(comp_name)});
79
+ var out = { name: comp.name, width: comp.width, height: comp.height, duration: comp.duration,
80
+ frameRate: comp.frameRate, currentTime: comp.time, numLayers: comp.numLayers, layers: [] };
81
+ for (var i = 1; i <= comp.numLayers; i++) {
82
+ var L = comp.layers[i];
83
+ var rec = { index: i, name: L.name, enabled: L.enabled, inPoint: L.inPoint, outPoint: L.outPoint,
84
+ parentIndex: L.parent ? L.parent.index : null };
85
+ if (L instanceof TextLayer) { rec.kind='text'; try { var td=L.property('Source Text').value; rec.text=td.text; rec.font=td.font; rec.fontSize=td.fontSize; } catch(e){} }
86
+ else if (L instanceof ShapeLayer) rec.kind='shape';
87
+ else if (L instanceof CameraLayer) rec.kind='camera';
88
+ else if (L instanceof LightLayer) rec.kind='light';
89
+ else if (L instanceof AVLayer) { rec.kind=(L.source && L.source instanceof CompItem)?'precomp':'av'; if (L.source) rec.sourceName=L.source.name; }
90
+ else rec.kind='other';
91
+ try { var tr=L.property('Transform');
92
+ rec.position=tr.property('Position').value; rec.scale=tr.property('Scale').value; rec.opacity=tr.property('Opacity').value; } catch(e){}
93
+ try { var fx=L.property('Effects');
94
+ if (fx && fx.numProperties>0){ rec.effects=[]; for (var e2=1;e2<=fx.numProperties;e2++) rec.effects.push({name:fx.property(e2).name, matchName:fx.property(e2).matchName}); } } catch(e){}
95
+ out.layers.push(rec);
96
+ }
97
+ return out;`;
98
+ return text(await runJSX("ae", jsx, 60000));
99
+ } catch (e) {
100
+ return errText(e);
101
+ }
102
+ }
103
+ );
104
+
105
+ server.registerTool(
106
+ "ae_save_frame",
107
+ {
108
+ title: "Render an AE comp frame to PNG",
109
+ description:
110
+ "Render one frame of a comp and return it inline so you can visually verify work. AE 2022+.",
111
+ inputSchema: {
112
+ comp_name: z.string().describe("Composition to render."),
113
+ time: z.number().optional().describe("Seconds (default: comp's current time)."),
114
+ max_width: z.number().optional().describe("Downscale to at most this width (default 1024)."),
115
+ },
116
+ },
117
+ async ({ comp_name, time, max_width }) => {
118
+ try {
119
+ const pngPath = path.join(os.tmpdir(), `adobe_mcp_frame_${Date.now()}.png`);
120
+ const jsx = `
121
+ ${FIND_COMP}
122
+ var comp = __findComp(${JSON.stringify(comp_name)});
123
+ if (!comp) throw new Error('No comp named ' + ${JSON.stringify(comp_name)});
124
+ if (typeof comp.saveFrameToPng !== 'function') throw new Error('saveFrameToPng requires AE 2022+');
125
+ var t = ${time === undefined ? "comp.time" : JSON.stringify(time)};
126
+ comp.saveFrameToPng(t, new File(${JSON.stringify(pngPath)}));
127
+ return { time: t, width: comp.width, height: comp.height };`;
128
+ const meta = await runJSX("ae", jsx, 120000);
129
+ let ok = false;
130
+ for (let i = 0; i < 50; i++) {
131
+ if (fs.existsSync(pngPath) && fs.statSync(pngPath).size > 0) {
132
+ const s1 = fs.statSync(pngPath).size;
133
+ await new Promise((r) => setTimeout(r, 150));
134
+ if (fs.statSync(pngPath).size === s1) { ok = true; break; }
135
+ } else await new Promise((r) => setTimeout(r, 150));
136
+ }
137
+ if (!ok) throw new Error("Frame render did not produce a PNG.");
138
+ if (meta.width > (max_width ?? 1024)) await downscalePng(pngPath, max_width ?? 1024);
139
+ const data = fs.readFileSync(pngPath).toString("base64");
140
+ fs.rmSync(pngPath, { force: true });
141
+ return { content: [
142
+ { type: "text", text: JSON.stringify(meta) },
143
+ { type: "image", data, mimeType: "image/png" },
144
+ ] };
145
+ } catch (e) {
146
+ return errText(e);
147
+ }
148
+ }
149
+ );
150
+
151
+ server.registerTool(
152
+ "ae_render_comp",
153
+ {
154
+ title: "Render an AE comp via the Render Queue",
155
+ description:
156
+ "Queue a comp and render it to disk (blocks until finished). Uses an H.264 output module " +
157
+ "template when available, else Lossless MOV. Registers the output as a workflow asset. " +
158
+ "If the call times out, the render may still have completed — check the output file " +
159
+ "(stable size, right duration) before re-queueing.",
160
+ inputSchema: {
161
+ comp_name: z.string().describe("Composition to render."),
162
+ output_path: z.string().optional().describe("Absolute output path (default ~/Desktop/<comp>.mp4)."),
163
+ om_template: z.string().optional().describe("Output module template name override."),
164
+ timeout_seconds: z.number().optional().describe("Max seconds (default 570)."),
165
+ },
166
+ },
167
+ async ({ comp_name, output_path, om_template, timeout_seconds }) => {
168
+ try {
169
+ const jsx = `
170
+ ${FIND_COMP}
171
+ var comp = __findComp(${JSON.stringify(comp_name)});
172
+ if (!comp) throw new Error('No comp named ' + ${JSON.stringify(comp_name)});
173
+ var rq = app.project.renderQueue;
174
+ while (rq.numItems > 0) rq.item(1).remove();
175
+ var it = rq.items.add(comp);
176
+ var om = it.outputModule(1);
177
+ var chosen = ${om_template ? JSON.stringify(om_template) : "null"};
178
+ if (!chosen) {
179
+ for (var t = 0; t < om.templates.length; t++) {
180
+ if (om.templates[t].indexOf('H.264 - Match Render Settings - 15') === 0) { chosen = om.templates[t]; break; }
181
+ }
182
+ if (!chosen) for (var t2 = 0; t2 < om.templates.length; t2++) { if (om.templates[t2].indexOf('H.264') === 0) { chosen = om.templates[t2]; break; } }
183
+ if (!chosen) chosen = 'Lossless';
184
+ }
185
+ om.applyTemplate(chosen);
186
+ var ext = (chosen.indexOf('H.264') === 0) ? '.mp4' : '.mov';
187
+ var outPath = ${output_path ? JSON.stringify(output_path) : "Folder('~/Desktop').fsName + '/' + comp.name.replace(/[^\\w\\- ]/g,'_') + ext"};
188
+ om.file = new File(outPath);
189
+ try { it.applyTemplate('Best Settings'); } catch (e) {}
190
+ rq.render();
191
+ var f = new File(outPath);
192
+ return { rendered: it.status === RQItemStatus.DONE, template: chosen, output: f.fsName, bytes: f.exists ? f.length : 0 };`;
193
+ const r = await runJSX("ae", jsx, (timeout_seconds ?? 570) * 1000);
194
+ if (r && r.rendered && r.output) registerAsset({ app: "ae", kind: "video", path: r.output, meta: { comp: comp_name } });
195
+ return text(r);
196
+ } catch (e) {
197
+ return errText(e);
198
+ }
199
+ }
200
+ );
201
+ }
@@ -0,0 +1,153 @@
1
+ // Illustrator adapter.
2
+ import { z } from "zod";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { runJSX, downscalePng } from "../core/bridge.mjs";
7
+
8
+ export function register(server, { text, errText, registerAsset }) {
9
+ server.registerTool(
10
+ "ai_run_extendscript",
11
+ {
12
+ title: "Run ExtendScript in Illustrator",
13
+ description:
14
+ "Execute ExtendScript (JSX) inside Illustrator and return the result. Runs as a function body: " +
15
+ "end with `return <value>`. ES3 only. Key DOM: app.documents, activeDocument, artboards, " +
16
+ "layers, pathItems (setEntirePath), textFrames, groupItems, symbols. Colors via new RGBColor(). " +
17
+ "GOTCHAS: exports/previews act on the ACTIVE document — activate by name first; documents.add() " +
18
+ "switches the active doc; no blend API (interpolate shapes in a loop); artboardRect is " +
19
+ "[0, H, W, 0] with Y up. More: knowledge_search.",
20
+ inputSchema: {
21
+ code: z.string().describe("ExtendScript function body."),
22
+ timeout_seconds: z.number().optional().describe("Max seconds (default 120)."),
23
+ },
24
+ },
25
+ async ({ code, timeout_seconds }) => {
26
+ try {
27
+ const r = await runJSX("ai", code, (timeout_seconds ?? 120) * 1000);
28
+ return text({ ok: true, result: r === undefined ? null : r });
29
+ } catch (e) {
30
+ return errText(e);
31
+ }
32
+ }
33
+ );
34
+
35
+ server.registerTool(
36
+ "ai_get_state",
37
+ {
38
+ title: "Inspect open Illustrator documents",
39
+ description:
40
+ "Lists open documents; for the active document returns artboards (name, rect), layers with " +
41
+ "item counts, and text frame contents.",
42
+ inputSchema: {},
43
+ },
44
+ async () => {
45
+ try {
46
+ const jsx = `
47
+ var out = { numDocuments: app.documents.length, documents: [], activeDocument: null };
48
+ for (var d = 0; d < app.documents.length; d++) {
49
+ out.documents.push({ name: app.documents[d].name, width: app.documents[d].width, height: app.documents[d].height });
50
+ }
51
+ if (app.documents.length) {
52
+ var doc = app.activeDocument;
53
+ var abs = [];
54
+ for (var a = 0; a < doc.artboards.length; a++) {
55
+ var r = doc.artboards[a].artboardRect;
56
+ abs.push({ index: a, name: doc.artboards[a].name, rect: [Math.round(r[0]), Math.round(r[1]), Math.round(r[2]), Math.round(r[3])] });
57
+ }
58
+ var lys = [];
59
+ for (var l = 0; l < doc.layers.length; l++) {
60
+ var L = doc.layers[l];
61
+ lys.push({ name: L.name, visible: L.visible, locked: L.locked,
62
+ pathItems: L.pathItems.length, groupItems: L.groupItems.length, textFrames: L.textFrames.length });
63
+ }
64
+ var txts = [];
65
+ for (var t = 0; t < doc.textFrames.length && t < 40; t++) txts.push(doc.textFrames[t].contents.slice(0, 120));
66
+ out.activeDocument = { name: doc.name, artboards: abs, layers: lys, textSamples: txts,
67
+ path: (function(){ try { return String(doc.fullName.fsName); } catch(e){ return null; } })() };
68
+ }
69
+ return out;`;
70
+ return text(await runJSX("ai", jsx, 60000));
71
+ } catch (e) {
72
+ return errText(e);
73
+ }
74
+ }
75
+ );
76
+
77
+ server.registerTool(
78
+ "ai_save_preview",
79
+ {
80
+ title: "Preview an Illustrator artboard",
81
+ description:
82
+ "Export the active document (active or given artboard) as PNG and return it inline for visual " +
83
+ "verification.",
84
+ inputSchema: {
85
+ artboard_index: z.number().optional().describe("Artboard index (default: active)."),
86
+ max_width: z.number().optional().describe("Downscale to at most this width (default 1024)."),
87
+ },
88
+ },
89
+ async ({ artboard_index, max_width }) => {
90
+ try {
91
+ const pngPath = path.join(os.tmpdir(), `adobe_mcp_ai_${Date.now()}.png`);
92
+ const jsx = `
93
+ if (!app.documents.length) throw new Error('No document open in Illustrator');
94
+ var doc = app.activeDocument;
95
+ ${artboard_index !== undefined ? `doc.artboards.setActiveArtboardIndex(${artboard_index});` : ""}
96
+ var f = new File(${JSON.stringify(pngPath)});
97
+ var opts = new ExportOptionsPNG24();
98
+ opts.artBoardClipping = true;
99
+ opts.antiAliasing = true;
100
+ doc.exportFile(f, ExportType.PNG24, opts);
101
+ var r = doc.artboards[doc.artboards.getActiveArtboardIndex()].artboardRect;
102
+ return { name: doc.name, artboard: doc.artboards.getActiveArtboardIndex(), width: Math.round(r[2]-r[0]), height: Math.round(r[1]-r[3]) };`;
103
+ const meta = await runJSX("ai", jsx, 120000);
104
+ if (!fs.existsSync(pngPath)) throw new Error("Preview PNG was not written.");
105
+ if (meta.width > (max_width ?? 1024)) await downscalePng(pngPath, max_width ?? 1024);
106
+ const data = fs.readFileSync(pngPath).toString("base64");
107
+ fs.rmSync(pngPath, { force: true });
108
+ return { content: [
109
+ { type: "text", text: JSON.stringify(meta) },
110
+ { type: "image", data, mimeType: "image/png" },
111
+ ] };
112
+ } catch (e) {
113
+ return errText(e);
114
+ }
115
+ }
116
+ );
117
+
118
+ server.registerTool(
119
+ "ai_export",
120
+ {
121
+ title: "Export the active Illustrator document",
122
+ description:
123
+ "Export to svg/png/pdf, or save a layered .ai copy (the format AE imports as a layered comp). " +
124
+ "Exports the ACTIVE document — set app.activeDocument to the right one first. " +
125
+ "Registers the file as a workflow asset.",
126
+ inputSchema: {
127
+ output_path: z.string().describe("Absolute output path; extension chooses format (.svg/.png/.pdf/.ai)."),
128
+ scale: z.number().optional().describe("PNG scale percent (default 100)."),
129
+ },
130
+ },
131
+ async ({ output_path, scale }) => {
132
+ try {
133
+ const ext = path.extname(output_path).toLowerCase();
134
+ const jsx = `
135
+ if (!app.documents.length) throw new Error('No document open in Illustrator');
136
+ var doc = app.activeDocument;
137
+ var f = new File(${JSON.stringify(output_path)});
138
+ var ext = ${JSON.stringify(ext)};
139
+ if (ext === '.svg') { var so = new ExportOptionsSVG(); doc.exportFile(f, ExportType.SVG, so); }
140
+ else if (ext === '.png') { var po = new ExportOptionsPNG24(); po.artBoardClipping = true; po.horizontalScale = ${scale ?? 100}; po.verticalScale = ${scale ?? 100}; doc.exportFile(f, ExportType.PNG24, po); }
141
+ else if (ext === '.pdf') { var pd = new PDFSaveOptions(); doc.saveAs(f, pd); }
142
+ else if (ext === '.ai') { var ao = new IllustratorSaveOptions(); doc.saveAs(f, ao); }
143
+ else throw new Error('Unsupported extension ' + ext + ' (use .svg/.png/.pdf/.ai)');
144
+ return { output: f.fsName, name: doc.name };`;
145
+ const r = await runJSX("ai", jsx, 120000);
146
+ registerAsset({ app: "ai", kind: ext.replace(".", ""), path: r.output, meta: { doc: r.name } });
147
+ return text(r);
148
+ } catch (e) {
149
+ return errText(e);
150
+ }
151
+ }
152
+ );
153
+ }