feat(automation): material_export MCP tool for portable .mcmat

Sandboxed agents could not hand a material to TextureCraft: the workspace
sandbox refuses `file.*` commands and there was no MCP tool for `.mcmat`.

Add `material_export {path, graph?, size?, values?}` (RPC method
`material.export`). It cooks the graph through the same engine code as
`file.exportMaterial` and writes the `.mcmat` only through
AuthorizedWorkspace (cap-std, `--write-root`): no write root, a malformed
path or an escape is an error, the parent folder must exist, and the file is
capped at what `package_open` may read back. Bridge mode refuses it like the
other path tools. The engine gets a shared `material_request` helper so the
command and the tool parse graph/size/values identically.

Tests: file written and readable, bad requests, denied without a write root
(Denied and read-only workspace), path escapes (`..`, absolute, backslash,
drive, symlink) and the MCP tool end to end. docs/control-protocol.md lists
the method and tool.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
A-Gift-Of-FlameandClaude Sonnet 5.5 committed 2026-11-03 23:55:13 +01:00
1 parent f1bb82e8e0
commit ef8ab335c2
6 files changed
+170 -10

No files matched your search

+22 -1
View File
@@ -4,7 +4,8 @@
use std::path::Path;
use materialcraft_engine::core::NodeId;
use materialcraft_engine::{Session, commands, file_cmds, inspect};
use materialcraft_engine::formats::material::MATERIAL_EXT;
use materialcraft_engine::{Session, commands, file_cmds, inspect, material_cmds};
use materialcraft_render::{Lighting, Maps, Scene, Settings};
use serde_json::{Value, json};
@@ -182,6 +183,26 @@ impl Headless {
Ok(json!({"files": written}))
}
/// Cook a graph and write it as a portable `.mcmat` material (`.mcmat` appended when
/// missing) to `path`: `{path, graph?, size?, values?}`, the workspace-scoped
/// `file.exportMaterial`. The file is capped at what `package_open` may read back.
pub fn export_material(&mut self, p: &Value) -> Result<Value, AutomationError> {
let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?;
let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") };
match &self.fs {
Filesystem::Denied => return Err(bad("file access is not granted: start the server with --write-root <dir>")),
Filesystem::Workspace(w) => w.check_write(&path)?,
Filesystem::TrustedLocal => {}
}
let (gi, options) = material_cmds::material_request(&self.session, "material.export", p)?;
let bytes = material_cmds::material_bytes(&self.session, gi, &options)?;
if bytes.len() as u64 > MAX_READ_BYTES {
return Err(bad(format!("the material is {} bytes (limit {MAX_READ_BYTES}); export a smaller `size`", bytes.len())));
}
self.write(&path, &bytes)?;
Ok(json!({"path": path, "bytes": bytes.len()}))
}
/// Render the 3D view or a node's 2D output as PNG.
pub fn render_png(&mut self, o: &RenderOptions) -> Result<Rendered, AutomationError> {
let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE };
+80 -2
View File
@@ -4,8 +4,9 @@
//!
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
//! `session.inspect`, plus `command.batch {steps}`, `package.open {path}`, `package.save {path?}`,
//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`
//! (workspace-scoped versions of the engine commands), `render {view?, width?, height?, yaw?,
//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`,
//! `material.export {path, graph?, size?, values?}` (workspace-scoped versions of the engine
//! commands; the last writes a portable `.mcmat`), `render {view?, width?, height?, yaw?,
//! pitch?, scene?, node?, port?, full?}` (PNG base64, the shape of the app's `view.screenshot`)
//! and `methods`.
@@ -32,6 +33,7 @@ pub const METHODS: &[&str] = &[
"package.save",
"bitmap.import",
"outputs.export",
"material.export",
"render",
];
@@ -84,6 +86,7 @@ impl Headless {
"package.save" => self.save(str_of(p, "path")),
"bitmap.import" => self.import_bitmap(required(p, "path")?, str_of(p, "name")),
"outputs.export" => self.export(p),
"material.export" => self.export_material(p),
"render" => {
let o = RenderOptions {
view: str_of(p, "view").map(str::to_string),
@@ -253,6 +256,81 @@ mod tests {
assert_eq!(r[6]["result"]["failed"]["index"], 1);
}
/// A workspace session rooted at a fresh `inside` folder, with an `outside` sibling.
fn workspace_session(name: &str, write: bool) -> (std::path::PathBuf, std::path::PathBuf, Mutex<Headless>) {
let base = std::env::temp_dir().join(format!("mc-rpc-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (inside, outside) = (base.join("inside"), base.join("outside"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let ws = crate::AuthorizedWorkspace::new(Some(&inside), write.then_some(inside.as_path())).unwrap();
let h = Mutex::new(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
(inside, outside, h)
}
fn call(h: &Mutex<Headless>, method: &str, params: Value) -> Result<Value, String> {
h.lock().unwrap().handle(method, &params).map_err(|e| e.to_string())
}
#[test]
fn material_export_writes_a_portable_material_below_the_write_root() {
let (inside, _, h) = workspace_session("mat-ok", true);
std::fs::create_dir(inside.join("out")).unwrap();
let r = call(&h, "material.export", json!({"path": "out/brick", "size": 32})).unwrap();
assert_eq!(r["path"], "out/brick.mcmat");
let bytes = std::fs::read(inside.join("out/brick.mcmat")).unwrap();
assert_eq!(r["bytes"], bytes.len());
let (m, source) = materialcraft_engine::formats::material::read_material(&bytes).unwrap();
assert_eq!(m.size, [32, 32]);
assert!(m.maps.iter().any(|e| e.usage == "baseColor"));
assert!(!source.is_empty());
assert_eq!(std::fs::read_dir(inside.join("out")).unwrap().count(), 1, "no temporary files left behind");
// An explicit extension is kept (case-insensitively) and the file can be opened again.
let r = call(&h, "material.export", json!({"path": "again.MCMAT", "size": 16})).unwrap();
assert_eq!(r["path"], "again.MCMAT");
assert!(call(&h, "package.open", json!({"path": "again.MCMAT"})).is_ok());
}
#[test]
fn material_export_reports_bad_requests() {
let (inside, _, h) = workspace_session("mat-bad", true);
for bad in [json!({}), json!({"path": "m", "graph": 99}), json!({"path": "m", "values": {"no_such_input": 1}})] {
assert!(call(&h, "material.export", bad.clone()).is_err(), "{bad}");
}
assert!(call(&h, "material.export", json!({"path": "missing/dir/m"})).is_err(), "parent must exist");
assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0, "failed exports leave nothing behind");
}
#[test]
fn material_export_needs_a_write_root() {
let denied = session();
let e = call(&denied, "material.export", json!({"path": "m.mcmat"})).unwrap_err();
assert!(e.contains("not granted"), "{e}");
let (inside, _, read_only) = workspace_session("mat-readonly", false);
let e = call(&read_only, "material.export", json!({"path": "m.mcmat"})).unwrap_err();
assert!(e.contains("no write root"), "{e}");
assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0);
}
#[test]
fn material_export_cannot_escape_the_write_root() {
let (inside, outside, h) = workspace_session("mat-escape", true);
let abs = outside.join("abs.mcmat").display().to_string();
for p in ["../outside/m.mcmat", "a/../../outside/m.mcmat", "/tmp/m.mcmat", "a\\b.mcmat", "C:/m.mcmat", "./m.mcmat", abs.as_str()] {
let e = call(&h, "material.export", json!({"path": p, "size": 16}));
assert!(e.is_err(), "accepted {p:?}");
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(&outside, inside.join("link")).unwrap();
assert!(call(&h, "material.export", json!({"path": "link/m.mcmat", "size": 16})).is_err());
}
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "nothing written outside the root");
// The generic command path stays closed too: host paths are still refused.
let e = call(&h, "command.run", json!({"id": "file.exportMaterial", "params": {"path": abs}})).unwrap_err();
assert!(e.contains("disabled for automation"), "{e}");
}
#[test]
fn tcp_requires_the_token() {
use std::io::{BufRead, BufReader};
+44 -2
View File
@@ -159,6 +159,22 @@ pub struct ExportParams {
pub graph: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MaterialExportParams {
/// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The
/// parent folder must exist.
pub path: String,
/// Graph index (default: the open graph).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option<u32>,
/// Square size in pixels, rounded to a power of two from 16 to 8192 (default: the graph's size).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
/// Exposed input values to cook with and embed, by input id (see `session_inspect`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub values: Option<Value>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct RenderParams {
/// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output).
@@ -305,7 +321,7 @@ impl MaterialcraftMcp {
b.call(method, p).await
}
"package.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await,
"package.save" | "package.open" | "bitmap.import" | "outputs.export" | "command.batch" | "render" => {
"package.save" | "package.open" | "bitmap.import" | "outputs.export" | "material.export" | "command.batch" | "render" => {
Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)")))
}
_ => b.call(method, p).await,
@@ -426,6 +442,13 @@ impl MaterialcraftMcp {
to_result(self.call("outputs.export", params(&p)).await)
}
#[tool(description = "Cook a graph at full size and write it as a portable .mcmat material (cooked maps, exposed inputs, \
source package) to a path relative to the write root, for TextureCraft. Optional graph, size and exposed input values. \
Returns {path, bytes}.")]
async fn material_export(&self, Parameters(p): Parameters<MaterialExportParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("material.export", params(&p)).await)
}
#[tool(description = "Headless: render the material on the 3D view's scene, or a node's output (view 2d), as a PNG up to \
2048 px a side. In bridge mode use view_screenshot.")]
async fn view_render(&self, Parameters(p): Parameters<RenderParams>) -> Result<CallToolResult, McpError> {
@@ -467,7 +490,7 @@ impl MaterialcraftMcp {
(usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \
(templates: pbr, bricks, wood, …) or package_open, browse nodes with library_list, build with node_add / node_connect \
/ node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \
view_render (3d, or 2d for one node), then package_save and outputs_export. Undo: command_run edit.undo."
view_render (3d, or 2d for one node), then package_save, outputs_export or material_export (.mcmat for TextureCraft). Undo: command_run edit.undo."
)]
impl ServerHandler for MaterialcraftMcp {}
@@ -489,6 +512,25 @@ mod tests {
assert!(mcp.call("session.inspect", json!({})).await.is_ok());
}
#[tokio::test(flavor = "multi_thread")]
async fn material_export_tool_writes_through_the_workspace_only() {
let base = std::env::temp_dir().join(format!("mc-mcp-{}-material", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let args = || Parameters(MaterialExportParams { path: "m".into(), graph: None, size: Some(16), values: None });
let denied = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
assert_eq!(denied.material_export(args()).await.unwrap().is_error, Some(true));
let ws = crate::AuthorizedWorkspace::new(None, Some(&base)).unwrap();
let mcp = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
assert_eq!(mcp.material_export(args()).await.unwrap().is_error, Some(false));
assert!(base.join("m.mcmat").is_file());
let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None, size: Some(16), values: None });
assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true));
assert!(!base.parent().unwrap().join("m.mcmat").exists());
}
#[test]
fn oversized_replies_become_errors() {
let r = ok_json(&json!("x".repeat(crate::budgets::MAX_RESPONSE_BYTES)));
+7
View File
@@ -69,6 +69,13 @@ impl AuthorizedWorkspace {
Ok(())
}
/// Fail now, before any expensive work, when [`write`](Self::write) to `path` cannot succeed
/// for lack of a write root or because the path is malformed.
pub fn check_write(&self, path: &str) -> Result<(), AutomationError> {
relative_path(path)?;
self.write.as_ref().map(|_| ()).ok_or_else(|| denied("write"))
}
/// Create a directory (and its parents) below the write root.
pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> {
let rel = relative_path(path)?;
+10 -2
View File
@@ -144,13 +144,21 @@ fn graph_param(s: &Session, p: &J) -> Result<usize> {
Ok(gi)
}
/// The graph and cook options a material export request asks for: `graph?`, `size?` (px) and
/// `values?` (exposed input values). Shared by `file.exportMaterial` and the workspace-scoped
/// automation export, which supply their own destination.
pub fn material_request(s: &Session, cmd: &str, p: &J) -> Result<(usize, MaterialOptions)> {
let gi = graph_param(s, p)?;
let o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(cmd, s.pkg.graph(gi)?, p)?, ..Default::default() };
Ok((gi, o))
}
#[cfg(not(target_arch = "wasm32"))]
fn export_material(s: &mut Session, p: &J) -> Result<J> {
const CMD: &str = "file.exportMaterial";
let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") };
let gi = graph_param(s, p)?;
let mut o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(CMD, s.pkg.graph(gi)?, p)?, ..Default::default() };
let (gi, mut o) = material_request(s, CMD, p)?;
for (id, file) in p.get("inputs").and_then(J::as_object).into_iter().flatten() {
let file = file.as_str().ok_or_else(|| bad(CMD, format!("inputs.{id} must be an image path")))?;
let bytes = std::fs::read(file).map_err(|e| bad(CMD, format!("{file}: {e}")))?;
+7 -3
View File
@@ -1,6 +1,6 @@
# Control protocol and MCP
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials for TextureCraft) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** minor (`material_export` MCP tool) · **Target:** the professional node-based material workflow
Agents drive MaterialCraft three ways, all dispatching the same engine commands:
@@ -26,6 +26,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands:
| `package.open {path}` / `package.save {path?}` | headless | workspace-scoped package I/O |
| `bitmap.import {path, name?}` | headless | embed an image as a resource |
| `outputs.export {dir, format?, pattern?, depth?, graph?}` | headless | cook at full size and write every output |
| `material.export {path, graph?, size?, values?}` | headless | cook and write a portable `.mcmat` (`.mcmat` appended when missing) below the write root: the workspace-scoped `file.exportMaterial` |
| `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii |
| `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's screen position, fps, toasts |
| `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click |
@@ -122,6 +123,9 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k
`session_inspect`, `command_list`, `command_run`, `command_batch`, `library_list`, `graph_new`,
`node_add`, `node_connect`, `node_param`, `package_open`, `package_save`, `bitmap_import`,
`outputs_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`,
`outputs_export`, `material_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`,
`ui_screenshot`, `ui_inspect`, `ui_menu_invoke`, `ui_input`. `package_open` opens `.mcmat` files
too; exporting one is CLI-only for now (the workspace sandbox refuses `file.*` commands).
too, and `material_export` `{path, graph?, size?, values?}` writes one below `--write-root` (`path` is
relative, the parent folder must exist, `values` are exposed input values). The workspace sandbox
still refuses `file.*` commands, so a sandboxed agent exports through the tool, not `file.exportMaterial`;
mesh-map `inputs` stay a CLI feature.