diff --git a/Cargo.lock b/Cargo.lock index ccad933..37a0954 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -88,9 +88,16 @@ dependencies = [ "fast_image_resize", "jpeg-encoder", "png", + "serde_json", "zune-jpeg", ] +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + [[package]] name = "jpeg-encoder" version = "0.6.1" @@ -103,6 +110,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -153,6 +166,48 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -196,6 +251,12 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + [[package]] name = "zune-core" version = "0.4.12" diff --git a/Cargo.toml b/Cargo.toml index 73d3a08..22ce3ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,4 +11,9 @@ exif-sooc = { git = "https://github.com/oddharsh/exif-sooc" } fast_image_resize = "6" jpeg-encoder = "0.6" png = "0.17" +# JSON-RPC needs a real JSON reader. Hand-rolling one to save a dependency +# means hand-rolling string escapes and unicode, which is exactly where a +# hand-rolled parser goes quietly wrong on a path containing a quote. Derive +# is deliberately off: the server works in `Value` and pulls no proc-macro. +serde_json = "1" zune-jpeg = "0.4" diff --git a/README.md b/README.md index 890690e..015ab22 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,51 @@ grid, save what Instagram serves back, and score each against its source. That harness is the obvious next piece and the upload is the one step a program cannot do for you. +## Point a model at it + +`ig-prep mcp` speaks [MCP](https://modelcontextprotocol.io) on stdin and stdout, +so an assistant with file access can convert photographs where they already sit. + +```jsonc +// claude_desktop_config.json, or any MCP client's server list +{ + "mcpServers": { + "ig-prep": { + "command": "ig-prep", + "args": ["mcp", "--root", "/Users/you/Pictures"] + } + } +} +``` + +Then: *"convert everything in ~/Pictures/selects for Instagram."* + +Three tools. `ig_plan` reports what a conversion would do and writes nothing, +`ig_convert` does it, and `ig_check_rotation` is `--check`. They take the same +arguments the flags take and share the same defaults, because both surfaces call +the same function — a tool server that reimplements its own CLI grows a second +set of defaults and then disagrees with its own documentation. + +**Photographs never move and never enter the conversation.** The files are +already on the machine the server runs on, so a result carries paths, sizes and +dimensions rather than image data. That is a deliberate limit and not a missing +feature: a converted frame is a few hundred kilobytes, which is roughly a +megabyte of base64, and forty of them would be forty megabytes of a model's +context spent on pixels it cannot look at anyway. + +**`--root` is the boundary.** Every path argument, inputs and output directory +alike, is resolved through its symlinks and refused if it lands outside. Without +it the server will convert anything it can read, which is fine for a tool you +drive yourself and is worth thinking about before handing it to an agent. + +One call converts at most 200 files, and says how many it left, because a result +listing 200 conversions of a 900-file directory otherwise reads as a complete +run. + +The server answers the 2026-07-28 revision and the three before it. Both eras +stay because a legacy client has no fall-forward mechanism: pointed at a +modern-only server it does not negotiate down, it fails. + ## --check A HEIF can state its rotation twice: as a container transform (`irot`, `imir`) diff --git a/src/decode.rs b/src/decode.rs index 7d71116..40fd773 100644 --- a/src/decode.rs +++ b/src/decode.rs @@ -68,14 +68,58 @@ fn read_head(path: &Path) -> Result, String> { Ok(b) } +/// Decode a JPEG to three channels. +/// +/// `jpeg_set_out_colorspace` is a REQUEST rather than an instruction, and for a +/// single-channel source zune-jpeg declines it and returns Luma anyway. That +/// declining is silent, which is what makes it worth a comment: the buffer +/// comes back at one byte per pixel, `Rgb::new` labels it as three, and the +/// mismatch surfaces two layers later inside the resizer as "Size of buffer is +/// smaller than required" — an error that names neither the file nor its +/// colour. Every black-and-white JPEG failed that way. +/// +/// So the colourspace the decoder actually USED is what gets expanded here, +/// never the one it was asked for. The length check below is the backstop for +/// the next colourspace this misses: a decoder disagreeing with its own +/// dimensions should be caught at the decode boundary, where the file name is +/// still in hand. fn jpeg(bytes: &[u8]) -> Result { + use zune_jpeg::zune_core::colorspace::ColorSpace; + let mut d = zune_jpeg::JpegDecoder::new(bytes); d.set_options( zune_jpeg::zune_core::options::DecoderOptions::default() - .jpeg_set_out_colorspace(zune_jpeg::zune_core::colorspace::ColorSpace::RGB), + .jpeg_set_out_colorspace(ColorSpace::RGB), ); let px = d.decode().map_err(|e| format!("jpeg: {e:?}"))?; let (w, h) = d.dimensions().ok_or("jpeg: no dimensions")?; + let space = d.get_output_colorspace().ok_or("jpeg: no colourspace")?; + + let px = match space { + ColorSpace::RGB => px, + ColorSpace::Luma => px.iter().flat_map(|&v| [v, v, v]).collect(), + ColorSpace::LumaA => px + .as_chunks::<2>() + .0 + .iter() + .flat_map(|c| [c[0], c[0], c[0]]) + .collect(), + ColorSpace::RGBA => px + .as_chunks::<4>() + .0 + .iter() + .flat_map(|c| [c[0], c[1], c[2]]) + .collect(), + other => return Err(format!("jpeg: unsupported colourspace {other:?}")), + }; + + let want = w * h * 3; + if px.len() != want { + return Err(format!( + "jpeg: decoded {} bytes for a {w}x{h} {space:?} image, expected {want}", + px.len() + )); + } Ok(Rgb::new(w as u32, h as u32, px)) } @@ -89,7 +133,9 @@ fn png(bytes: &[u8]) -> Result { let px = match info.color_type { png::ColorType::Rgb => buf[..info.buffer_size()].to_vec(), png::ColorType::Rgba => buf[..info.buffer_size()] - .chunks_exact(4) + .as_chunks::<4>() + .0 + .iter() .flat_map(|c| [c[0], c[1], c[2]]) .collect(), png::ColorType::Grayscale => buf[..info.buffer_size()] @@ -284,7 +330,9 @@ fn tiff(d: &[u8]) -> Result { if samples == 3 { raw } else { - raw.chunks_exact(4) + raw.as_chunks::<4>() + .0 + .iter() .flat_map(|c| [c[0], c[1], c[2]]) .collect() } @@ -308,3 +356,59 @@ fn tiff(d: &[u8]) -> Result { }; Ok(Rgb::new(w, h, px)) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A grayscale JPEG must come back as three channels. + /// + /// This is a regression rather than a nicety: `jpeg_set_out_colorspace` is + /// a request the decoder declines for a single-channel source, so every + /// black-and-white JPEG used to reach the resizer at a third of the length + /// its dimensions claimed and die there with an error naming neither. + /// Built here rather than committed as a fixture so the test carries its + /// own input. + #[test] + fn grayscale_jpeg_expands_to_rgb() { + let (w, h) = (32usize, 24usize); + let luma: Vec = (0..w * h).map(|i| (i % 256) as u8).collect(); + let mut encoded = Vec::new(); + jpeg_encoder::Encoder::new(&mut encoded, 90) + .encode(&luma, w as u16, h as u16, jpeg_encoder::ColorType::Luma) + .expect("encode a luma jpeg"); + + let img = jpeg(&encoded).expect("decode the luma jpeg"); + assert_eq!((img.w, img.h), (w as u32, h as u32)); + assert_eq!(img.px.len(), w * h * 3, "must be three channels"); + // Expanded rather than merely padded: a pixel is grey, so its three + // channels agree. + for px in img.px.as_chunks::<3>().0.iter() { + assert_eq!(px[0], px[1]); + assert_eq!(px[1], px[2]); + } + } + + /// The colour path is untouched by that expansion. + #[test] + fn colour_jpeg_still_decodes_to_rgb() { + let (w, h) = (32usize, 24usize); + let rgb: Vec = (0..w * h) + .flat_map(|i| { + [ + (i % 256) as u8, + ((i * 3) % 256) as u8, + ((i * 7) % 256) as u8, + ] + }) + .collect(); + let mut encoded = Vec::new(); + jpeg_encoder::Encoder::new(&mut encoded, 90) + .encode(&rgb, w as u16, h as u16, jpeg_encoder::ColorType::Rgb) + .expect("encode an rgb jpeg"); + + let img = jpeg(&encoded).expect("decode the rgb jpeg"); + assert_eq!((img.w, img.h), (w as u32, h as u32)); + assert_eq!(img.px.len(), w * h * 3); + } +} diff --git a/src/encode.rs b/src/encode.rs index a67f28c..ab77c73 100644 --- a/src/encode.rs +++ b/src/encode.rs @@ -8,20 +8,60 @@ //! successive halvings visibly smear saturated edges. The cost is bytes on an //! upload, which nobody sees. //! -//! UNVERIFIED, like the rest of the Instagram-facing assumptions here: worth a -//! round trip before anyone treats it as fact. +//! 4:2:2 is the middle, and it is the honest one for a camera that shoots +//! 4:2:2. It is worth being precise about why the source ratio does NOT settle +//! the question on its own. A Fujifilm HIF halves chroma horizontally in its +//! own landscape orientation, so a 7728x5152 frame carries a 3864x5152 chroma +//! plane; held vertically that becomes 5152x3864, and the halved axis lands on +//! the LONG edge of the portrait. Against a 1440x2160 output that is still +//! 3.58x horizontally and 1.79x vertically of real chroma to average down. +//! Full-resolution output chroma is therefore measured rather than invented, +//! and 4:2:0 here would discard detail the source genuinely resolves. +//! +//! That reasoning holds only while the downscale stays large. Somebody +//! delivering at or near native size has a 4:2:2 source that cannot fill a +//! 4:4:4 output, and should say `--422` and mean it. +//! +//! UNVERIFIED, like the rest of the Instagram-facing assumptions here: which of +//! the three survives a round trip best is exactly what the upload harness is +//! supposed to settle. use crate::image::Rgb; use jpeg_encoder::{ColorType, Encoder, SamplingFactor}; -pub fn jpeg(img: &Rgb, quality: u8, subsample: bool) -> Result, String> { +/// What the chroma plane is worth on the way out, named for the JPEG ratio. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Chroma { + /// 4:4:4, chroma at luma resolution. + Full, + /// 4:2:2, chroma halved horizontally. What the camera shot. + Halved, + /// 4:2:0, chroma halved on both axes. What Instagram will store anyway. + Quartered, +} + +impl Chroma { + fn sampling(self) -> SamplingFactor { + match self { + Chroma::Full => SamplingFactor::R_4_4_4, + Chroma::Halved => SamplingFactor::R_4_2_2, + Chroma::Quartered => SamplingFactor::R_4_2_0, + } + } + + pub fn label(self) -> &'static str { + match self { + Chroma::Full => "4:4:4", + Chroma::Halved => "4:2:2", + Chroma::Quartered => "4:2:0", + } + } +} + +pub fn jpeg(img: &Rgb, quality: u8, chroma: Chroma) -> Result, String> { let mut out = Vec::new(); let mut enc = Encoder::new(&mut out, quality); - enc.set_sampling_factor(if subsample { - SamplingFactor::F_2_2 - } else { - SamplingFactor::F_1_1 - }); + enc.set_sampling_factor(chroma.sampling()); enc.set_progressive(false); enc.encode(&img.px, img.w as u16, img.h as u16, ColorType::Rgb) .map_err(|e| format!("encode: {e}"))?; diff --git a/src/image.rs b/src/image.rs index 4b13518..6c087dc 100644 --- a/src/image.rs +++ b/src/image.rs @@ -124,7 +124,7 @@ pub fn resize(src: &Rgb, w: u32, h: u32) -> Result { // took a file from 2.4s to under a second. let table = srgb_to_linear_table(); let mut bytes = vec![0u8; src.px.len() * 4]; - for (chunk, &i) in bytes.chunks_exact_mut(4).zip(src.px.iter()) { + for (chunk, &i) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(src.px.iter()) { chunk.copy_from_slice(&table[i as usize].to_ne_bytes()); } let src_img = Image::from_vec_u8(src.w, src.h, bytes, PixelType::F32x3) @@ -140,7 +140,9 @@ pub fn resize(src: &Rgb, w: u32, h: u32) -> Result { let out: Vec = dst_img .buffer() - .chunks_exact(4) + .as_chunks::<4>() + .0 + .iter() .map(|c| linear_to_srgb(f32::from_ne_bytes([c[0], c[1], c[2], c[3]]))) .collect(); Ok(Rgb::new(w, h, out)) diff --git a/src/main.rs b/src/main.rs index a1d2f1e..3382ea2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,9 @@ mod encode; mod geometry; mod heif; mod image; +mod mcp; +use encode::Chroma; use geometry::{Fit, Gravity}; use std::path::{Path, PathBuf}; @@ -33,20 +35,58 @@ FIT OPTIONS -w, --width target width (default 1440) -q <1-100> JPEG quality (default 95) - --420 subsample chroma (default is 4:4:4) + --444 chroma at full resolution (default). The 3.58x/1.79x + downscale means a 4:2:2 source still fills it. + --422 chroma halved horizontally, matching what the camera + shot. The honest choice near native size. + --420 chroma halved on both axes, matching what Instagram + stores anyway. Smallest upload. --pad-color fill for --pad (default ffffff) -o, --out output directory (default ./ig) -n, --dry-run report the plan for each file, write nothing --check report files whose two rotations disagree, convert nothing. Exits non-zero if any do. -h, --help + +MCP SERVER + ig-prep mcp [--root ] + Speak MCP on stdin and stdout, so a model with file access + can convert photographs where they already are. Tools: + ig_plan, ig_convert, ig_check_rotation. --root confines every + path argument to one directory; without it any readable path + may be converted. "; fn main() { + // `mcp` is a MODE rather than an option, and it is matched before the + // option loop because everything below parses arguments for a conversion + // this process is not going to perform. + let argv: Vec = std::env::args().skip(1).collect(); + if argv.first().map(String::as_str) == Some("mcp") { + let mut root = None; + let mut rest = argv[1..].iter(); + while let Some(a) = rest.next() { + match a.as_str() { + "--root" => match rest.next() { + Some(d) => root = Some(PathBuf::from(d)), + None => { + eprintln!("ig-prep: --root needs a directory"); + std::process::exit(2); + } + }, + other => { + eprintln!("ig-prep mcp: unknown option {other}"); + std::process::exit(2); + } + } + } + std::process::exit(mcp::serve(root)); + } + let mut args = std::env::args().skip(1).peekable(); let (mut paths, mut fit, mut gravity) = (Vec::new(), Fit::Full, Gravity::Center); let mut width = geometry::TARGET_WIDTH; - let (mut quality, mut subsample, mut dry) = (95u8, false, false); + let (mut quality, mut chroma, mut dry) = (95u8, Chroma::Full, false); let mut check = false; let mut out_dir = PathBuf::from("ig"); let mut pad = [255u8, 255, 255]; @@ -57,7 +97,9 @@ fn main() { "--full" => fit = Fit::Full, "--crop" => fit = Fit::Crop, "--pad" => fit = Fit::Pad, - "--420" => subsample = true, + "--444" => chroma = Chroma::Full, + "--422" => chroma = Chroma::Halved, + "--420" => chroma = Chroma::Quartered, "-n" | "--dry-run" => dry = true, "--check" => check = true, "--gravity" => { @@ -106,37 +148,136 @@ fn main() { std::process::exit(1); } - let threads = std::thread::available_parallelism() - .map(|n| n.get()) - .unwrap_or(4) - .min(files.len()); - let chunk = files.len().div_ceil(threads); let opts = Opts { fit, gravity, width, quality, - subsample, + chroma, dry, pad, out_dir: out_dir.clone(), }; - let lines: Vec> = std::thread::scope(|s| { + for r in run_all(&files, &opts) { + println!("{}", r.line()); + } +} + +/// Convert a batch across the available cores, in input order. +/// +/// Shared by the CLI and the MCP server so that a conversion cannot depend on +/// which door it came through. Order is preserved because a caller matching +/// results against the paths it sent has no other key to match on: the report +/// carries the source path, but a model reading the text lines reads them +/// positionally. +pub fn run_all(files: &[PathBuf], opts: &Opts) -> Vec { + if files.is_empty() { + return Vec::new(); + } + let threads = std::thread::available_parallelism() + .map(|n| n.get()) + .unwrap_or(4) + .min(files.len()); + let chunk = files.len().div_ceil(threads); + let parts: Vec> = std::thread::scope(|s| { let handles: Vec<_> = files .chunks(chunk) - .map(|part| { - let opts = &opts; - s.spawn(move || part.iter().map(|p| one(p, opts)).collect::>()) - }) + .map(|part| s.spawn(move || part.iter().map(|p| one(p, opts)).collect::>())) .collect(); handles.into_iter().map(|h| h.join().unwrap()).collect() }); - for l in lines.into_iter().flatten() { - println!("{l}"); + parts.into_iter().flatten().collect() +} + +/// Report files whose container transform and EXIF Orientation disagree. +/// +/// Carrying BOTH is normal and is what every Fujifilm HIF does; a viewer that +/// applies one of them is right. What cannot be recovered is the two saying +/// DIFFERENT things, because then there is no orientation the file agrees on +/// and every viewer is wrong in some way. Only that case is a failure here. +/// How a file's two statements about its own rotation line up. +pub enum Agreement { + /// Container transform and EXIF Orientation, saying the same thing. What + /// every Fujifilm HIF does, and not a problem. + Both, + /// The two say DIFFERENT things, so no viewer can be right. + Disagree, + /// Only one of the two is present, which is unambiguous. + One, + /// Neither is present, so the pixels are already upright. + Neither, + Unreadable, +} + +impl Agreement { + pub fn label(&self) -> &'static str { + match self { + Agreement::Both => "both", + Agreement::Disagree => "disagree", + Agreement::One => "one", + Agreement::Neither => "neither", + Agreement::Unreadable => "unreadable", + } } } +pub struct Check { + pub name: String, + pub source: PathBuf, + pub agreement: Agreement, + /// What each of the two says, as prose, present only when that one is. + pub container: Option, + pub exif: Option, + pub error: Option, +} + +pub fn check_one(path: &Path) -> Check { + let name = path + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(); + let bytes = match std::fs::read(path) { + Ok(b) => b, + Err(e) => { + return Check { + name, + source: path.to_path_buf(), + agreement: Agreement::Unreadable, + container: None, + exif: None, + error: Some(e.to_string()), + }; + } + }; + let exif = exif_sooc::read(path) + .ok() + .and_then(|p| p.get("Orientation").and_then(|t| t.value.as_i64())) + .and_then(|v| heif::Transform::from_exif(v as u16)); + let container = heif::container_transform(&bytes); + let agreement = match (exif, container) { + (Some(e), Some(c)) if e == c => Agreement::Both, + (Some(_), Some(_)) => Agreement::Disagree, + (Some(_), None) | (None, Some(_)) => Agreement::One, + (None, None) => Agreement::Neither, + }; + Check { + name, + source: path.to_path_buf(), + agreement, + container: container.map(|c| c.describe()), + exif: exif.map(|e| e.describe()), + error: None, + } +} + +/// The note a disagreement earns. Shared so the CLI and the MCP server explain +/// the same finding the same way. +pub const DISAGREE_NOTE: &str = "A file whose two rotations disagree has no orientation every viewer can \ +agree on. Converting it here bakes ONE of them into the pixels and drops the tags, which at least \ +makes the result unambiguous."; + /// Report files whose container transform and EXIF Orientation disagree. /// /// Carrying BOTH is normal and is what every Fujifilm HIF does; a viewer that @@ -146,32 +287,21 @@ fn main() { fn run_check(files: &[PathBuf]) -> i32 { let (mut both, mut disagree, mut one, mut neither) = (0, 0, 0, 0); for path in files { - let name = path.file_name().unwrap_or_default().to_string_lossy(); - let bytes = match std::fs::read(path) { - Ok(b) => b, - Err(e) => { - println!("{name}: {e}"); - continue; - } - }; - let exif = exif_sooc::read(path) - .ok() - .and_then(|p| p.get("Orientation").and_then(|t| t.value.as_i64())) - .and_then(|v| heif::Transform::from_exif(v as u16)); - let container = heif::container_transform(&bytes); - - match (exif, container) { - (Some(e), Some(c)) if e == c => both += 1, - (Some(e), Some(c)) => { + let c = check_one(path); + match c.agreement { + Agreement::Unreadable => println!("{}: {}", c.name, c.error.unwrap_or_default()), + Agreement::Both => both += 1, + Agreement::Disagree => { disagree += 1; println!( - "{name}: DISAGREE container says {}, EXIF says {}", - c.describe(), - e.describe() + "{}: DISAGREE container says {}, EXIF says {}", + c.name, + c.container.unwrap_or_default(), + c.exif.unwrap_or_default() ); } - (Some(_), None) | (None, Some(_)) => one += 1, - (None, None) => neither += 1, + Agreement::One => one += 1, + Agreement::Neither => neither += 1, } } println!( @@ -179,30 +309,113 @@ fn run_check(files: &[PathBuf]) -> i32 { files.len() ); if disagree > 0 { - println!( - "\nA file whose two rotations disagree has no orientation every viewer can\n\ - agree on. Converting it here bakes ONE of them into the pixels and drops\n\ - the tags, which at least makes the result unambiguous." - ); + println!("\n{DISAGREE_NOTE}"); 1 } else { 0 } } -struct Opts { - fit: Fit, - gravity: Gravity, - width: u32, - quality: u8, - subsample: bool, - dry: bool, +pub struct Opts { + pub fit: Fit, + pub gravity: Gravity, + pub width: u32, + pub quality: u8, + pub chroma: Chroma, + pub dry: bool, pad: [u8; 3], - out_dir: PathBuf, + pub out_dir: PathBuf, } -fn one(path: &Path, o: &Opts) -> String { - let name = path.file_name().unwrap_or_default().to_string_lossy(); +impl Opts { + /// The defaults the CLI applies, so a caller that sets nothing gets the + /// same conversion the bare `ig-prep ` command performs. + pub fn defaults() -> Opts { + Opts { + fit: Fit::Full, + gravity: Gravity::Center, + width: geometry::TARGET_WIDTH, + quality: 95, + chroma: Chroma::Full, + dry: false, + pad: [255, 255, 255], + out_dir: PathBuf::from("ig"), + } + } + + /// `--pad-color`, parsed from `ffffff` or `#ffffff`. Anything else leaves + /// the fill alone rather than substituting a colour nobody asked for. + pub fn set_pad_color(&mut self, hex: &str) { + let h = hex.trim_start_matches('#'); + if h.len() == 6 { + for i in 0..3 { + self.pad[i] = u8::from_str_radix(&h[i * 2..i * 2 + 2], 16).unwrap_or(255); + } + } + } +} + +/// What became of one file. +/// +/// The CLI renders this as a line and the MCP server hands the same fields +/// back as JSON, so the two surfaces cannot end up describing different +/// conversions. Every field is optional in the way the failure actually is: +/// a file that would not decode has no dimensions, and a dry run has no +/// output path, rather than either being reported as a zero. +pub struct Report { + pub name: String, + pub source: PathBuf, + /// Display dimensions, after rotation. Every later number derives from + /// these rather than from what the decoder happened to hand back. + pub from: Option<(u32, u32)>, + pub to: Option<(u32, u32)>, + /// True when the source ratio is outside what Instagram shows uncropped. + pub outside_band: bool, + pub output: Option, + pub bytes: Option, + pub chroma: &'static str, + pub error: Option, + note: &'static str, +} + +impl Report { + fn failed(path: &Path, name: String, e: String) -> Report { + Report { + name, + source: path.to_path_buf(), + from: None, + to: None, + outside_band: false, + output: None, + bytes: None, + chroma: "", + error: Some(e), + note: "", + } + } + + /// The one line the CLI prints. Kept here so that changing what a run says + /// changes it in one place for both surfaces. + pub fn line(&self) -> String { + if let Some(e) = &self.error { + return format!("{}: {e}", self.name); + } + let (fw, fh) = self.from.unwrap_or((0, 0)); + let (tw, th) = self.to.unwrap_or((0, 0)); + let summary = format!("{}: {fw}x{fh} -> {tw}x{th}{}", self.name, self.note); + match self.bytes { + Some(b) => format!("{summary} {} {} KB", self.chroma, b / 1024), + None => summary, + } + } +} + +pub fn one(path: &Path, o: &Opts) -> Report { + let name = path + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(); // Orientation comes from the metadata reader rather than from the decoder, // because a HEIF's rotation lives in its EXIF and sips does not apply it. @@ -213,7 +426,7 @@ fn one(path: &Path, o: &Opts) -> String { let decoded = match decode::open(path) { Ok(d) => d, - Err(e) => return format!("{name}: {e}"), + Err(e) => return Report::failed(path, name, e), }; // Trust the measurement over the flag where the measurement can tell. @@ -249,12 +462,20 @@ fn one(path: &Path, o: &Opts) -> String { } else { "" }; - let summary = format!( - "{name}: {}x{} -> {}x{}{note}", - img.w, img.h, plan.canvas.0, plan.canvas.1 - ); + let mut report = Report { + name, + source: path.to_path_buf(), + from: Some((img.w, img.h)), + to: Some(plan.canvas), + outside_band: plan.outside_band, + output: None, + bytes: None, + chroma: o.chroma.label(), + error: None, + note, + }; if o.dry { - return summary; + return report; } let cropped = if plan.crop == (0, 0, img.w, img.h) { @@ -264,7 +485,7 @@ fn one(path: &Path, o: &Opts) -> String { }; let scaled = match image::resize(&cropped, plan.scale.0, plan.scale.1) { Ok(s) => s, - Err(e) => return format!("{name}: {e}"), + Err(e) => return Report::failed(path, report.name, e), }; let final_img = if plan.canvas != plan.scale { scaled.pad_onto( @@ -277,23 +498,27 @@ fn one(path: &Path, o: &Opts) -> String { } else { scaled }; - let bytes = match encode::jpeg(&final_img, o.quality, o.subsample) { + let bytes = match encode::jpeg(&final_img, o.quality, o.chroma) { Ok(b) => b, - Err(e) => return format!("{name}: {e}"), + Err(e) => return Report::failed(path, report.name, e), }; let dest = o.out_dir.join(format!( "{}.jpg", path.file_stem().unwrap_or_default().to_string_lossy() )); match std::fs::write(&dest, &bytes) { - Ok(()) => format!("{summary} {} KB", bytes.len() / 1024), - Err(e) => format!("{name}: {e}"), + Ok(()) => { + report.bytes = Some(bytes.len()); + report.output = Some(dest); + report + } + Err(e) => Report::failed(path, report.name, format!("{}: {e}", dest.display())), } } const EXTS: [&str; 8] = ["jpg", "jpeg", "heif", "heic", "hif", "jxl", "png", "avif"]; -fn expand(paths: &[PathBuf]) -> Vec { +pub fn expand(paths: &[PathBuf]) -> Vec { let mut out = Vec::new(); for p in paths { if p.is_dir() { diff --git a/src/mcp.rs b/src/mcp.rs new file mode 100644 index 0000000..dd29a78 --- /dev/null +++ b/src/mcp.rs @@ -0,0 +1,1116 @@ +//! `ig-prep mcp` — the converter as a tool a model can call. +//! +//! The point of this mode is that the photographs never move. A model with +//! file access runs this server over stdio, names paths on the machine the +//! photographs are already on, and gets back the files it asked for plus the +//! numbers describing what happened. Nothing is uploaded, nothing is encoded +//! into the conversation, and the conversion is the same one `ig-prep ` +//! performs, because both surfaces call the same `one()`. +//! +//! That last part is the design rather than an implementation detail. A tool +//! server that re-implements its own CLI grows a second set of defaults and +//! then disagrees with the documentation; here `Opts::defaults()` is the CLI's +//! defaults, and a caller who sets no arguments gets exactly `ig-prep `. +//! +//! WHAT IT DELIBERATELY DOES NOT DO: return image bytes. A converted 1440px +//! frame is a few hundred kilobytes, which is a megabyte of base64 in a tool +//! result, and a model that asked to convert forty photographs does not want +//! forty megabytes of them in its context. The files are on disk, where the +//! caller can already reach them, so the result carries paths and sizes. +//! +//! ## Transport +//! +//! Newline-delimited JSON-RPC on stdin and stdout, which is MCP's stdio +//! transport. Nothing else may write to stdout: a stray `println!` corrupts +//! the stream and the client reports a parse error rather than the print. +//! Diagnostics go to stderr. The one real hazard is the HEIF path, which +//! shells out to `sips`; `decode.rs` uses `.output()`, so the child's stdout +//! is captured rather than inherited, and that is load-bearing here in a way +//! it is not for the CLI. + +use crate::encode::Chroma; +use crate::geometry::{Fit, Gravity}; +use crate::{Agreement, Opts, Report}; +use serde_json::{Map, Value, json}; +use std::io::{BufRead, Write}; +use std::path::{Path, PathBuf}; + +const SERVER_NAME: &str = "ig-prep"; +const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// The revision this server declares, and the three legacy ones it still +/// answers. Both eras stay for the reason the spec gives: a legacy client has +/// no fall-forward mechanism, so pointed at a modern-only server it does not +/// negotiate down, it simply fails. Today essentially every stdio client in +/// the wild opens with `initialize`, which is the legacy handshake. +const MCP_PROTOCOL: &str = "2026-07-28"; +const MCP_SUPPORTED: [&str; 4] = [MCP_PROTOCOL, "2025-06-18", "2025-03-26", "2024-11-05"]; + +/// Files converted in one call before the batch is cut short. +/// +/// A cap is needed because a caller can name a directory and a directory can +/// hold a thousand 40-megapixel frames, which is tens of minutes of work under +/// a client that will have given up long before. What the cap must not do is +/// truncate quietly: a result listing 200 conversions of a 900-file directory +/// reads as a complete run, so the overflow is reported by count and the +/// caller is told to narrow the request. +const MAX_FILES: usize = 200; + +// ── transport ───────────────────────────────────────────────────────── + +pub fn serve(root: Option) -> i32 { + // Resolved once, at startup, so that a symlink swapped underneath us later + // cannot widen the boundary mid-session. + let root = match root { + Some(r) => match r.canonicalize() { + Ok(c) => Some(c), + Err(e) => { + eprintln!("ig-prep: --root {}: {e}", r.display()); + return 1; + } + }, + None => None, + }; + match &root { + Some(r) => eprintln!("ig-prep mcp: confined to {}", r.display()), + None => eprintln!( + "ig-prep mcp: unconfined — any readable path may be converted. \ + Pass --root DIR to limit it." + ), + } + + let stdin = std::io::stdin(); + let mut stdout = std::io::stdout(); + for line in stdin.lock().lines() { + let line = match line { + Ok(l) => l, + Err(e) => { + eprintln!("ig-prep mcp: stdin: {e}"); + return 1; + } + }; + if line.trim().is_empty() { + continue; + } + let response = match serde_json::from_str::(&line) { + Ok(req) => handle(&req, root.as_deref()), + // A parse failure has no id to answer under, which is what the + // spec's null id is for. + Err(e) => Some(error( + Value::Null, + -32700, + &format!("parse error: {e}"), + None, + )), + }; + if let Some(r) = response { + // A write failure means the client is gone; there is nothing left + // to report it to. + if writeln!(stdout, "{r}").is_err() || stdout.flush().is_err() { + return 0; + } + } + } + 0 +} + +/// `None` for a notification, which by JSON-RPC carries no id and gets no +/// answer. Replying to one is a protocol error that some clients treat as a +/// stray message and others as a fault. +fn handle(req: &Value, root: Option<&Path>) -> Option { + let method = req.get("method").and_then(Value::as_str).unwrap_or(""); + let id = req.get("id").cloned(); + let id = match id { + Some(Value::Null) | None => return None, + Some(i) => i, + }; + let params = req.get("params").cloned().unwrap_or_else(|| json!({})); + + // The era is chosen by the shape of the request and by nothing else. A + // `_meta` block is a modern client declaring itself; its absence is how a + // legacy client presents itself, so absence cannot also be read as + // malformed. `initialize` selects legacy outright. + let meta = params.get("_meta"); + if let Some(m) = meta + && let Some(v) = m.get("protocolVersion").and_then(Value::as_str) + && !MCP_SUPPORTED.contains(&v) + { + return Some(error( + id, + -32022, + &format!("unsupported protocol version {v}"), + Some(json!({ "supported": MCP_SUPPORTED, "requested": v })), + )); + } + + match method { + "initialize" => { + let asked = params + .get("protocolVersion") + .and_then(Value::as_str) + .unwrap_or(""); + // Echo the client's revision when we speak it. Otherwise answer + // with the newest LEGACY one rather than with `MCP_PROTOCOL`, + // since a client that opened with `initialize` is by definition + // not speaking the revision that deleted `initialize`. + let agreed = if MCP_SUPPORTED.contains(&asked) { + asked + } else { + MCP_SUPPORTED[1] + }; + Some(ok( + id, + json!({ + "protocolVersion": agreed, + "capabilities": { "tools": { "listChanged": false } }, + "serverInfo": { "name": SERVER_NAME, "version": SERVER_VERSION }, + "instructions": INSTRUCTIONS, + }), + )) + } + // The modern revision replaces the handshake with this, and says + // servers MUST implement it. + "server/discover" => Some(ok( + id, + json!({ + "serverInfo": { "name": SERVER_NAME, "version": SERVER_VERSION }, + "capabilities": { "tools": { "listChanged": false } }, + "protocolVersions": MCP_SUPPORTED, + "instructions": INSTRUCTIONS, + }), + )), + // Removed by 2026-07-28 and kept because legacy clients send it and it + // costs nothing. + "ping" => Some(ok(id, json!({}))), + "tools/list" => Some(ok( + id, + json!({ + "tools": tools(), + // A tool list changes only when the binary does, so a client + // may hold it for as long as it holds the process. + "ttlMs": 3_600_000, + "cacheScope": "session", + }), + )), + "tools/call" => Some(call(id, ¶ms, root)), + _ => Some(error(id, -32601, &format!("unknown method {method}"), None)), + } +} + +const INSTRUCTIONS: &str = "\ +Prepares photographs for Instagram's compression, on this machine. Name paths \ +to files or directories; converted JPEGs are written to disk and the result \ +reports paths and sizes rather than image bytes. Start with ig_plan to see \ +what a conversion would do, then ig_convert to do it. The default delivers the \ +whole frame at 1440px wide so the framing choice stays in the Instagram app \ +and Instagram has nothing left to resample — tell the photographer to drag \ +rather than pinch-zoom, because zooming changes the scale and hands the \ +resample back."; + +// ── results ─────────────────────────────────────────────────────────── + +fn envelope(mut result: Map) -> Value { + // Emitted unconditionally, which is safe in both directions: a JSON-RPC + // client ignores unknown result fields, and the modern spec tells a modern + // client to read a missing `resultType` as complete anyway. One code path + // beats two. + result.insert("resultType".into(), json!("complete")); + result.insert( + "_meta".into(), + json!({ + "io.modelcontextprotocol/serverInfo": { + "name": SERVER_NAME, "version": SERVER_VERSION + } + }), + ); + Value::Object(result) +} + +fn ok(id: Value, result: Value) -> Value { + let map = match result { + Value::Object(m) => m, + other => { + let mut m = Map::new(); + m.insert("value".into(), other); + m + } + }; + json!({ "jsonrpc": "2.0", "id": id, "result": envelope(map) }) +} + +fn error(id: Value, code: i32, message: &str, data: Option) -> Value { + let mut e = json!({ "code": code, "message": message }); + if let Some(d) = data { + e["data"] = d; + } + json!({ "jsonrpc": "2.0", "id": id, "error": e }) +} + +/// A tool that failed at its own job rather than at the protocol. `isError` +/// keeps the failure inside the result, which is what lets a model read it and +/// try something else instead of the whole call unwinding. +fn tool_error(id: Value, message: String) -> Value { + ok( + id, + json!({ + "content": [{ "type": "text", "text": message }], + "isError": true, + }), + ) +} + +fn tool_ok(id: Value, text: String, structured: Value) -> Value { + ok( + id, + json!({ + "content": [{ "type": "text", "text": text }], + "structuredContent": structured, + "isError": false, + }), + ) +} + +// ── tools ───────────────────────────────────────────────────────────── + +/// Shared by all three tools: what to operate on. +fn paths_schema(verb: &str) -> Value { + json!({ + "type": "array", + "items": { "type": "string" }, + "minItems": 1, + "description": format!( + "Files or directories on this machine to {verb}. A directory is \ + read one level deep for jpg, jpeg, heif, heic, hif, jxl, png and \ + avif." + ), + }) +} + +fn geometry_props(map: &mut Map) { + map.insert( + "fit".into(), + json!({ + "type": "string", + "enum": ["full", "crop", "pad"], + "default": "full", + "description": "full delivers the whole frame at the target width and leaves the \ + framing choice to the Instagram app, which costs nothing because \ + cropping a portrait to 4:5 removes height only. crop takes the \ + nearest allowed ratio here instead. pad keeps the whole frame and \ + fills the rest.", + }), + ); + map.insert( + "gravity".into(), + json!({ + "type": "string", + "enum": ["center", "top", "bottom"], + "default": "center", + "description": "Where fit=crop takes its window. Ignored by the other two.", + }), + ); + map.insert( + "width".into(), + json!({ + "type": "integer", + "minimum": 1, + "maximum": 16384, + "default": 1440, + "description": "Target delivery width in pixels. 1440 is a deliberate guess rather \ + than a measured fact: guessing high costs Instagram one clean \ + downscale, guessing low makes it upscale and invent detail. A frame \ + already narrower than this is never enlarged.", + }), + ); +} + +fn tools() -> Value { + let mut plan_props = Map::new(); + plan_props.insert("paths".into(), paths_schema("inspect")); + geometry_props(&mut plan_props); + + let mut convert_props = plan_props.clone(); + convert_props.insert( + "out_dir".into(), + json!({ + "type": "string", + "default": "ig", + "description": "Directory to write JPEGs into, created if missing. Each output is \ + named after its source stem.", + }), + ); + convert_props.insert( + "quality".into(), + json!({ + "type": "integer", "minimum": 1, "maximum": 100, "default": 95, + "description": "JPEG quality. High by default because Instagram re-encodes whatever \ + it receives, and every pre-compression pass compounds with that one.", + }), + ); + convert_props.insert( + "chroma".into(), + json!({ + "type": "string", + "enum": ["444", "422", "420"], + "default": "444", + "description": "Output chroma resolution. 444 hands Instagram's own encoder \ + full-resolution chroma to average rather than chroma already halved \ + once. 422 is the honest choice near native size, where a 4:2:2 \ + source cannot fill 4:4:4. 420 is the smallest upload.", + }), + ); + convert_props.insert( + "pad_color".into(), + json!({ + "type": "string", + "default": "ffffff", + "description": "Six-digit hex fill for fit=pad. Ignored otherwise.", + }), + ); + + json!([ + { + "name": "ig_plan", + "title": "Plan an Instagram conversion", + "description": "Report what converting these photographs would do — the display \ + dimensions after rotation, the size each would be delivered at, \ + and whether the frame falls outside the band Instagram shows \ + uncropped. Writes nothing. Run this first on a directory, both to \ + see the shape of the batch and to find files that will not decode.", + "inputSchema": { "type": "object", "properties": plan_props, "required": ["paths"] }, + "outputSchema": plan_output_schema(), + "annotations": { + "title": "Plan an Instagram conversion", + "readOnlyHint": true, "destructiveHint": false, + "idempotentHint": true, "openWorldHint": false, + }, + }, + { + "name": "ig_convert", + "title": "Convert photographs for Instagram", + "description": "Convert photographs and write sRGB JPEGs to disk. Reads JPEG, \ + HEIF/HEIC/HIF, JPEG XL and PNG. Rotation is read from metadata and \ + baked into the pixels, the downscale runs in linear light with \ + Lanczos3, and the result reports output paths and byte counts \ + rather than image data. HEIF and JPEG XL need `sips` (macOS) or \ + `djxl` on PATH; a file that cannot be decoded is reported by name \ + rather than skipped silently.", + "inputSchema": { "type": "object", "properties": convert_props, "required": ["paths"] }, + "outputSchema": convert_output_schema(), + "annotations": { + "title": "Convert photographs for Instagram", + // Writes new files, so not read-only. Not destructive: it only + // ever creates, and it creates under out_dir rather than beside + // the source. Idempotent because the same input and options + // produce the same bytes at the same path. + "readOnlyHint": false, "destructiveHint": false, + "idempotentHint": true, "openWorldHint": false, + }, + }, + { + "name": "ig_check_rotation", + "title": "Check for contradictory rotation metadata", + "description": "Report photographs whose two statements of their own rotation \ + disagree. A HEIF can say how to turn itself twice, once as a \ + container transform and once as EXIF Orientation; saying it twice \ + is normal and every Fujifilm HIF does it. Saying two DIFFERENT \ + things is the fault, because then no viewer is right and the \ + photograph has no defined orientation. Writes nothing.", + "inputSchema": { + "type": "object", + "properties": { "paths": paths_schema("check") }, + "required": ["paths"], + }, + "outputSchema": check_output_schema(), + "annotations": { + "title": "Check for contradictory rotation metadata", + "readOnlyHint": true, "destructiveHint": false, + "idempotentHint": true, "openWorldHint": false, + }, + }, + ]) +} + +fn file_props(converted: bool) -> Value { + let mut p = json!({ + "source": { "type": "string" }, + "from": { + "type": "array", "items": { "type": "integer" }, "minItems": 2, "maxItems": 2, + "description": "Display width and height after rotation. Absent if it would not decode.", + }, + "to": { + "type": "array", "items": { "type": "integer" }, "minItems": 2, "maxItems": 2, + "description": "Delivered width and height.", + }, + "outside_band": { + "type": "boolean", + "description": "True when the source ratio falls outside 4:5 to 1.91:1, so \ + Instagram will crop it unless fit=crop or fit=pad handled it here.", + }, + "error": { "type": "string", "description": "Present only if this file failed." }, + }); + if converted { + p["output"] = json!({ "type": "string", "description": "Path of the written JPEG." }); + p["bytes"] = json!({ "type": "integer" }); + p["chroma"] = json!({ "type": "string" }); + } + p +} + +fn plan_output_schema() -> Value { + json!({ + "type": "object", + "properties": { + "files": { "type": "array", "items": { "type": "object", "properties": file_props(false) } }, + "planned": { "type": "integer" }, + "failed": { "type": "integer" }, + "not_shown": { + "type": "integer", + "description": "Files matched but not reported, because the batch hit its cap.", + }, + }, + "required": ["files", "planned", "failed"], + }) +} + +fn convert_output_schema() -> Value { + json!({ + "type": "object", + "properties": { + "files": { "type": "array", "items": { "type": "object", "properties": file_props(true) } }, + "written": { "type": "integer" }, + "failed": { "type": "integer" }, + "out_dir": { "type": "string" }, + "not_converted": { + "type": "integer", + "description": "Files matched but not converted, because the batch hit its cap.", + }, + }, + "required": ["files", "written", "failed", "out_dir"], + }) +} + +fn check_output_schema() -> Value { + json!({ + "type": "object", + "properties": { + "files": { + "type": "array", + "items": { + "type": "object", + "properties": { + "source": { "type": "string" }, + "agreement": { + "type": "string", + "enum": ["both", "disagree", "one", "neither", "unreadable"], + }, + "container": { "type": "string" }, + "exif": { "type": "string" }, + "error": { "type": "string" }, + }, + }, + }, + "disagree": { "type": "integer" }, + "checked": { "type": "integer" }, + "not_checked": { "type": "integer" }, + }, + "required": ["files", "disagree", "checked"], + }) +} + +// ── calling them ────────────────────────────────────────────────────── + +fn call(id: Value, params: &Value, root: Option<&Path>) -> Value { + let name = params.get("name").and_then(Value::as_str).unwrap_or(""); + let args = params + .get("arguments") + .cloned() + .unwrap_or_else(|| json!({})); + + // The NAME is checked before the arguments, because an unknown tool is a + // protocol fault rather than a bad request, and reporting a path problem + // for a tool that does not exist sends the caller to fix the wrong thing. + if !["ig_plan", "ig_convert", "ig_check_rotation"].contains(&name) { + return error(id, -32602, &format!("unknown tool {name}"), None); + } + + let (files, overflow) = match inputs(&args, root) { + Ok(v) => v, + Err(e) => return tool_error(id, e), + }; + + match name { + "ig_plan" => { + let mut opts = match geometry_opts(&args) { + Ok(o) => o, + Err(e) => return tool_error(id, e), + }; + opts.dry = true; + let reports = crate::run_all(&files, &opts); + let failed = reports.iter().filter(|r| r.error.is_some()).count(); + let mut text = lines(&reports); + if overflow > 0 { + text.push_str(&overflow_note(overflow, "planned")); + } + let mut out = json!({ + "files": reports.iter().map(report_json_plan).collect::>(), + "planned": reports.len() - failed, + "failed": failed, + }); + if overflow > 0 { + out["not_shown"] = json!(overflow); + } + tool_ok(id, text, out) + } + "ig_convert" => { + let opts = match convert_opts(&args, root) { + Ok(o) => o, + Err(e) => return tool_error(id, e), + }; + if let Err(e) = std::fs::create_dir_all(&opts.out_dir) { + return tool_error(id, format!("{}: {e}", opts.out_dir.display())); + } + let reports = crate::run_all(&files, &opts); + let failed = reports.iter().filter(|r| r.error.is_some()).count(); + let mut text = lines(&reports); + if overflow > 0 { + text.push_str(&overflow_note(overflow, "converted")); + } + let mut out = json!({ + "files": reports.iter().map(report_json_full).collect::>(), + "written": reports.len() - failed, + "failed": failed, + "out_dir": opts.out_dir.display().to_string(), + }); + if overflow > 0 { + out["not_converted"] = json!(overflow); + } + tool_ok(id, text, out) + } + "ig_check_rotation" => { + let checks: Vec<_> = files.iter().map(|p| crate::check_one(p)).collect(); + let disagree = checks + .iter() + .filter(|c| matches!(c.agreement, Agreement::Disagree)) + .count(); + let mut text = String::new(); + for c in &checks { + match c.agreement { + Agreement::Disagree => text.push_str(&format!( + "{}: DISAGREE container says {}, EXIF says {}\n", + c.name, + c.container.clone().unwrap_or_default(), + c.exif.clone().unwrap_or_default() + )), + Agreement::Unreadable => text.push_str(&format!( + "{}: {}\n", + c.name, + c.error.clone().unwrap_or_default() + )), + _ => {} + } + } + text.push_str(&format!( + "{} files checked, {disagree} disagree.", + checks.len() + )); + if disagree > 0 { + text.push_str(&format!("\n\n{}", crate::DISAGREE_NOTE)); + } + if overflow > 0 { + text.push_str(&overflow_note(overflow, "checked")); + } + let mut out = json!({ + "files": checks.iter().map(|c| { + let mut m = json!({ + "source": c.source.display().to_string(), + "agreement": c.agreement.label(), + }); + if let Some(v) = &c.container { m["container"] = json!(v); } + if let Some(v) = &c.exif { m["exif"] = json!(v); } + if let Some(v) = &c.error { m["error"] = json!(v); } + m + }).collect::>(), + "disagree": disagree, + "checked": checks.len(), + }); + if overflow > 0 { + out["not_checked"] = json!(overflow); + } + tool_ok(id, text, out) + } + // Unreachable: the guard above already refused anything else. Kept so + // adding a tool to that list without adding an arm fails loudly here + // rather than silently answering nothing. + other => error( + id, + -32603, + &format!("tool {other} is listed but unimplemented"), + None, + ), + } +} + +fn lines(reports: &[Report]) -> String { + let mut s = String::new(); + for r in reports { + s.push_str(&r.line()); + s.push('\n'); + } + s +} + +fn overflow_note(n: usize, verb: &str) -> String { + format!( + "\n{n} further file(s) matched and were not {verb}: a single call handles at most \ + {MAX_FILES}. Name a narrower set of paths to reach the rest." + ) +} + +/// An undefined field is OMITTED rather than sent as null, so a reader can +/// tell "this file did not decode" from "this file decoded to nothing". +fn report_json_plan(r: &Report) -> Value { + let mut m = json!({ "source": r.source.display().to_string() }); + if let Some((w, h)) = r.from { + m["from"] = json!([w, h]); + } + if let Some((w, h)) = r.to { + m["to"] = json!([w, h]); + m["outside_band"] = json!(r.outside_band); + } + if let Some(e) = &r.error { + m["error"] = json!(e); + } + m +} + +fn report_json_full(r: &Report) -> Value { + let mut m = report_json_plan(r); + if let Some(o) = &r.output { + m["output"] = json!(o.display().to_string()); + m["bytes"] = json!(r.bytes.unwrap_or(0)); + m["chroma"] = json!(r.chroma); + } + m +} + +// ── arguments ───────────────────────────────────────────────────────── + +fn geometry_opts(args: &Value) -> Result { + let mut o = Opts::defaults(); + match args.get("fit").and_then(Value::as_str) { + None | Some("full") => o.fit = Fit::Full, + Some("crop") => o.fit = Fit::Crop, + Some("pad") => o.fit = Fit::Pad, + Some(x) => return Err(format!("fit must be full, crop or pad, got {x:?}")), + } + match args.get("gravity").and_then(Value::as_str) { + None | Some("center") => o.gravity = Gravity::Center, + Some("top") => o.gravity = Gravity::Top, + Some("bottom") => o.gravity = Gravity::Bottom, + Some(x) => return Err(format!("gravity must be center, top or bottom, got {x:?}")), + } + if let Some(w) = args.get("width") { + let w = w + .as_u64() + .filter(|w| (1..=16384).contains(w)) + .ok_or("width must be a whole number of pixels between 1 and 16384")?; + o.width = w as u32; + } + Ok(o) +} + +fn convert_opts(args: &Value, root: Option<&Path>) -> Result { + let mut o = geometry_opts(args)?; + o.dry = false; + if let Some(q) = args.get("quality") { + let q = q + .as_u64() + .filter(|q| (1..=100).contains(q)) + .ok_or("quality must be a whole number between 1 and 100")?; + o.quality = q as u8; + } + match args.get("chroma") { + None => {} + Some(v) => match v.as_str() { + Some("444") => o.chroma = Chroma::Full, + Some("422") => o.chroma = Chroma::Halved, + Some("420") => o.chroma = Chroma::Quartered, + other => return Err(format!("chroma must be 444, 422 or 420, got {other:?}")), + }, + } + if let Some(c) = args.get("pad_color").and_then(Value::as_str) { + let h = c.trim_start_matches('#'); + if h.len() != 6 || !h.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(format!("pad_color must be six hex digits, got {c:?}")); + } + o.set_pad_color(c); + } + let dir = args.get("out_dir").and_then(Value::as_str).unwrap_or("ig"); + o.out_dir = under_root(Path::new(dir), root, false)?; + Ok(o) +} + +fn inputs(args: &Value, root: Option<&Path>) -> Result<(Vec, usize), String> { + let list = args + .get("paths") + .and_then(Value::as_array) + .ok_or("paths is required and must be an array of strings")?; + if list.is_empty() { + return Err("paths must name at least one file or directory".into()); + } + let mut given = Vec::new(); + for v in list { + let s = v.as_str().ok_or("every entry in paths must be a string")?; + given.push(under_root(Path::new(s), root, true)?); + } + let mut files = crate::expand(&given); + if files.is_empty() { + return Err("no readable images at those paths".into()); + } + // Re-checked after expansion rather than trusted: a directory inside the + // root can hold a symlink pointing outside it, and the entry that opened + // the directory says nothing about that. + for f in &files { + under_root(f, root, true)?; + } + let overflow = files.len().saturating_sub(MAX_FILES); + files.truncate(MAX_FILES); + Ok((files, overflow)) +} + +/// Resolve a caller-supplied path, and refuse it if `--root` was given and it +/// lands outside. +/// +/// Symlinks are resolved before the comparison, because comparing the string a +/// caller wrote against the root would let `root/link-to-elsewhere` pass. For +/// a path that does not exist yet, which is the `out_dir` case, the deepest +/// EXISTING ancestor is resolved and the remaining components are appended +/// after `.` and `..` have been folded away; a lexical check alone would let a +/// symlinked parent escape, and requiring existence would refuse to create an +/// output directory at all. +fn under_root(p: &Path, root: Option<&Path>, must_exist: bool) -> Result { + let resolved = resolve(p, must_exist)?; + match root { + Some(r) if !resolved.starts_with(r) => Err(format!( + "{} is outside the root this server was started with ({})", + resolved.display(), + r.display() + )), + _ => Ok(resolved), + } +} + +fn resolve(p: &Path, must_exist: bool) -> Result { + if let Ok(c) = p.canonicalize() { + return Ok(c); + } + if must_exist { + return Err(format!("{}: no such file or directory", p.display())); + } + let abs = if p.is_absolute() { + p.to_path_buf() + } else { + std::env::current_dir().map_err(|e| e.to_string())?.join(p) + }; + // Fold `.` and `..` away first, so the split below cannot be fooled by a + // tail that climbs back out. + let mut folded = PathBuf::new(); + for c in abs.components() { + match c { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + folded.pop(); + } + other => folded.push(other), + } + } + // Walk up to something real, resolve that, and put the tail back. + let mut tail = Vec::new(); + let mut probe = folded.clone(); + loop { + if let Ok(c) = probe.canonicalize() { + let mut out = c; + for t in tail.iter().rev() { + out.push(t); + } + return Ok(out); + } + match probe.file_name() { + Some(n) => { + tail.push(n.to_os_string()); + probe.pop(); + } + None => return Ok(folded), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn call_tool(name: &str, args: Value, root: Option<&Path>) -> Value { + call(json!(1), &json!({ "name": name, "arguments": args }), root) + } + + fn text_of(v: &Value) -> String { + v["result"]["content"][0]["text"] + .as_str() + .unwrap_or("") + .into() + } + + fn is_tool_error(v: &Value) -> bool { + v["result"]["isError"].as_bool().unwrap_or(false) + } + + /// A real directory pair, since the boundary is about paths that EXIST. + /// Built rather than borrowed from the filesystem: an earlier version + /// reached for `/etc`, which passes on Unix and fails on Windows for a + /// reason that has nothing to do with the boundary being tested. + fn sandbox(tag: &str) -> (PathBuf, PathBuf) { + let base = std::env::temp_dir() + .canonicalize() + .unwrap() + .join(format!("ig-prep-{tag}-{}", std::process::id())); + let (root, outside) = (base.join("root"), base.join("outside")); + std::fs::create_dir_all(root.join("in")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(root.join("in").join("a.jpg"), b"not really a jpeg").unwrap(); + std::fs::write(outside.join("b.jpg"), b"also not a jpeg").unwrap(); + (root, outside) + } + + // ── the protocol ────────────────────────────────────────────── + + #[test] + fn a_notification_gets_no_reply() { + let n = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }); + assert!(handle(&n, None).is_none()); + // An explicit null id is the same case. + let n = json!({ "jsonrpc": "2.0", "id": null, "method": "ping" }); + assert!(handle(&n, None).is_none()); + } + + #[test] + fn initialize_echoes_a_revision_it_speaks() { + for asked in ["2025-06-18", "2025-03-26", "2024-11-05"] { + let r = handle( + &json!({"jsonrpc":"2.0","id":1,"method":"initialize", + "params":{"protocolVersion": asked}}), + None, + ) + .unwrap(); + assert_eq!(r["result"]["protocolVersion"], asked); + } + } + + /// A client that opened with `initialize` is by definition not speaking the + /// revision that deleted `initialize`, so an unknown version must not be + /// answered with 2026-07-28. + #[test] + fn initialize_never_answers_with_the_modern_revision() { + let r = handle( + &json!({"jsonrpc":"2.0","id":1,"method":"initialize", + "params":{"protocolVersion":"1999-01-01"}}), + None, + ) + .unwrap(); + assert_ne!(r["result"]["protocolVersion"], MCP_PROTOCOL); + assert_eq!(r["result"]["protocolVersion"], MCP_SUPPORTED[1]); + } + + #[test] + fn an_unsupported_meta_version_is_refused_by_code() { + let r = handle( + &json!({"jsonrpc":"2.0","id":1,"method":"tools/list", + "params":{"_meta":{"protocolVersion":"1999-01-01"}}}), + None, + ) + .unwrap(); + assert_eq!(r["error"]["code"], -32022); + // The client can only retry if it is told what would work. + assert!(r["error"]["data"]["supported"].is_array()); + assert_eq!(r["error"]["data"]["requested"], "1999-01-01"); + } + + /// An absent `_meta` is how a legacy client presents itself, so it cannot + /// also be read as malformed. + #[test] + fn no_meta_is_legacy_rather_than_an_error() { + let r = handle(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}), None).unwrap(); + assert!(r["error"].is_null()); + assert!(r["result"]["tools"].is_array()); + } + + #[test] + fn discover_reports_every_revision() { + let r = handle( + &json!({"jsonrpc":"2.0","id":1,"method":"server/discover"}), + None, + ) + .unwrap(); + let vs = r["result"]["protocolVersions"].as_array().unwrap(); + assert_eq!(vs.len(), MCP_SUPPORTED.len()); + assert_eq!(vs[0], MCP_PROTOCOL); + } + + #[test] + fn every_result_carries_the_completion_marker() { + for m in ["initialize", "server/discover", "ping", "tools/list"] { + let r = handle(&json!({"jsonrpc":"2.0","id":1,"method":m}), None).unwrap(); + assert_eq!(r["result"]["resultType"], "complete", "{m}"); + assert!(!r["result"]["_meta"]["io.modelcontextprotocol/serverInfo"].is_null()); + } + } + + // ── the catalogue ───────────────────────────────────────────── + + /// The write tool must not advertise itself as a read. A model choosing + /// what it may run unattended reads these and nothing else. + #[test] + fn only_the_converter_declares_itself_a_write() { + let tools = tools(); + for t in tools.as_array().unwrap() { + let name = t["name"].as_str().unwrap(); + let read_only = t["annotations"]["readOnlyHint"].as_bool().unwrap(); + assert_eq!(read_only, name != "ig_convert", "{name}"); + // Nothing here reaches the network or a model. + assert_eq!(t["annotations"]["openWorldHint"], false, "{name}"); + assert_eq!(t["annotations"]["destructiveHint"], false, "{name}"); + assert!( + t["inputSchema"]["properties"]["paths"].is_object(), + "{name}" + ); + assert_eq!(t["inputSchema"]["required"][0], "paths", "{name}"); + } + assert_eq!(tools.as_array().unwrap().len(), 3); + } + + // ── arguments ───────────────────────────────────────────────── + + #[test] + fn defaults_match_the_command_line() { + let o = geometry_opts(&json!({})).unwrap(); + assert_eq!(o.width, crate::geometry::TARGET_WIDTH); + assert_eq!(o.fit, Fit::Full); + assert_eq!(o.gravity, Gravity::Center); + let c = convert_opts(&json!({}), None).unwrap(); + assert_eq!(c.quality, 95); + assert!(c.chroma == Chroma::Full); + } + + /// A misspelled enum is refused rather than silently defaulted, because + /// silently defaulting hands back a conversion nobody asked for and + /// reports success. + #[test] + fn bad_values_are_refused_rather_than_defaulted() { + assert!(geometry_opts(&json!({ "fit": "cropp" })).is_err()); + assert!(geometry_opts(&json!({ "gravity": "middle" })).is_err()); + assert!(geometry_opts(&json!({ "width": 0 })).is_err()); + assert!(geometry_opts(&json!({ "width": -5 })).is_err()); + assert!(geometry_opts(&json!({ "width": "1440" })).is_err()); + assert!(convert_opts(&json!({ "quality": 0 }), None).is_err()); + assert!(convert_opts(&json!({ "quality": 101 }), None).is_err()); + assert!(convert_opts(&json!({ "chroma": "411" }), None).is_err()); + assert!(convert_opts(&json!({ "pad_color": "xyzxyz" }), None).is_err()); + assert!(convert_opts(&json!({ "pad_color": "fff" }), None).is_err()); + } + + #[test] + fn paths_must_be_a_non_empty_array_of_strings() { + assert!(inputs(&json!({}), None).is_err()); + assert!(inputs(&json!({ "paths": [] }), None).is_err()); + assert!(inputs(&json!({ "paths": "one.jpg" }), None).is_err()); + assert!(inputs(&json!({ "paths": [7] }), None).is_err()); + } + + // ── the boundary ────────────────────────────────────────────── + + #[test] + fn root_refuses_a_path_outside_it() { + let (root, outside) = sandbox("root"); + let inside = root.join("in"); + + assert!(under_root(&inside, Some(&root), true).is_ok()); + // The classic escape, and the one a lexical check alone would miss if + // it ran after the join rather than before. + assert!(under_root(&inside.join("../.."), Some(&root), true).is_err()); + assert!(under_root(&outside, Some(&root), true).is_err()); + // An output directory that does not exist yet still has to land inside. + assert!(under_root(&root.join("out"), Some(&root), false).is_ok()); + assert!(under_root(&root.join("../out"), Some(&root), false).is_err()); + // With no root, a real path outside resolves fine. + assert!(under_root(&outside, None, true).is_ok()); + + std::fs::remove_dir_all(root.parent().unwrap()).ok(); + } + + /// A symlink inside the root that points out of it must not widen the + /// boundary, because the comparison is what stops it and a comparison + /// against the string the caller wrote would pass. + #[test] + #[cfg(unix)] + fn a_symlink_cannot_widen_the_root() { + let dir = std::env::temp_dir() + .canonicalize() + .unwrap() + .join(format!("ig-prep-link-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let link = dir.join("escape"); + std::os::unix::fs::symlink("/etc", &link).ok(); + assert!(under_root(&link, Some(&dir), true).is_err()); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn a_confined_call_reports_the_refusal_as_a_tool_error() { + let (root, outside) = sandbox("call"); + // A tool error rather than a JSON-RPC error: the model should be able + // to read it and choose another path, rather than have the call unwind. + let target = outside.join("b.jpg").display().to_string(); + let r = call_tool("ig_plan", json!({ "paths": [target] }), Some(&root)); + assert!(is_tool_error(&r)); + assert!(text_of(&r).contains("outside the root")); + std::fs::remove_dir_all(root.parent().unwrap()).ok(); + } + + /// Every name the catalogue advertises has to reach a dispatch arm. The + /// guard and the `match` list the same three names, and this is what keeps + /// them together when a fourth is added. + #[test] + fn every_advertised_tool_dispatches() { + let (root, _outside) = sandbox("dispatch"); + let inside = root.join("in").display().to_string(); + let out = root.join("out").display().to_string(); + for t in tools().as_array().unwrap() { + let name = t["name"].as_str().unwrap(); + let r = call_tool( + name, + json!({ "paths": [inside], "out_dir": out }), + Some(&root), + ); + assert!( + r["error"].is_null(), + "{name} is advertised but did not dispatch: {}", + r["error"] + ); + } + std::fs::remove_dir_all(root.parent().unwrap()).ok(); + } + + #[test] + fn an_unknown_tool_is_a_protocol_error() { + // Refused on the NAME, before its arguments are resolved, so a caller + // is told the thing that is actually wrong. The path here does not + // exist on any platform, which is the point. + let r = call_tool( + "ig_nope", + json!({ "paths": ["/nonexistent/anywhere.jpg"] }), + None, + ); + assert_eq!(r["error"]["code"], -32602); + assert!(r["error"]["message"].as_str().unwrap().contains("ig_nope")); + } +}