diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index a8d6cc86e6..2c16587227 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1663,6 +1663,37 @@ fn transform_refused_by_a_later_operation_changes_nothing() { assert_eq!(count(&mut s), base, "one undo removes the rectangle"); } +#[test] +fn transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing() { + let inspect = |s: &mut Server, id| serde_json::from_str::(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap(); + let mut s = server(); + let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"}))); + let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"}))); + let before = inspect(&mut s, 3); + let cases = [ + ("object.reflect", json!({"dx": 10, "reflect": 42, "copy": true})), + ("object.reflect", json!({"dx": 10, "reflect": true})), + ("copy", json!({"dx": 10, "copy": "yes"})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": "center", "copy": true})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": [5]})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": [5, "a"]})), + ]; + for (index, (says, mut args)) in cases.into_iter().enumerate() { + args["ids"] = json!([first]); + let request_id = 4 + index as u64 * 2; + let rejected = call(&mut s, request_id, "transform", args.clone()); + assert_eq!(rejected["isError"], true, "{args}: {rejected}"); + assert!(text_of(&rejected).contains(says), "{args}: {rejected}"); + // The document, the selection and the undo history are as they were. + assert_eq!(inspect(&mut s, request_id + 1), before, "{args}"); + } + // A null `reflect`, `copy` or `origin` is left out. + let applied = call(&mut s, 20, "transform", json!({"ids": [second], "dx": 10, "reflect": null, "copy": null, "origin": null})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move"])); +} + #[test] fn add_text_rejects_invalid_path_effects_before_editing() { let mut s = server(); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d730f8deaf..5cd48e145b 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec { tool( "transform", "Transform", - "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.", + "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses, or an argument of the wrong type, returns that error before any step runs, and nothing changes.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 619af2e12e..cd7a0fc20b 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -303,7 +303,8 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result { // Each operation is its own command: check the params the later ones refuse before the first - // runs, so a refused request changes nothing. + // runs, so a refused request changes nothing. The `transform` arm of `dispatch` has already + // refused a `dx`, `dy`, `rotate`, `scale`, `scaleX`, `scaleY` or `shear` that is not a number. fn bad(cmd: &'static str) -> impl Fn(String) -> String { move |e| format!("invalid parameters for `{cmd}`: {e}") } @@ -312,7 +313,12 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result if sx.is_some() || sy.is_some() { vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?; } - let reflect = a.get("reflect").and_then(Value::as_str); + // A null `reflect`, `copy` or `origin` is left out. + let reflect = match a.get("reflect") { + None | Some(Value::Null) => None, + Some(Value::String(axis)) => Some(axis.as_str()), + Some(v) => return Err(format!("invalid parameters for `object.reflect`: axis must be \"vertical\" or \"horizontal\", not `{v}`")), + }; if let Some(axis) = reflect { vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?; } @@ -320,9 +326,18 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result if let Some(sh) = shear { vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?; } + let copy = match a.get("copy") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| format!("`copy` must be true or false, not {v}"))?, + }; + if let Some(o) = a.get("origin").filter(|o| !o.is_null()) + && !o.as_array().is_some_and(|xy| xy.len() == 2 && xy.iter().all(Value::is_number)) + { + return Err(format!("`origin` must be [x, y], not {o}")); + } select_ids(b, a)?; // With `copy`, the first operation duplicates and the rest transform the copy (the new selection). - let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false)); + let copy = std::cell::Cell::new(copy); let with = |mut p: Value| { if let Some(o) = a.get("origin") { p["origin"] = o.clone(); diff --git a/docs/mcp.md b/docs/mcp.md index 655efa1b4c..54dc29fedd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -724,7 +724,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | -| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. | +| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is not a number, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers; a null `reflect`, `copy` or `origin` is left out. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. |