mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #18292 from davidmann4/fix/18208-headless-mcp-discovery
Fix headless MCP command discovery and edit validation (#18289)
This commit is contained in:
8 files changed
+103
-23
No files matched your search
@@ -2112,7 +2112,7 @@ fn mcp_session(args: &[&str], env: &[(&str, &std::ffi::OsStr)], calls: &[(&str,
|
||||
}
|
||||
|
||||
/// Plain `mcp` without the person's consent works headless, as it always did: commands run, UI
|
||||
/// tools say they need the open app. `--headless` too, and it doesn't read a PHOTOCRAFT_CONTROL_PORT
|
||||
/// tools are not offered. `--headless` too, and it doesn't read a PHOTOCRAFT_CONTROL_PORT
|
||||
/// exported for another tool (here not even a port).
|
||||
#[test]
|
||||
fn mcp_without_consent_works_headless() {
|
||||
@@ -2124,8 +2124,8 @@ fn mcp_without_consent_works_headless() {
|
||||
let calls = [("command_list", json!({})), ("ui_inspect", json!({}))];
|
||||
let r = mcp_session(&["mcp", "--when-closed", "error"], &env, &calls);
|
||||
assert_ne!(r[0]["isError"], true, "headless commands run: {}", r[0]);
|
||||
assert_eq!(r[1]["isError"], true, "{}", r[1]);
|
||||
assert!(r[1]["content"][0]["text"].as_str().unwrap().contains("bridge"), "{}", r[1]);
|
||||
// An unknown tool is a protocol error, so the reply has no `result`.
|
||||
assert!(r[1].is_null(), "headless mcp offers no ui_* tools: {}", r[1]);
|
||||
let mut env = env.to_vec();
|
||||
env.push(("PHOTOCRAFT_CONTROL_PORT", std::ffi::OsStr::new("not-a-port")));
|
||||
let r = mcp_session(&["mcp", "--headless"], &env, &calls[..1]);
|
||||
|
||||
@@ -637,6 +637,9 @@ impl PhotocraftMcp {
|
||||
|
||||
pub fn with_backend(backend: Backend) -> Self {
|
||||
let mut tool_router = Self::tool_router();
|
||||
if matches!(&backend, Backend::Headless(_)) {
|
||||
tool_router.map.retain(|name, _| !name.starts_with("ui_") && name != "control_call");
|
||||
}
|
||||
for route in tool_router.map.values_mut() {
|
||||
let mut schema = (*route.attr.input_schema).clone();
|
||||
strict_schema(&mut schema);
|
||||
@@ -1058,13 +1061,13 @@ impl PhotocraftMcp {
|
||||
`disabledReason` says why a command is off (null when enabled); `needsDocument` is true when it is off because no \
|
||||
document is open: create or open one first (doc_new, doc_open).")]
|
||||
async fn command_list(&self, Parameters(p): Parameters<ListParams>) -> Result<CallToolResult, McpError> {
|
||||
let all = if let Some(r) = self.headless_op(|h| Ok(h.command_list())).await {
|
||||
r
|
||||
let (all, headless) = if let Some(r) = self.headless_op(|h| Ok(h.command_list())).await {
|
||||
(r, true)
|
||||
} else {
|
||||
let Some(b) = self.bridge_client() else {
|
||||
return Ok(no_backend());
|
||||
};
|
||||
b.call_read("engine.commands", json!({})).await
|
||||
(b.call_read("engine.commands", json!({})).await, false)
|
||||
};
|
||||
let all = match all {
|
||||
Ok(v) => v,
|
||||
@@ -1072,10 +1075,19 @@ impl PhotocraftMcp {
|
||||
};
|
||||
let needle = p.filter.map(|f| f.to_lowercase());
|
||||
let enabled_only = p.enabled_only.unwrap_or(false);
|
||||
let params = json!({});
|
||||
let items: Vec<Value> = into_command_rows(all)
|
||||
.into_iter()
|
||||
.filter(|c| {
|
||||
needle.as_ref().is_none_or(|n| photocraft_engine::commands::list_entry_matches(c, n))
|
||||
let allowed = c.get("id").and_then(Value::as_str).is_some_and(|id| {
|
||||
if headless {
|
||||
id == "file.export.renderVideo" || crate::workspace::authorize_engine_command(id, ¶ms).is_ok()
|
||||
} else {
|
||||
crate::workspace::authorize_desktop_engine_command(id, ¶ms).is_ok()
|
||||
}
|
||||
});
|
||||
allowed
|
||||
&& needle.as_ref().is_none_or(|n| photocraft_engine::commands::list_entry_matches(c, n))
|
||||
&& (!enabled_only || c.get("enabled").and_then(Value::as_bool).unwrap_or(true))
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -9,7 +9,7 @@ use rmcp::service::RequestContext;
|
||||
|
||||
const DOCUMENT: &str = "photocraft://document";
|
||||
const COMMANDS: &str = "photocraft://commands";
|
||||
const INSTRUCTIONS: &str = "PhotoCraft image editor. Start with doc_new/doc_open, discover ids and parameter docs with command_list, edit with command_run or command_batch (one history step per command). Inspect with doc_inspect and render_preview; doc_save writes native .pcraft or exports by extension. File paths are relative to the read/write roots granted at launch; agent_folders tells where they are. ui_inspect/ui_screenshot and other ui_* tools require bridge mode. Read photocraft://document and photocraft://commands for live JSON state.";
|
||||
const INSTRUCTIONS: &str = "PhotoCraft image editor. Start with doc_new/doc_open, discover ids and parameter docs with command_list, edit with command_run or command_batch (one history step per command). Inspect with doc_inspect and render_preview; doc_save writes native .pcraft or exports by extension. File paths are relative to the read/write roots granted at launch; agent_folders tells where they are. ui_* tools and control_call, where listed, need the open app (bridge mode). Read photocraft://document and photocraft://commands for live JSON state.";
|
||||
|
||||
fn annotated(mut tool: Tool) -> Tool {
|
||||
let words = tool.name.replace('_', " ");
|
||||
|
||||
@@ -93,15 +93,11 @@ async fn lists_expected_tools() {
|
||||
"command_list",
|
||||
"command_run",
|
||||
"command_batch",
|
||||
"ui_inspect",
|
||||
"ui_screenshot",
|
||||
"ui_pointer",
|
||||
"ui_menu_invoke",
|
||||
"ui_set",
|
||||
"control_call",
|
||||
] {
|
||||
assert!(names.contains(&n.to_string()), "missing tool {n}: {names:?}");
|
||||
}
|
||||
assert!(!names.iter().any(|name| name.starts_with("ui_") || name == "control_call"));
|
||||
assert!(client.call_tool(CallToolRequestParams::new("ui_screenshot")).await.is_err());
|
||||
for t in &tools {
|
||||
assert!(t.name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'), "tool name `{}`", t.name);
|
||||
assert!(t.description.as_ref().is_some_and(|d| !d.is_empty()));
|
||||
@@ -165,6 +161,15 @@ async fn command_list_filters() {
|
||||
let all = json_of(&call(&client, "command_list", json!({})).await);
|
||||
let n_all = all.as_array().unwrap().len();
|
||||
assert!(n_all > 20);
|
||||
for id in ["file.openAs", "file.placeEmbedded", "file.export.quickExport", "file.automate.photomerge"] {
|
||||
assert!(!all.as_array().unwrap().iter().any(|row| row["id"] == id), "{id}");
|
||||
}
|
||||
for filter in ["rotate", "rotation"] {
|
||||
let rows = json_of(&call(&client, "command_list", json!({"filter": filter})).await);
|
||||
for id in ["image.imageRotation.90cw", "edit.transform.rotate90Cw"] {
|
||||
assert!(rows.as_array().unwrap().iter().any(|row| row["id"] == id), "{filter}: {id}");
|
||||
}
|
||||
}
|
||||
let blur = json_of(&call(&client, "command_list", json!({"filter": "blur"})).await);
|
||||
assert!(!blur.as_array().unwrap().is_empty() && blur.as_array().unwrap().len() < n_all);
|
||||
assert!(blur.as_array().unwrap().iter().all(|c| c["params"].is_string()));
|
||||
@@ -221,7 +226,7 @@ fn strict_schema_problems(path: &str, schema: &Value, out: &mut Vec<String>) {
|
||||
async fn tool_schemas_pass_strict_validators() {
|
||||
// #1782: `ui_pointer`'s `items: true` and `command_batch`'s `$ref`/`$defs` made strict
|
||||
// providers (e.g. Moonshot via Volcano Ark) reject the whole request.
|
||||
let client = connect(PhotocraftMcp::headless()).await;
|
||||
let client = connect(PhotocraftMcp::bridge("127.0.0.1:1", CONTROL_TOKEN).unwrap()).await;
|
||||
let tools = client.list_all_tools().await.unwrap();
|
||||
let mut problems = Vec::new();
|
||||
for t in &tools {
|
||||
@@ -294,7 +299,7 @@ fn ui_set_fields() -> Vec<String> {
|
||||
/// three fields missing when the issue was filed.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ui_set_description_names_every_accepted_field() {
|
||||
let client = connect(PhotocraftMcp::headless()).await;
|
||||
let client = connect(PhotocraftMcp::bridge("127.0.0.1:1", CONTROL_TOKEN).unwrap()).await;
|
||||
let tools = client.list_all_tools().await.unwrap();
|
||||
let tool = tools.iter().find(|t| t.name == "ui_set").expect("ui_set tool");
|
||||
let schema = Value::Object((*tool.input_schema).clone());
|
||||
@@ -319,9 +324,6 @@ async fn errors_are_tool_errors_not_crashes() {
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
let r = call(&client, "doc_open", json!({"path": "/definitely/missing.png"})).await;
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
let r = call(&client, "ui_inspect", json!({})).await;
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
assert!(text(&r).contains("bridge"));
|
||||
let r = call(&client, "doc_export", json!({})).await;
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
// Quality 0 is refused, not clamped to 1 (serde already refuses 500, -1 and "85").
|
||||
@@ -1368,6 +1370,58 @@ async fn command_batch_description_exposes_non_atomic_semantics_when_tools_are_l
|
||||
client.cancel().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn invalid_edit_parameters_do_not_modify_the_document() {
|
||||
let client = connect(PhotocraftMcp::headless()).await;
|
||||
json_of(&call(&client, "doc_new", json!({"width": 8, "height": 8})).await);
|
||||
let before = json_of(&call(&client, "doc_inspect", json!({})).await);
|
||||
for (id, params, expected) in [
|
||||
("image.adjustments.desaturate", json!({"amount": 50}), "unknown parameter"),
|
||||
("image.adjustments.desaturate", json!([]), "object"),
|
||||
("document.pixel", json!({"x": 0}), "y must be a number"),
|
||||
("image.crop", json!({"deleteCroppedPixels": "false"}), "must be true or false"),
|
||||
] {
|
||||
let step = json!({"id": id, "params": params});
|
||||
let reply = call(&client, "command_run", step.clone()).await;
|
||||
assert_eq!(reply.is_error, Some(true), "{id}: {}", text(&reply));
|
||||
assert!(text(&reply).contains(expected), "{id}: {}", text(&reply));
|
||||
let batch = json_of(&call(&client, "command_batch", json!({"steps": [step]})).await);
|
||||
assert_eq!(batch["failed"], 1, "{batch}");
|
||||
assert!(batch["results"][0]["error"].as_str().unwrap().contains(expected), "{batch}");
|
||||
}
|
||||
let after = json_of(&call(&client, "doc_inspect", json!({})).await);
|
||||
assert_eq!(after["history"], before["history"]);
|
||||
assert_eq!(after["width"], 8);
|
||||
assert_eq!(after["height"], 8);
|
||||
client.cancel().await.unwrap();
|
||||
}
|
||||
|
||||
/// The headless session's gate is no reason to refuse a crop frame past the canvas: the Crop tool
|
||||
/// extends the canvas that way, and Reveal All always crops to a frame larger than the canvas.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn gated_sessions_still_crop_past_the_canvas() {
|
||||
let client = connect(PhotocraftMcp::headless()).await;
|
||||
json_of(&call(&client, "doc_new", json!({"width": 8, "height": 8})).await);
|
||||
let size = |doc: &Value| (doc["width"].as_u64().unwrap(), doc["height"].as_u64().unwrap());
|
||||
let run = |id: &'static str, params: Value| {
|
||||
let client = &client;
|
||||
async move {
|
||||
let reply = call(client, "command_run", json!({"id": id, "params": params})).await;
|
||||
assert_ne!(reply.is_error, Some(true), "{id}: {}", text(&reply));
|
||||
}
|
||||
};
|
||||
run("image.crop", json!({"x": -2, "y": 0, "width": 10, "height": 8})).await;
|
||||
let extended = size(&json_of(&call(&client, "doc_inspect", json!({})).await));
|
||||
assert!(extended.0 > 8, "an extending crop widens the canvas: {extended:?}");
|
||||
run("image.crop", json!({"x": 2, "y": 0, "width": 4, "height": 8, "deleteCroppedPixels": false})).await;
|
||||
let cropped = size(&json_of(&call(&client, "doc_inspect", json!({})).await));
|
||||
assert!(cropped.0 < extended.0, "{cropped:?}");
|
||||
run("image.revealAll", json!({})).await;
|
||||
let revealed = size(&json_of(&call(&client, "doc_inspect", json!({})).await));
|
||||
assert!(revealed.0 > cropped.0, "Reveal All brings the hidden pixels back: {revealed:?}");
|
||||
client.cancel().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn command_batch_runs_steps_in_order() {
|
||||
let client = connect(PhotocraftMcp::headless()).await;
|
||||
@@ -1552,7 +1606,7 @@ async fn convention_tool_hints_match_what_each_tool_does() {
|
||||
("ui_set", EDITS),
|
||||
("control_call", EDITS),
|
||||
];
|
||||
let client = connect(PhotocraftMcp::headless()).await;
|
||||
let client = connect(PhotocraftMcp::bridge("127.0.0.1:1", CONTROL_TOKEN).unwrap()).await;
|
||||
let tools = client.list_all_tools().await.unwrap();
|
||||
assert_eq!(tools.len(), expected.len(), "classify every tool here");
|
||||
for tool in tools {
|
||||
|
||||
@@ -812,7 +812,11 @@ fn unlock_background_for_crop(doc: &mut Document) {
|
||||
}
|
||||
|
||||
fn crop_with(s: &mut Session, p: &Value, keep_background: bool) -> Result<Value> {
|
||||
let delete = p.get("deleteCroppedPixels").and_then(Value::as_bool).unwrap_or(true);
|
||||
let delete = match p.get("deleteCroppedPixels") {
|
||||
None | Some(Value::Null) => true,
|
||||
Some(Value::Bool(value)) => *value,
|
||||
Some(value) => return Err(bad("image.crop", format!("`deleteCroppedPixels` must be true or false, not {value}"))),
|
||||
};
|
||||
// The Crop tool's Fill: Content-Aware Fill of what the crop uncovers (#3823).
|
||||
let content_aware = match p.get("contentAware") {
|
||||
None | Some(Value::Null) => false,
|
||||
|
||||
@@ -109,7 +109,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
params: r##"{"x":i32,"y":i32}"##,
|
||||
enabled: has_doc,
|
||||
run: |s, p| {
|
||||
let coord = |k: &str| i32::try_from(int(p, k).unwrap_or(0)).map_err(|_| bad("document.pixel", format!("{k} must fit in 32 bits")));
|
||||
let coord = |key: &str| {
|
||||
let value = int(p, key).ok_or_else(|| bad("document.pixel", format!("{key} must be a number")))?;
|
||||
i32::try_from(value).map_err(|_| bad("document.pixel", format!("{key} must fit in 32 bits")))
|
||||
};
|
||||
let (x, y) = (coord("x")?, coord("y")?);
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
// At i32::MAX the 1x1 rect saturates to empty: a pixel that far out is transparent.
|
||||
|
||||
@@ -135,6 +135,13 @@ pub fn list_entry(s: &Session, c: &CommandSpec, reason: Option<String>) -> Value
|
||||
/// say "RAW Develop" (#12403).
|
||||
pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] = &[
|
||||
("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")"),
|
||||
("image.imageRotation.180", "Rotate Canvas, Image Rotation"),
|
||||
("image.imageRotation.90cw", "Rotate Canvas, Image Rotation"),
|
||||
("image.imageRotation.90ccw", "Rotate Canvas, Image Rotation"),
|
||||
("edit.transform.rotate180", "Layer Rotation"),
|
||||
("edit.transform.rotate90Cw", "Layer Rotation"),
|
||||
("edit.transform.rotate90Ccw", "Layer Rotation"),
|
||||
("image.rotation.arbitrary", "Rotate Canvas, Image Rotation"),
|
||||
("filter.cameraRaw", "Camera Raw Filter"),
|
||||
("edit.preferences.rawDefaults", "Camera Raw Defaults"),
|
||||
];
|
||||
|
||||
@@ -470,7 +470,7 @@ How each MCP tool maps onto control methods in bridge mode:
|
||||
|
||||
Bridge previews capture the app window; passing `index` is an error. Headless `doc_render_preview` supports `index` without changing the active document.
|
||||
|
||||
`doc_select` and `doc_close` work only in headless mode. The `ui_*` tools and `control_call` work only in bridge mode; in headless mode they return a tool error that explains how to start bridge mode.
|
||||
`doc_select` and `doc_close` work only in headless mode. The `ui_*` tools and `control_call` work only in bridge mode. A headless server (`--headless`, or plain `mcp` without the suite's `AI-MCP` flag) does not list them, and calling one is a protocol error for an unknown tool. Plain `mcp` with the flag lists them; while it runs headless because the app is closed, they return a tool error that explains how to start bridge mode.
|
||||
|
||||
**Security note:** TCP control uses a bearer token, not client identity or general per-method
|
||||
authorization. A client that possesses the token receives the non-filesystem control surface,
|
||||
|
||||
Reference in new issue
Block a user