Screenshots of live websites. Minimal interface, powerful engine.
Add Iris MCP camera server
Bridger Towera7da4277b923
diff --git a/Cargo.lock b/Cargo.lockindex 61b56a2..dd9556b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -11,6 +11,15 @@ dependencies = ["memchr",]+[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]+[[package]]name = "anstream"version = "1.0.0"@@ -87,6 +96,12 @@ version = "1.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"+[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"+[[package]]name = "base64"version = "0.22.1"@@ -126,6 +141,16 @@ version = "1.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"+[[package]]+name = "cc"+version = "1.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d"+dependencies = [+ "find-msvc-tools",+ "shlex",+]+[[package]]name = "cfg-if"version = "1.0.4"@@ -151,7 +176,7 @@ dependencies = ["reqwest","serde","serde_json",- "thiserror",+ "thiserror 1.0.69","tokio","tracing","url",@@ -198,6 +223,18 @@ dependencies = ["serde_json",]+[[package]]+name = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "num-traits",+ "serde",+ "windows-link",+]+[[package]]name = "clap"version = "4.6.6"@@ -244,6 +281,12 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"+[[package]]name = "cpufeatures"version = "0.2.17"@@ -263,6 +306,40 @@ dependencies = ["typenum",]+[[package]]+name = "darling"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88490bf1b990d87eaaa7ac8aa887f629a08e7359765b4911faf63c3763347d23"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "084e274f91c482280130e1e34e0b8d6e66776a060d7b6de7b84289ca778868c4"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 3.0.3",+]++[[package]]+name = "darling_macro"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68f5792fa0d41cd2325ce0ffa64f0a340eaebd4971a3a0c5e1ffd2cc488a355e"+dependencies = [+ "darling_core",+ "quote",+ "syn 3.0.3",+]+[[package]]name = "data-encoding"version = "2.11.1"@@ -296,12 +373,24 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"+[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"+[[package]]name = "either"version = "1.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"+[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"+[[package]]name = "errno"version = "0.3.14"@@ -312,6 +401,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "find-msvc-tools"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"+[[package]]name = "fnv"version = "1.0.7"@@ -442,6 +537,23 @@ dependencies = ["wasi",]+[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+[[package]]name = "heck"version = "0.4.1"@@ -545,6 +657,30 @@ dependencies = ["tracing",]+[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]+[[package]]name = "icu_collections"version = "2.3.0"@@ -628,6 +764,12 @@ dependencies = ["zerovec",]+[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"+[[package]]name = "idna"version = "1.1.0"@@ -649,6 +791,18 @@ dependencies = ["icu_properties",]+[[package]]+name = "indexmap"+version = "2.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"+dependencies = [+ "equivalent",+ "hashbrown",+ "serde",+ "serde_core",+]+[[package]]name = "ipnet"version = "2.12.1"@@ -657,12 +811,14 @@ checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78"[[package]]name = "iris-screenshot"-version = "0.3.1"+version = "0.4.0"dependencies = ["anyhow",+ "base64","chromiumoxide","clap","futures",+ "rmcp","serde","serde_json","tokio",@@ -733,6 +889,15 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]+[[package]]name = "once_cell"version = "1.21.4"@@ -745,6 +910,12 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]+name = "pastey"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"+[[package]]name = "percent-encoding"version = "2.3.2"@@ -793,6 +964,12 @@ dependencies = ["proc-macro2",]+[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]name = "rand"version = "0.8.7"@@ -820,7 +997,27 @@ version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"dependencies = [- "getrandom",+ "getrandom 0.2.17",+]++[[package]]+name = "ref-cast"+version = "1.0.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "216e8f773d7923bcba9ceb86a86c93cabb3903a11872fc3f138c49630e50b96d"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",][[package]]@@ -884,6 +1081,41 @@ dependencies = ["web-sys",]+[[package]]+name = "rmcp"+version = "3.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f17072af977b0f86f714dbd64b3d37d0715bb63064f9d13483f0a1775813374"+dependencies = [+ "chrono",+ "futures",+ "indexmap",+ "pastey",+ "pin-project-lite",+ "rmcp-macros",+ "schemars",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+ "tokio",+ "tokio-util",+ "tracing",+ "uuid",+]++[[package]]+name = "rmcp-macros"+version = "3.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "54817231d63a35330d5c3a5782a4a166fbe3b914a9faab440d3dd8bd37971890"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "serde_json",+ "syn 3.0.3",+]+[[package]]name = "rustix"version = "0.38.44"@@ -909,6 +1141,32 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]+name = "schemars"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"+dependencies = [+ "chrono",+ "dyn-clone",+ "ref-cast",+ "schemars_derive",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d98c67716b46af2f0b8cf752abc930f6f9aecfbf671ecfb531db8a31dbe4e2ba"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 3.0.3",+]+[[package]]name = "serde"version = "1.0.229"@@ -939,6 +1197,17 @@ dependencies = ["syn 3.0.3",]+[[package]]+name = "serde_derive_internals"+version = "0.30.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]+[[package]]name = "serde_json"version = "1.0.151"@@ -975,6 +1244,12 @@ dependencies = ["digest",]+[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"+[[package]]name = "signal-hook-registry"version = "1.4.8"@@ -1067,7 +1342,16 @@ version = "1.0.69"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"dependencies = [- "thiserror-impl",+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"+dependencies = [+ "thiserror-impl 2.0.20",][[package]]@@ -1081,6 +1365,17 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "thiserror-impl"+version = "2.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]+[[package]]name = "tinystr"version = "0.8.4"@@ -1118,6 +1413,20 @@ dependencies = ["syn 3.0.3",]+[[package]]+name = "tokio-util"+version = "0.7.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "libc",+ "pin-project-lite",+ "tokio",+]+[[package]]name = "tower"version = "0.5.3"@@ -1214,7 +1523,7 @@ dependencies = ["log","rand","sha1",- "thiserror",+ "thiserror 1.0.69","utf-8",]@@ -1260,6 +1569,17 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"+[[package]]+name = "uuid"+version = "1.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2cefc03fd367c0c6d4305de1b312cf00248c4114f4a0418ce6a6af769e3b0bd9"+dependencies = [+ "getrandom 0.4.3",+ "js-sys",+ "wasm-bindgen",+]+[[package]]name = "version_check"version = "0.9.5"@@ -1358,12 +1678,65 @@ dependencies = ["winsafe",]+[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "windows-link"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"+[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]+[[package]]name = "windows-sys"version = "0.48.0"diff --git a/Cargo.toml b/Cargo.tomlindex 96f37c8..afda2eb 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,8 +1,8 @@[package]name = "iris-screenshot"-version = "0.3.1"+version = "0.4.0"edition = "2024"-rust-version = "1.85"+rust-version = "1.88"description = "Minimal, powerful screenshots of live websites"license = "MIT"repository = "https://github.com/brijr/iris"@@ -16,12 +16,14 @@ path = "src/main.rs"[dependencies]anyhow = "1"+base64 = "0.22"clap = { version = "4", features = ["derive", "env"] }chromiumoxide = { version = "0.7", default-features = false, features = ["tokio-runtime"] }futures = "0.3"+rmcp = { version = "3.1.2", default-features = false, features = ["macros", "server", "transport-io"] }serde = { version = "1", features = ["derive"] }serde_json = "1"-tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "fs"] }+tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "fs", "io-std", "sync"] }url = "2"[profile.release]diff --git a/README.md b/README.mdindex 169de88..66a1163 100644--- a/README.md+++ b/README.md@@ -1,6 +1,6 @@# iris-Screenshots of live websites. Minimal interface, powerful engine.+A camera for coding agents. One fast command or MCP tool call produces one trustworthy image.```iris example.com # 1440×900 @2x → example.com.png@@ -32,12 +32,52 @@ cargo install iris-screenshotThe crates.io package is named `iris-screenshot`; the installed command is `iris`.The only runtime dependency is an installed Chrome-family browser (Chrome, Chromium, Edge, or Brave).+Building from source requires Rust 1.88 or newer.++## Give your coding agent eyes++Iris includes a local stdio MCP server in the same binary. Add it to Codex:++```+codex mcp add iris -- iris mcp+```++Or use the equivalent configuration in another MCP client:++```json+{+ "mcpServers": {+ "iris": {+ "command": "iris",+ "args": ["mcp"]+ }+ }+}+```++The server exposes one tool, `capture`, which returns the image inline with structured metadata. It writes nothing by default; pass `output` when the agent also needs a file.++```json+{+ "url": "localhost:3000",+ "selector": "#pricing-card",+ "padding": 24,+ "size": "desktop",+ "dark": false,+ "format": "png",+ "timeout_seconds": 30,+ "output": "/tmp/pricing-card.png"+}+```++Bare localhost, `.localhost`, and loopback addresses use HTTP automatically. Other bare hosts use HTTPS. Run `iris mcp --help` to select a Chrome binary for the server.## What it does for you- Renders with your real installed Chrome, driven over the DevTools Protocol- Waits for fonts, image loads, entrance animations, and — on `--full` — scroll-triggers lazy-loaded content before capturing- Captures the first matching element with `--selector`, automatically scrolling it into view and settling newly visible content before framing it+- Serves the same capture engine to coding agents with `iris mcp`, returning pixels inline instead of making the agent locate a file- Retina `@2x` output by default; full pages taller than Chrome's ~16k px render limit fall back to `@1x` automatically (the report tells you which you got)- Image format from the `-o` extension or `--format`: `png` (default), `jpg`, `webp` (JPEG/WebP encode at quality 90)- One browser process, concurrent tabs; a failed URL prints `✗` and never kills the batch (exit code 1 if anything failed)@@ -69,6 +109,8 @@ Element capture is intentionally CSS-selector based: Iris captures the first mat--json emit one JSON object per completed capture```+`iris mcp [--chrome <PATH>]` serves the single-image `capture` tool over stdio. Batch capture, browser interaction scripting, diffs, and review workflows remain outside Iris.+## License[MIT](LICENSE)diff --git a/src/capture.rs b/src/capture.rsindex 6931c82..c369353 100644--- a/src/capture.rs+++ b/src/capture.rs@@ -1,4 +1,6 @@+use std::net::IpAddr;use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};use std::time::Duration;use anyhow::{Context, Result, anyhow, bail};@@ -14,13 +16,37 @@ use chromiumoxide::cdp::js_protocol::runtime::EvaluateParams;use chromiumoxide::error::CdpError;use chromiumoxide::page::{Page, ScreenshotParams};use futures::StreamExt;-use serde::Deserialize;+use serde::{Deserialize, Serialize};use tokio::task::JoinHandle;+use url::Url;const IPHONE_UA: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) \AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1";+static PROFILE_SEQUENCE: AtomicU64 = AtomicU64::new(0);-#[derive(Clone, Copy)]+struct ProfileDir(PathBuf);++impl ProfileDir {+ fn unique() -> Self {+ Self(std::env::temp_dir().join(format!(+ "iris-chrome-{}-{}",+ std::process::id(),+ PROFILE_SEQUENCE.fetch_add(1, Ordering::Relaxed)+ )))+ }++ fn path(&self) -> &Path {+ &self.0+ }+}++impl Drop for ProfileDir {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++#[derive(Clone, Copy, Debug)]pub struct Viewport {pub width: u32,pub height: u32,@@ -28,7 +54,18 @@ pub struct Viewport {pub mobile: bool,}-#[derive(Clone, Copy, PartialEq)]+impl Viewport {+ pub fn desktop() -> Self {+ Self {+ width: 1440,+ height: 900,+ scale: 2.0,+ mobile: false,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq)]pub enum Format {Png,Jpeg,@@ -53,6 +90,14 @@ impl Format {}}+ pub fn mime_type(self) -> &'static str {+ match self {+ Self::Png => "image/png",+ Self::Jpeg => "image/jpeg",+ Self::Webp => "image/webp",+ }+ }+fn cdp(self) -> CaptureScreenshotFormat {match self {Self::Png => CaptureScreenshotFormat::Png,@@ -93,6 +138,7 @@ impl CaptureMode {}}+#[derive(Debug)]pub struct Opts {pub viewport: Viewport,pub mode: CaptureMode,@@ -114,6 +160,103 @@ pub struct Shot {pub bytes: u64,}+#[derive(Debug, Clone, Serialize)]+pub struct SuccessReport {+ status: &'static str,+ url: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ output: Option<String>,+ mode: &'static str,+ #[serde(skip_serializing_if = "Option::is_none")]+ selector: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ padding: Option<u32>,+ css_width: u32,+ css_height: u32,+ scale: f64,+ format: &'static str,+ bytes: u64,+}++#[derive(Debug, Clone, Serialize)]+pub struct ErrorReport {+ status: &'static str,+ url: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ output: Option<String>,+ mode: &'static str,+ #[serde(skip_serializing_if = "Option::is_none")]+ selector: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ padding: Option<u32>,+ error: String,+}++pub fn success_report(+ url: &str,+ output: Option<&Path>,+ mode: &CaptureMode,+ format: Format,+ shot: &Shot,+) -> SuccessReport {+ SuccessReport {+ status: "ok",+ url: url.into(),+ output: output.map(absolute_output),+ mode: mode.name(),+ selector: mode.selector().map(str::to_owned),+ padding: mode.padding(),+ css_width: shot.width,+ css_height: shot.height,+ scale: shot.scale,+ format: format.ext(),+ bytes: shot.bytes,+ }+}++pub fn error_report(+ url: &str,+ output: Option<&Path>,+ mode: &CaptureMode,+ error: String,+) -> ErrorReport {+ ErrorReport {+ status: "error",+ url: url.into(),+ output: output.map(absolute_output),+ mode: mode.name(),+ selector: mode.selector().map(str::to_owned),+ padding: mode.padding(),+ error,+ }+}++pub fn absolute_output(path: &Path) -> String {+ std::path::absolute(path)+ .unwrap_or_else(|_| path.to_path_buf())+ .to_string_lossy()+ .into_owned()+}++#[derive(Debug)]+pub struct CapturedImage {+ pub shot: Shot,+ pub data: Vec<u8>,+}++impl CapturedImage {+ pub async fn write_to(&self, out: &Path) -> Result<()> {+ if let Some(parent) = out.parent().filter(|path| !path.as_os_str().is_empty()) {+ tokio::fs::create_dir_all(parent)+ .await+ .with_context(|| format!("failed to create {}", parent.display()))?;+ }+ tokio::fs::write(out, &self.data)+ .await+ .with_context(|| format!("failed to write {}", out.display()))+ }+}+#[derive(Debug, Deserialize)]struct ElementBounds {x: f64,@@ -135,13 +278,19 @@ struct ClipRect {pub struct Session {browser: Browser,handler: JoinHandle<()>,+ // Declared after Browser so fallback field-drop cleanup happens after+ // Chromiumoxide has stopped its child process.+ profile_dir: ProfileDir,/// Browser's real UA with "HeadlessChrome" scrubbed, so sites don't serve degraded pages.user_agent: Option<String>,}impl Session {pub async fn launch(chrome: Option<PathBuf>, viewport: Viewport) -> Result<Self> {- let mut config = BrowserConfig::builder().window_size(viewport.width, viewport.height);+ let profile_dir = ProfileDir::unique();+ let mut config = BrowserConfig::builder()+ .window_size(viewport.width, viewport.height)+ .user_data_dir(profile_dir.path());if let Some(path) = chrome.or_else(find_chrome) {config = config.chrome_executable(path);}@@ -168,15 +317,16 @@ impl Session {Ok(Self {browser,handler,+ profile_dir,user_agent,})}- pub async fn capture(&self, url: &str, out: &Path, opts: &Opts) -> Result<Shot> {+ pub async fn capture(&self, url: &str, opts: &Opts) -> Result<CapturedImage> {let page = tokio::time::timeout(opts.timeout, self.browser.new_page("about:blank")).await.map_err(|_| anyhow!("timed out opening a tab"))??;- let result = tokio::time::timeout(opts.timeout, self.pipeline(&page, url, out, opts))+ let result = tokio::time::timeout(opts.timeout, self.pipeline(&page, url, opts)).await.map_err(|_| anyhow!("timed out after {}s", opts.timeout.as_secs())).and_then(|r| r);@@ -184,7 +334,11 @@ impl Session {result}- async fn pipeline(&self, page: &Page, url: &str, out: &Path, opts: &Opts) -> Result<Shot> {+ pub fn is_healthy(&self) -> bool {+ !self.handler.is_finished()+ }++ async fn pipeline(&self, page: &Page, url: &str, opts: &Opts) -> Result<CapturedImage> {let started = std::time::Instant::now();let v = opts.viewport;page.execute(@@ -345,14 +499,14 @@ impl Session {};let bytes = data.len() as u64;- tokio::fs::write(out, data)- .await- .with_context(|| format!("failed to write {}", out.display()))?;- Ok(Shot {- width,- height,- scale,- bytes,+ Ok(CapturedImage {+ shot: Shot {+ width,+ height,+ scale,+ bytes,+ },+ data,})}@@ -398,6 +552,62 @@ impl Session {let _ = self.browser.kill().await;}self.handler.abort();+ let _ = tokio::fs::remove_dir_all(self.profile_dir.path()).await;+ }+}++pub fn parse_viewport(size: &str, scale: Option<f64>) -> Result<Viewport> {+ let (width, height, preset_scale, mobile) = match size {+ "desktop" => (1440, 900, 2.0, false),+ "iphone" => (390, 844, 3.0, true),+ "ipad" => (1024, 1366, 2.0, false),+ custom => {+ let (width, height) = custom+ .split_once(['x', 'X'])+ .and_then(|(width, height)| {+ Some((width.parse::<u32>().ok()?, height.parse::<u32>().ok()?))+ })+ .with_context(|| {+ format!(+ "invalid size {custom:?}: use WxH (e.g. 1440x900) or desktop|iphone|ipad"+ )+ })?;+ if width == 0 || height == 0 {+ bail!("invalid size {custom:?}: width and height must be greater than zero");+ }+ (width, height, 2.0, false)+ }+ };+ let scale = scale.unwrap_or(preset_scale);+ if !scale.is_finite() || scale <= 0.0 {+ bail!("invalid scale {scale}: use a finite number greater than zero");+ }+ Ok(Viewport {+ width,+ height,+ scale,+ mobile,+ })+}++pub fn normalize_url(raw: &str) -> Result<Url> {+ if raw.contains("://") {+ return Url::parse(raw).with_context(|| format!("invalid URL: {raw}"));+ }++ let http =+ Url::parse(&format!("http://{raw}")).with_context(|| format!("invalid URL: {raw}"))?;+ let local = http.host_str().is_some_and(|host| {+ host.eq_ignore_ascii_case("localhost")+ || host.to_ascii_lowercase().ends_with(".localhost")+ || host+ .parse::<IpAddr>()+ .is_ok_and(|address| address.is_loopback() || address.is_unspecified())+ });+ if local {+ Ok(http)+ } else {+ Url::parse(&format!("https://{raw}")).with_context(|| format!("invalid URL: {raw}"))}}@@ -656,6 +866,38 @@ mod tests {);}+ #[test]+ fn local_urls_use_http_and_public_hosts_use_https() {+ assert_eq!(+ normalize_url("localhost:3000").unwrap().as_str(),+ "http://localhost:3000/"+ );+ assert_eq!(+ normalize_url("app.localhost:4173").unwrap().as_str(),+ "http://app.localhost:4173/"+ );+ assert_eq!(+ normalize_url("127.0.0.1:8080").unwrap().as_str(),+ "http://127.0.0.1:8080/"+ );+ assert_eq!(+ normalize_url("example.com").unwrap().as_str(),+ "https://example.com/"+ );+ assert_eq!(+ normalize_url("http://example.com").unwrap().as_str(),+ "http://example.com/"+ );+ }++ #[test]+ fn viewport_rejects_zero_dimensions_and_invalid_scales() {+ assert!(parse_viewport("0x900", None).is_err());+ assert!(parse_viewport("1440x0", None).is_err());+ assert!(parse_viewport("desktop", Some(0.0)).is_err());+ assert!(parse_viewport("desktop", Some(f64::NAN)).is_err());+ }+#[tokio::test]async fn browser_element_capture_contract() -> Result<()> {let temp = std::env::temp_dir().join(format!("iris-browser-{}", std::process::id()));@@ -674,13 +916,13 @@ mod tests {let session = Session::launch(None, viewport).await?;let one_x_path = temp.join("target-1x.png");- let one_x = session- .capture(- url.as_str(),- &one_x_path,- &element_opts(viewport, ".capture-target", 10, Format::Png),- )- .await?;+ let one_x = capture_to(+ &session,+ url.as_str(),+ &one_x_path,+ &element_opts(viewport, ".capture-target", 10, Format::Png),+ )+ .await?;// The first duplicate starts at 80.5px and transitions to 120.5px only// after scrolling into view. The final 141x81 frame proves first-match,// automatic scroll/settle, outward rounding, and padding together.@@ -695,13 +937,13 @@ mod tests {..viewport};let two_x_path = temp.join("target-2x.png");- let two_x = session- .capture(- url.as_str(),- &two_x_path,- &element_opts(two_x_viewport, ".capture-target", 10, Format::Png),- )- .await?;+ let two_x = capture_to(+ &session,+ url.as_str(),+ &two_x_path,+ &element_opts(two_x_viewport, ".capture-target", 10, Format::Png),+ )+ .await?;assert_eq!((two_x.width, two_x.height), (141, 81));assert_eq!(png_dimensions(&tokio::fs::read(&two_x_path).await?),@@ -709,34 +951,70 @@ mod tests {);let jpeg_path = temp.join("target.jpg");- session+ capture_to(+ &session,+ url.as_str(),+ &jpeg_path,+ &element_opts(viewport, ".capture-target", 0, Format::Jpeg),+ )+ .await?;+ let jpeg = tokio::fs::read(&jpeg_path).await?;+ assert!(jpeg.starts_with(&[0xff, 0xd8, 0xff]));++ let webp_path = temp.join("target.webp");+ capture_to(+ &session,+ url.as_str(),+ &webp_path,+ &element_opts(viewport, ".capture-target", 0, Format::Webp),+ )+ .await?;+ let webp = tokio::fs::read(&webp_path).await?;+ assert_eq!(&webp[..4], b"RIFF");+ assert_eq!(&webp[8..12], b"WEBP");++ let dark_viewport = session.capture(url.as_str(),- &jpeg_path,- &element_opts(viewport, ".capture-target", 0, Format::Jpeg),+ &page_opts(viewport, CaptureMode::Viewport, true),).await?;- let jpeg = tokio::fs::read(&jpeg_path).await?;- assert!(jpeg.starts_with(&[0xff, 0xd8, 0xff]));+ assert_eq!(+ (dark_viewport.shot.width, dark_viewport.shot.height),+ (320, 240)+ );+ assert_eq!(png_dimensions(&dark_viewport.data), (320, 240));- let webp_path = temp.join("target.webp");- session+ let full_page = session.capture(url.as_str(),- &webp_path,- &element_opts(viewport, ".capture-target", 0, Format::Webp),+ &page_opts(viewport, CaptureMode::FullPage, false),).await?;- let webp = tokio::fs::read(&webp_path).await?;- assert_eq!(&webp[..4], b"RIFF");- assert_eq!(&webp[8..12], b"WEBP");+ assert_eq!(full_page.shot.width, 320);+ assert!(full_page.shot.height > viewport.height);+ assert_eq!(+ png_dimensions(&full_page.data),+ (full_page.shot.width, full_page.shot.height)+ );- let invalid = session+ let phone = Viewport {+ width: 390,+ height: 844,+ scale: 1.0,+ mobile: true,+ };+ let mobile = session.capture(url.as_str(),- &temp.join("invalid.png"),- &element_opts(viewport, "[", 0, Format::Png),+ &page_opts(phone, CaptureMode::Viewport, false),)+ .await?;+ assert_eq!((mobile.shot.width, mobile.shot.height), (390, 844));+ assert_eq!(png_dimensions(&mobile.data), (390, 844));++ let invalid = session+ .capture(url.as_str(), &element_opts(viewport, "[", 0, Format::Png)).await.unwrap_err();assert!(format!("{invalid:#}").contains("invalid selector: ["));@@ -746,7 +1024,6 @@ mod tests {let missing = session.capture(missing_url.as_str(),- &temp.join("missing.png"),&element_opts(viewport, ".capture-target", 0, Format::Png),).await@@ -756,7 +1033,6 @@ mod tests {let zero = session.capture(url.as_str(),- &temp.join("zero.png"),&element_opts(viewport, "#zero-size", 0, Format::Png),).await@@ -783,6 +1059,24 @@ mod tests {}}+ fn page_opts(viewport: Viewport, mode: CaptureMode, dark: bool) -> Opts {+ Opts {+ viewport,+ mode,+ dark,+ wait_ms: 0,+ wait_for: None,+ timeout: Duration::from_secs(5),+ format: Format::Png,+ }+ }++ async fn capture_to(session: &Session, url: &str, path: &Path, opts: &Opts) -> Result<Shot> {+ let image = session.capture(url, opts).await?;+ image.write_to(path).await?;+ Ok(image.shot)+ }+fn png_dimensions(bytes: &[u8]) -> (u32, u32) {assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");(diff --git a/src/main.rs b/src/main.rsindex bde61ab..350ec49 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,4 +1,5 @@mod capture;+mod mcp;use std::collections::HashMap;use std::io::Read;@@ -7,10 +8,9 @@ use std::sync::Arc;use std::time::Duration;use anyhow::{Context, Result, bail};-use capture::{CaptureMode, Format, Opts, Session, Shot, Viewport};-use clap::Parser;+use capture::{CaptureMode, Format, Opts, Session, normalize_url, parse_viewport, success_report};+use clap::{Args, Parser, Subcommand};use futures::StreamExt;-use serde::Serialize;use url::Url;/// Screenshot live websites. Minimal interface, powerful engine:@@ -20,14 +20,32 @@ use url::Url;name = "iris",version,arg_required_else_help = true,+ subcommand_negates_reqs = true,+ args_conflicts_with_subcommands = true,after_help = "\Examples:iris example.com 1440\u{d7}900 @2x \u{2192} example.com.pngiris --full --dark tailwindcss.com full page, dark color schemeiris --selector '#hero' --padding 24 app.dev+ iris mcp serve the capture tool over stdiocat urls.txt | iris - -o shots/ concurrent batch from stdin")]struct Cli {+ #[command(subcommand)]+ command: Option<Command>,++ #[command(flatten)]+ capture: CaptureArgs,+}++#[derive(Subcommand)]+enum Command {+ /// Serve Iris as a local Model Context Protocol camera+ Mcp(mcp::McpArgs),+}++#[derive(Args)]+struct CaptureArgs {/// URLs to capture; `-` reads newline-separated URLs from stdin#[arg(required = true, value_name = "URL")]urls: Vec<String>,@@ -89,42 +107,18 @@ struct Cli {json: bool,}-#[derive(Serialize)]-struct SuccessReport<'a> {- status: &'static str,- url: &'a str,- output: String,- mode: &'static str,- #[serde(skip_serializing_if = "Option::is_none")]- selector: Option<&'a str>,- #[serde(skip_serializing_if = "Option::is_none")]- padding: Option<u32>,- css_width: u32,- css_height: u32,- scale: f64,- format: &'static str,- bytes: u64,-}--#[derive(Serialize)]-struct ErrorReport<'a> {- status: &'static str,- url: &'a str,- output: String,- mode: &'static str,- #[serde(skip_serializing_if = "Option::is_none")]- selector: Option<&'a str>,- #[serde(skip_serializing_if = "Option::is_none")]- padding: Option<u32>,- error: String,-}-#[tokio::main]async fn main() -> Result<()> {let cli = Cli::parse();+ if let Some(Command::Mcp(args)) = cli.command {+ return mcp::run(args).await;+ }+ run_capture(cli.capture).await+}+async fn run_capture(cli: CaptureArgs) -> Result<()> {let urls = collect_urls(&cli.urls)?;- let viewport = parse_size(&cli.size, cli.scale)?;+ let viewport = parse_viewport(&cli.size, cli.scale)?;let mode = capture_mode(&cli);let flag_format = cli.format.as_deref().and_then(Format::from_ext);let (targets, format) = resolve_outputs(&urls, cli.out.as_deref(), flag_format).await?;@@ -151,7 +145,10 @@ async fn main() -> Result<()> {let session = Arc::clone(&session);let opts = Arc::clone(&opts);async move {- let result = session.capture(url.as_str(), &path, &opts).await;+ let result = match session.capture(url.as_str(), &opts).await {+ Ok(image) => image.write_to(&path).await.map(|()| image.shot),+ Err(error) => Err(error),+ };(url, path, result)}}@@ -166,7 +163,7 @@ async fn main() -> Result<()> {"{}",serde_json::to_string(&success_report(url.as_str(),- &path,+ Some(&path),&mode,format,&shot,@@ -188,9 +185,9 @@ async fn main() -> Result<()> {if cli.json {println!("{}",- serde_json::to_string(&error_report(+ serde_json::to_string(&capture::error_report(url.as_str(),- &path,+ Some(&path),&mode,format!("{err:#}"),))?@@ -213,7 +210,7 @@ async fn main() -> Result<()> {Ok(())}-fn capture_mode(cli: &Cli) -> CaptureMode {+fn capture_mode(cli: &CaptureArgs) -> CaptureMode {if let Some(selector) = &cli.selector {CaptureMode::Element {selector: selector.clone(),@@ -226,52 +223,6 @@ fn capture_mode(cli: &Cli) -> CaptureMode {}}-fn success_report<'a>(- url: &'a str,- path: &std::path::Path,- mode: &'a CaptureMode,- format: Format,- shot: &Shot,-) -> SuccessReport<'a> {- SuccessReport {- status: "ok",- url,- output: absolute_output(path),- mode: mode.name(),- selector: mode.selector(),- padding: mode.padding(),- css_width: shot.width,- css_height: shot.height,- scale: shot.scale,- format: format.ext(),- bytes: shot.bytes,- }-}--fn error_report<'a>(- url: &'a str,- path: &std::path::Path,- mode: &'a CaptureMode,- error: String,-) -> ErrorReport<'a> {- ErrorReport {- status: "error",- url,- output: absolute_output(path),- mode: mode.name(),- selector: mode.selector(),- padding: mode.padding(),- error,- }-}--fn absolute_output(path: &std::path::Path) -> String {- std::path::absolute(path)- .unwrap_or_else(|_| path.to_path_buf())- .to_string_lossy()- .into_owned()-}-fn collect_urls(args: &[String]) -> Result<Vec<Url>> {let mut raw = Vec::new();for arg in args {@@ -294,41 +245,7 @@ fn collect_urls(args: &[String]) -> Result<Vec<Url>> {if raw.is_empty() {bail!("no URLs given");}- raw.iter()- .map(|s| {- let s = if s.contains("://") {- s.clone()- } else {- format!("https://{s}")- };- Url::parse(&s).with_context(|| format!("invalid URL: {s}"))- })- .collect()-}--fn parse_size(size: &str, scale: Option<f64>) -> Result<Viewport> {- let (width, height, preset_scale, mobile) = match size {- "desktop" => (1440, 900, 2.0, false),- "iphone" => (390, 844, 3.0, true),- "ipad" => (1024, 1366, 2.0, false),- custom => {- let (w, h) = custom- .split_once(['x', 'X'])- .and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?)))- .with_context(|| {- format!(- "invalid --size {custom:?}: use WxH (e.g. 1440x900) or desktop|iphone|ipad"- )- })?;- (w, h, 2.0, false)- }- };- Ok(Viewport {- width,- height,- scale: scale.unwrap_or(preset_scale),- mobile,- })+ raw.iter().map(|value| normalize_url(value)).collect()}/// Pair each URL with its output path and settle the image format. Single URL +@@ -401,6 +318,7 @@ mod tests {use clap::error::ErrorKind;use super::*;+ use crate::capture::Shot;#[test]fn selector_conflicts_with_full_page() {@@ -436,7 +354,7 @@ mod tests {]).unwrap();assert_eq!(- capture_mode(&element),+ capture_mode(&element.capture),CaptureMode::Element {selector: "main > h1".into(),padding: 24,@@ -444,10 +362,21 @@ mod tests {);let full = Cli::try_parse_from(["iris", "example.com", "--full"]).unwrap();- assert_eq!(capture_mode(&full), CaptureMode::FullPage);+ assert_eq!(capture_mode(&full.capture), CaptureMode::FullPage);let viewport = Cli::try_parse_from(["iris", "example.com"]).unwrap();- assert_eq!(capture_mode(&viewport), CaptureMode::Viewport);+ assert_eq!(capture_mode(&viewport.capture), CaptureMode::Viewport);+ }++ #[test]+ fn mcp_subcommand_does_not_require_a_url() {+ let cli = Cli::try_parse_from(["iris", "mcp"]).unwrap();+ assert!(matches!(cli.command, Some(Command::Mcp(_))));++ let conflict = Cli::try_parse_from(["iris", "mcp", "--dark"])+ .err()+ .unwrap();+ assert_eq!(conflict.kind(), ErrorKind::UnknownArgument);}#[test]@@ -464,7 +393,7 @@ mod tests {};let success = serde_json::to_string(&success_report("https://example.com/",- std::path::Path::new("/tmp/example.png"),+ Some(std::path::Path::new("/tmp/example.png")),&mode,Format::Png,&shot,@@ -475,9 +404,9 @@ mod tests {r#"{"status":"ok","url":"https://example.com/","output":"/tmp/example.png","mode":"element","selector":"h1","padding":24,"css_width":180,"css_height":72,"scale":2.0,"format":"png","bytes":14231}"#);- let failure = serde_json::to_string(&error_report(+ let failure = serde_json::to_string(&capture::error_report("https://example.com/",- std::path::Path::new("/tmp/example.png"),+ Some(std::path::Path::new("/tmp/example.png")),&mode,"selector never appeared: h1".into(),))diff --git a/src/mcp.rs b/src/mcp.rsnew file mode 100644index 0000000..8bac079--- /dev/null+++ b/src/mcp.rs@@ -0,0 +1,499 @@+use std::path::PathBuf;+use std::sync::Arc;+use std::time::Duration;++use anyhow::{Context, Result, anyhow, bail};+use base64::Engine as _;+use base64::engine::general_purpose::STANDARD as BASE64;+use clap::Args;+use rmcp::handler::server::{router::tool::ToolRouter, wrapper::Parameters};+use rmcp::model::{CallToolResult, ContentBlock, Implementation, ServerCapabilities, ServerInfo};+use rmcp::{ServerHandler, ServiceExt, schemars, tool, tool_handler, tool_router};+use serde::Deserialize;+use serde_json::json;+use tokio::sync::{Mutex, Semaphore};++use crate::capture::{+ CaptureMode, CapturedImage, Format, Opts, Session, Viewport, error_report, normalize_url,+ parse_viewport, success_report,+};++#[derive(Debug, Args)]+pub struct McpArgs {+ /// Chrome/Chromium binary [auto-detected]+ #[arg(long, env = "CHROME", value_name = "PATH")]+ chrome: Option<PathBuf>,+}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct CaptureRequest {+ /// URL to capture. Bare localhost and loopback addresses use HTTP; other bare hosts use HTTPS.+ url: String,+ /// Capture the first element matching this CSS selector.+ selector: Option<String>,+ /// Uniform CSS-pixel padding around a selected element.+ padding: Option<u32>,+ /// Capture the full page height. Conflicts with selector.+ #[serde(default)]+ full_page: bool,+ /// Viewport as WxH or desktop, iphone, or ipad. Defaults to desktop.+ size: Option<String>,+ /// Emulate prefers-color-scheme: dark.+ #[serde(default)]+ dark: bool,+ /// Image format. Defaults to png; a recognized output extension wins.+ format: Option<ImageFormat>,+ /// Extra settle delay in milliseconds after smart waiting.+ #[serde(default)]+ wait_ms: u64,+ /// Wait until this CSS selector exists before capturing.+ wait_for: Option<String>,+ /// Device scale factor overriding the viewport preset.+ scale: Option<f64>,+ /// Per-page timeout in seconds. Defaults to 30.+ timeout_seconds: Option<u64>,+ /// Optional image path. Relative paths resolve from the MCP server working directory.+ output: Option<PathBuf>,+}++#[derive(Clone, Copy, Debug, Deserialize, schemars::JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum ImageFormat {+ Png,+ Jpg,+ Jpeg,+ Webp,+}++impl ImageFormat {+ fn capture_format(self) -> Format {+ match self {+ Self::Png => Format::Png,+ Self::Jpg | Self::Jpeg => Format::Jpeg,+ Self::Webp => Format::Webp,+ }+ }+}++#[derive(Debug)]+struct PreparedCapture {+ url: url::Url,+ output: Option<PathBuf>,+ opts: Opts,+}++impl CaptureRequest {+ fn prepare(self) -> Result<PreparedCapture> {+ let url = normalize_url(self.url.trim())?;+ let selector_supplied = self.selector.is_some();+ let selector = self+ .selector+ .map(|selector| selector.trim().to_owned())+ .filter(|selector| !selector.is_empty());+ if selector_supplied && selector.is_none() {+ bail!("selector must not be empty");+ }+ if self.full_page && selector.is_some() {+ bail!("selector conflicts with full_page");+ }+ if self.padding.is_some() && selector.is_none() {+ bail!("padding requires selector");+ }+ let mode = if let Some(selector) = selector {+ CaptureMode::Element {+ selector,+ padding: self.padding.unwrap_or(0),+ }+ } else if self.full_page {+ CaptureMode::FullPage+ } else {+ CaptureMode::Viewport+ };++ let viewport = parse_viewport(self.size.as_deref().unwrap_or("desktop"), self.scale)?;+ let timeout_seconds = self.timeout_seconds.unwrap_or(30);+ if timeout_seconds == 0 {+ bail!("timeout_seconds must be greater than zero");+ }+ let wait_for_supplied = self.wait_for.is_some();+ let wait_for = self+ .wait_for+ .map(|selector| selector.trim().to_owned())+ .filter(|selector| !selector.is_empty());+ if wait_for_supplied && wait_for.is_none() {+ bail!("wait_for must not be empty");+ }++ let mut format = self+ .format+ .map(ImageFormat::capture_format)+ .unwrap_or(Format::Png);+ if let Some(output) = &self.output {+ let extension = output+ .extension()+ .and_then(|extension| extension.to_str())+ .ok_or_else(|| anyhow!("output must end in .png, .jpg, .jpeg, or .webp"))?;+ format = Format::from_ext(extension)+ .ok_or_else(|| anyhow!("unsupported output extension: .{extension}"))?;+ }++ Ok(PreparedCapture {+ url,+ output: self.output,+ opts: Opts {+ viewport,+ mode,+ dark: self.dark,+ wait_ms: self.wait_ms,+ wait_for,+ timeout: Duration::from_secs(timeout_seconds),+ format,+ },+ })+ }+}++struct McpState {+ chrome: Option<PathBuf>,+ session: Mutex<Option<Arc<Session>>>,+ permits: Semaphore,+}++impl McpState {+ fn new(chrome: Option<PathBuf>) -> Self {+ Self {+ chrome,+ session: Mutex::new(None),+ permits: Semaphore::new(4),+ }+ }++ async fn session(&self) -> Result<Arc<Session>> {+ let mut session = self.session.lock().await;+ if session+ .as_ref()+ .is_some_and(|session| !session.is_healthy())+ {+ session.take();+ }+ if let Some(session) = session.as_ref() {+ return Ok(Arc::clone(session));+ }+ let launched = Arc::new(Session::launch(self.chrome.clone(), Viewport::desktop()).await?);+ *session = Some(Arc::clone(&launched));+ Ok(launched)+ }++ async fn capture(&self, url: &str, opts: &Opts) -> Result<CapturedImage> {+ let _permit = self+ .permits+ .acquire()+ .await+ .map_err(|_| anyhow!("capture queue closed"))?;+ let session = self.session().await?;+ let result = session.capture(url, opts).await;+ if result.is_err() && !session.is_healthy() {+ let mut current = self.session.lock().await;+ if current+ .as_ref()+ .is_some_and(|candidate| Arc::ptr_eq(candidate, &session))+ {+ current.take();+ }+ }+ result+ }++ async fn close(&self) {+ let session = self.session.lock().await.take();+ if let Some(session) = session+ && let Ok(session) = Arc::try_unwrap(session)+ {+ session.close().await;+ }+ }+}++#[derive(Clone)]+struct IrisServer {+ state: Arc<McpState>,+ tool_router: ToolRouter<Self>,+}++impl IrisServer {+ fn new(state: Arc<McpState>) -> Self {+ Self {+ state,+ tool_router: Self::tool_router(),+ }+ }++ async fn capture_image(&self, request: CaptureRequest) -> CallToolResult {+ let prepared = match request.prepare() {+ Ok(prepared) => prepared,+ Err(error) => return simple_error(format!("{error:#}")),+ };++ let image = match self+ .state+ .capture(prepared.url.as_str(), &prepared.opts)+ .await+ {+ Ok(image) => image,+ Err(error) => {+ return report_error(&prepared, format!("{error:#}"));+ }+ };+ if let Some(output) = &prepared.output+ && let Err(error) = image.write_to(output).await+ {+ return report_error(&prepared, format!("{error:#}"));+ }++ let report = success_report(+ prepared.url.as_str(),+ prepared.output.as_deref(),+ &prepared.opts.mode,+ prepared.opts.format,+ &image.shot,+ );+ let structured = match serde_json::to_value(&report) {+ Ok(structured) => structured,+ Err(error) => {+ return simple_error(format!("failed to serialize capture report: {error}"));+ }+ };+ let destination = prepared+ .output+ .as_deref()+ .map(crate::capture::absolute_output)+ .map(|path| format!(" → {path}"))+ .unwrap_or_default();+ let summary = format!(+ "Captured {}×{} CSS px @{}x as {}{}",+ image.shot.width,+ image.shot.height,+ image.shot.scale,+ prepared.opts.format.ext(),+ destination,+ );+ let mut result = CallToolResult::success(vec![+ ContentBlock::image(BASE64.encode(&image.data), prepared.opts.format.mime_type()),+ ContentBlock::text(summary),+ ]);+ result.structured_content = Some(structured);+ result+ }+}++#[tool_router(router = tool_router)]+impl IrisServer {+ /// Capture one trustworthy image of a live page or its first matching element.+ #[tool(+ name = "capture",+ annotations(+ title = "Capture a web page",+ read_only_hint = false,+ destructive_hint = true,+ idempotent_hint = false,+ open_world_hint = true+ )+ )]+ async fn capture(&self, Parameters(request): Parameters<CaptureRequest>) -> CallToolResult {+ self.capture_image(request).await+ }+}++#[tool_handler(router = self.tool_router)]+impl ServerHandler for IrisServer {+ fn get_info(&self) -> ServerInfo {+ ServerInfo::new(ServerCapabilities::builder().enable_tools().build())+ .with_server_info(Implementation::new("iris", env!("CARGO_PKG_VERSION")))+ .with_instructions(+ "Iris is a camera for coding agents. Use capture for one page or element at a time; it returns the image inline and saves a file only when output is provided.",+ )+ }+}++fn simple_error(message: String) -> CallToolResult {+ let mut result = CallToolResult::error(vec![ContentBlock::text(message.clone())]);+ result.structured_content = Some(json!({ "status": "error", "error": message }));+ result+}++fn report_error(prepared: &PreparedCapture, message: String) -> CallToolResult {+ let report = error_report(+ prepared.url.as_str(),+ prepared.output.as_deref(),+ &prepared.opts.mode,+ message.clone(),+ );+ let mut result = CallToolResult::error(vec![ContentBlock::text(message)]);+ result.structured_content = serde_json::to_value(report).ok();+ result+}++pub async fn run(args: McpArgs) -> Result<()> {+ let state = Arc::new(McpState::new(args.chrome));+ let service = IrisServer::new(Arc::clone(&state))+ .serve(rmcp::transport::stdio())+ .await+ .context("failed to start Iris MCP server")?;+ let result = service.waiting().await;+ state.close().await;+ result.context("Iris MCP server task failed")?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn request(url: &str) -> CaptureRequest {+ CaptureRequest {+ url: url.into(),+ selector: None,+ padding: None,+ full_page: false,+ size: None,+ dark: false,+ format: None,+ wait_ms: 0,+ wait_for: None,+ scale: None,+ timeout_seconds: None,+ output: None,+ }+ }++ #[test]+ fn request_defaults_and_conflicts_are_validated() {+ let prepared = request("localhost:3000").prepare().unwrap();+ assert_eq!(prepared.url.as_str(), "http://localhost:3000/");+ assert_eq!(prepared.opts.mode, CaptureMode::Viewport);+ assert_eq!(prepared.opts.viewport.width, 1440);+ assert_eq!(prepared.opts.format, Format::Png);+ assert_eq!(prepared.opts.timeout, Duration::from_secs(30));++ let mut conflict = request("example.com");+ conflict.selector = Some("main".into());+ conflict.full_page = true;+ assert!(+ conflict+ .prepare()+ .unwrap_err()+ .to_string()+ .contains("selector conflicts with full_page")+ );++ let mut padding = request("example.com");+ padding.padding = Some(0);+ assert!(+ padding+ .prepare()+ .unwrap_err()+ .to_string()+ .contains("padding requires selector")+ );+ }++ #[test]+ fn output_extension_overrides_requested_format() {+ let mut capture = request("example.com");+ capture.format = Some(ImageFormat::Png);+ capture.output = Some(PathBuf::from("shot.webp"));+ let prepared = capture.prepare().unwrap();+ assert_eq!(prepared.opts.format, Format::Webp);+ }++ #[test]+ fn server_advertises_one_focused_capture_tool() {+ let server = IrisServer::new(Arc::new(McpState::new(None)));+ let tools = server.tool_router.list_all();+ assert_eq!(tools.len(), 1);+ let tool = &tools[0];+ assert_eq!(tool.name, "capture");+ assert_eq!(+ tool.input_schema+ .get("required")+ .and_then(|required| required.as_array())+ .unwrap(),+ &[serde_json::Value::String("url".into())]+ );+ let annotations = tool.annotations.as_ref().unwrap();+ assert_eq!(annotations.read_only_hint, Some(false));+ assert_eq!(annotations.open_world_hint, Some(true));+ }++ #[tokio::test]+ async fn capture_tool_returns_inline_pixels_metadata_and_optional_file() -> Result<()> {+ let temp = std::env::temp_dir().join(format!("iris-mcp-{}", std::process::id()));+ let output = temp.join("nested/target.png");+ let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("tests/fixtures/precise-capture.html")+ .canonicalize()?;+ let url = url::Url::from_file_path(fixture)+ .map_err(|_| anyhow!("fixture path is not a file URL"))?;+ let state = Arc::new(McpState::new(None));+ let server = IrisServer::new(Arc::clone(&state));++ let mut capture = request(url.as_str());+ capture.selector = Some(".capture-target".into());+ capture.padding = Some(10);+ capture.size = Some("320x240".into());+ capture.scale = Some(1.0);+ capture.timeout_seconds = Some(3);+ capture.output = Some(output.clone());+ let result = server.capture_image(capture).await;++ assert_eq!(result.is_error, Some(false));+ let image = result+ .content+ .iter()+ .find_map(ContentBlock::as_image)+ .expect("capture result should contain an image");+ assert_eq!(image.mime_type, "image/png");+ let bytes = BASE64.decode(&image.data)?;+ assert_eq!(png_dimensions(&bytes), (141, 81));+ assert_eq!(tokio::fs::read(&output).await?, bytes);+ let structured = result.structured_content.unwrap();+ assert_eq!(structured["status"], "ok");+ assert_eq!(structured["mode"], "element");+ assert_eq!(structured["css_width"], 141);+ assert_eq!(structured["css_height"], 81);+ assert_eq!(+ structured["output"],+ crate::capture::absolute_output(&output)+ );++ let mut invalid = request(url.as_str());+ invalid.selector = Some("[".into());+ invalid.timeout_seconds = Some(3);+ let failure = server.capture_image(invalid).await;+ assert_eq!(failure.is_error, Some(true));+ assert!(+ failure+ .content+ .iter()+ .all(|content| content.as_image().is_none())+ );+ assert!(+ failure.structured_content.unwrap()["error"]+ .as_str()+ .unwrap()+ .contains("invalid selector: [")+ );++ state.close().await;+ tokio::fs::remove_dir_all(temp).await?;+ Ok(())+ }++ fn png_dimensions(bytes: &[u8]) -> (u32, u32) {+ assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");+ (+ u32::from_be_bytes(bytes[16..20].try_into().unwrap()),+ u32::from_be_bytes(bytes[20..24].try_into().unwrap()),+ )+ }+}diff --git a/tests/cli.rs b/tests/cli.rsindex 28463c9..1863a83 100644--- a/tests/cli.rs+++ b/tests/cli.rs@@ -1,5 +1,9 @@-use std::process::Command;+use std::io::{BufRead, BufReader, Read, Write};+use std::process::{Command, Stdio};+use std::sync::mpsc::{Receiver, channel};+use std::time::{Duration, Instant};+use base64::Engine as _;use serde_json::Value;use url::Url;@@ -80,3 +84,156 @@ fn json_batch_reports_success_and_failure_on_stdout() {std::fs::remove_dir_all(temp).unwrap();}++#[test]+fn mcp_stdio_lists_one_tool_and_returns_an_inline_capture() {+ let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("tests/fixtures/precise-capture.html")+ .canonicalize()+ .unwrap();+ let url = Url::from_file_path(fixture).unwrap();+ let mut child = Command::new(env!("CARGO_BIN_EXE_iris"))+ .arg("mcp")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ let stdout = child.stdout.take().unwrap();+ let (sender, receiver) = channel();+ let reader = std::thread::spawn(move || {+ for line in BufReader::new(stdout).lines() {+ sender.send(line.unwrap()).unwrap();+ }+ });+ let mut stdin = child.stdin.take().unwrap();++ send_message(+ &mut stdin,+ serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-11-25",+ "capabilities": {},+ "clientInfo": { "name": "iris-test", "version": "0.0.0" }+ }+ }),+ );+ let initialized = receive_response(&receiver, 1, Duration::from_secs(5));+ assert_eq!(initialized["result"]["serverInfo"]["name"], "iris");++ send_message(+ &mut stdin,+ serde_json::json!({+ "jsonrpc": "2.0",+ "method": "notifications/initialized"+ }),+ );+ send_message(+ &mut stdin,+ serde_json::json!({+ "jsonrpc": "2.0",+ "id": 2,+ "method": "tools/list",+ "params": {}+ }),+ );+ let listed = receive_response(&receiver, 2, Duration::from_secs(5));+ let tools = listed["result"]["tools"].as_array().unwrap();+ assert_eq!(tools.len(), 1);+ assert_eq!(tools[0]["name"], "capture");++ send_message(+ &mut stdin,+ serde_json::json!({+ "jsonrpc": "2.0",+ "id": 3,+ "method": "tools/call",+ "params": {+ "name": "capture",+ "arguments": {+ "url": url.as_str(),+ "selector": ".capture-target",+ "padding": 10,+ "size": "320x240",+ "scale": 1,+ "timeout_seconds": 3+ }+ }+ }),+ );+ let captured = receive_response(&receiver, 3, Duration::from_secs(15));+ let result = &captured["result"];+ assert_eq!(result["isError"], false);+ assert_eq!(result["structuredContent"]["status"], "ok");+ assert_eq!(result["structuredContent"]["css_width"], 141);+ assert_eq!(result["structuredContent"]["css_height"], 81);+ assert!(result["structuredContent"].get("output").is_none());+ let image = result["content"]+ .as_array()+ .unwrap()+ .iter()+ .find(|content| content["type"] == "image")+ .unwrap();+ assert_eq!(image["mimeType"], "image/png");+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(image["data"].as_str().unwrap())+ .unwrap();+ assert_eq!(png_dimensions(&bytes), (141, 81));++ drop(stdin);+ let deadline = Instant::now() + Duration::from_secs(10);+ let status = loop {+ if let Some(status) = child.try_wait().unwrap() {+ break status;+ }+ if Instant::now() >= deadline {+ let _ = child.kill();+ panic!("Iris MCP server did not exit after stdin closed");+ }+ std::thread::sleep(Duration::from_millis(50));+ };+ assert!(status.success());+ reader.join().unwrap();+ let mut stderr = String::new();+ child+ .stderr+ .take()+ .unwrap()+ .read_to_string(&mut stderr)+ .unwrap();+ assert!(+ stderr.is_empty(),+ "MCP diagnostics leaked to stderr: {stderr}"+ );+}++fn send_message(stdin: &mut impl Write, message: Value) {+ writeln!(stdin, "{}", serde_json::to_string(&message).unwrap()).unwrap();+ stdin.flush().unwrap();+}++fn receive_response(receiver: &Receiver<String>, id: u64, timeout: Duration) -> Value {+ let deadline = Instant::now() + timeout;+ loop {+ let remaining = deadline.saturating_duration_since(Instant::now());+ let line = receiver+ .recv_timeout(remaining)+ .unwrap_or_else(|_| panic!("timed out waiting for MCP response id {id}"));+ let message: Value = serde_json::from_str(&line)+ .unwrap_or_else(|error| panic!("MCP stdout was not JSON: {error}: {line}"));+ if message["id"] == id {+ return message;+ }+ }+}++fn png_dimensions(bytes: &[u8]) -> (u32, u32) {+ assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");+ (+ u32::from_be_bytes(bytes[16..20].try_into().unwrap()),+ u32::from_be_bytes(bytes[20..24].try_into().unwrap()),+ )+}diff --git a/tests/fixtures/precise-capture.html b/tests/fixtures/precise-capture.htmlindex 6f368a7..0d1c57b 100644--- a/tests/fixtures/precise-capture.html+++ b/tests/fixtures/precise-capture.html@@ -12,6 +12,14 @@background: #f5f3ee;}+ @media (prefers-color-scheme: dark) {+ html,+ body {+ background: #151713;+ color: #f5f3ee;+ }+ }+.spacer {height: 1100px;}