poly-mcp 0.5.0

A comprehensive MCP server with filesystem, diagnostics, scripting, time, network, context, git, input, clipboard, transform, and screen control tools
Documentation
use super::ScreenModule;
use anyhow::Context;
use base64::Engine;
use image::codecs::jpeg::JpegEncoder;
use image::codecs::png::{CompressionType as PngCompression, FilterType as PngFilter, PngEncoder};
use image::imageops::FilterType;
use image::{DynamicImage, ImageEncoder, RgbaImage};
use serde_json::{json, Value};
use std::io::Cursor;
use std::time::Instant;

pub fn tools() -> Vec<Value> {
    vec![json!({
        "name": "screen_capture",
        "description": "Take a screenshot of the full screen, a specific window, or a rectangular region. Returns an image that the AI can analyze to understand what's on screen. Default scale is 0.5 to keep images manageable.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "target": {
                    "type": "string",
                    "description": "What to capture: 'full' (entire screen), 'window' (specific window by ID), 'region' (rectangular area)",
                    "enum": ["full", "window", "region"]
                },
                "window_id": {
                    "type": "string",
                    "description": "Window ID to capture (hex, e.g. '0x04e00003'). Required when target is 'window'."
                },
                "x": {
                    "type": "number",
                    "description": "Region X coordinate (left edge). Required when target is 'region'."
                },
                "y": {
                    "type": "number",
                    "description": "Region Y coordinate (top edge). Required when target is 'region'."
                },
                "width": {
                    "type": "number",
                    "description": "Region width in pixels. Required when target is 'region'."
                },
                "height": {
                    "type": "number",
                    "description": "Region height in pixels. Required when target is 'region'."
                },
                "format": {
                    "type": "string",
                    "description": "Image format: 'png' (lossless) or 'jpeg' (smaller files)",
                    "enum": ["png", "jpeg"]
                },
                "quality": {
                    "type": "number",
                    "description": "JPEG quality 1-100 (default 80). Ignored for PNG."
                },
                "scale": {
                    "type": "number",
                    "description": "Scale factor 0.1-1.0 (default 0.5). Lower values produce smaller images."
                },
                "monitor": {
                    "type": "number",
                    "description": "Monitor index (0-based). Default 0 (primary monitor)."
                }
            },
            "required": []
        }
    })]
}

pub async fn capture(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let start = Instant::now();

    let target = args["target"].as_str().unwrap_or("full");
    let format = args["format"].as_str().unwrap_or("png");
    let quality = args["quality"].as_u64().unwrap_or(80).min(100) as u8;
    let scale = args["scale"]
        .as_f64()
        .unwrap_or(0.5)
        .clamp(0.1, 1.0) as f32;
    let monitor_idx = args["monitor"].as_u64().unwrap_or(0) as usize;

    // Capture the raw image — use fast path (scrot/grim) when available
    let raw_image = match target {
        "window" => capture_window(&args).await?,
        "region" => capture_region_fast(module, &args).await?,
        _ => capture_full_fast(module, monitor_idx).await?,
    };

    let orig_width = raw_image.width();
    let orig_height = raw_image.height();

    // Scale if needed
    let img = if (scale - 1.0).abs() > 0.01 {
        let new_w = (orig_width as f32 * scale) as u32;
        let new_h = (orig_height as f32 * scale) as u32;
        let dynamic = DynamicImage::ImageRgba8(raw_image);
        dynamic.resize_exact(new_w, new_h, FilterType::Triangle).to_rgba8()
    } else {
        raw_image
    };

    let final_width = img.width();
    let final_height = img.height();

    // Encode to target format
    let (encoded, mime_type) = encode_image(&img, format, quality)?;
    let encoded_size = encoded.len();

    // Base64 encode
    let b64 = base64::engine::general_purpose::STANDARD.encode(&encoded);

    let elapsed_ms = start.elapsed().as_millis();

    Ok(json!({
        "content": [
            {
                "type": "image",
                "data": b64,
                "mimeType": mime_type
            },
            {
                "type": "text",
                "text": serde_json::to_string_pretty(&json!({
                    "target": target,
                    "original_size": [orig_width, orig_height],
                    "output_size": [final_width, final_height],
                    "scale": scale,
                    "format": format,
                    "bytes": encoded_size,
                    "capture_ms": elapsed_ms
                }))?
            }
        ]
    }))
}

// ── Fast capture paths (scrot/grim subprocess) ─────────────────────

/// Full screen capture — tries scrot/grim first (~50ms), falls back to xcap (~950ms).
async fn capture_full_fast(module: &ScreenModule, monitor_idx: usize) -> anyhow::Result<RgbaImage> {
    // Fast path: scrot (X11) or grim (Wayland)
    if let Some(img) = try_scrot_full(module, monitor_idx) {
        return Ok(img);
    }
    if let Some(img) = try_grim_full(module, monitor_idx) {
        return Ok(img);
    }

    // Slow fallback: xcap
    capture_full_xcap(monitor_idx).await
}

/// Region capture — scrot -a is ~8ms, else full capture + crop.
async fn capture_region_fast(module: &ScreenModule, args: &Value) -> anyhow::Result<RgbaImage> {
    let x = args["x"].as_u64().context("Missing 'x' for region capture")? as u32;
    let y = args["y"].as_u64().context("Missing 'y' for region capture")? as u32;
    let w = args["width"].as_u64().context("Missing 'width' for region capture")? as u32;
    let h = args["height"].as_u64().context("Missing 'height' for region capture")? as u32;

    // Fast path: scrot -a x,y,w,h
    if let Some(ref scrot) = module.scrot_path {
        let tmp = temp_capture_path("png");
        let area = format!("{},{},{},{}", x, y, w, h);
        let output = std::process::Command::new(scrot)
            .args(["-a", &area, "-o", &tmp])
            .output();

        if let Ok(out) = output {
            if out.status.success() {
                if let Ok(img) = image::open(&tmp) {
                    let _ = std::fs::remove_file(&tmp);
                    return Ok(img.to_rgba8());
                }
                let _ = std::fs::remove_file(&tmp);
            }
        }
    }

    // Fallback: full capture + crop
    let monitor_idx = args["monitor"].as_u64().unwrap_or(0) as usize;
    let full = capture_full_fast(module, monitor_idx).await?;

    let img_w = full.width();
    let img_h = full.height();
    if x + w > img_w || y + h > img_h {
        return Err(anyhow::anyhow!(
            "Region ({},{} {}x{}) exceeds screen bounds ({}x{})",
            x, y, w, h, img_w, img_h
        ));
    }

    let dynamic = DynamicImage::ImageRgba8(full);
    let cropped = dynamic.crop_imm(x, y, w, h);
    Ok(cropped.to_rgba8())
}

fn try_scrot_full(module: &ScreenModule, _monitor_idx: usize) -> Option<RgbaImage> {
    let scrot = module.scrot_path.as_ref()?;
    let tmp = temp_capture_path("png");

    let output = std::process::Command::new(scrot)
        .args(["-o", &tmp])
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let img = image::open(&tmp).ok()?.to_rgba8();
    let _ = std::fs::remove_file(&tmp);
    Some(img)
}

fn try_grim_full(module: &ScreenModule, _monitor_idx: usize) -> Option<RgbaImage> {
    let grim = module.grim_path.as_ref()?;
    let tmp = temp_capture_path("png");

    let output = std::process::Command::new(grim)
        .arg(&tmp)
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let img = image::open(&tmp).ok()?.to_rgba8();
    let _ = std::fs::remove_file(&tmp);
    Some(img)
}

// ── Slow fallback (xcap) ──────────────────────────────────────���───

async fn capture_full_xcap(monitor_idx: usize) -> anyhow::Result<RgbaImage> {
    let monitors = xcap::Monitor::all().context("Failed to enumerate monitors")?;
    let monitor = monitors
        .get(monitor_idx)
        .context(format!(
            "Monitor index {} not found ({} monitors available)",
            monitor_idx,
            monitors.len()
        ))?;
    monitor.capture_image().context("Failed to capture screen")
}

async fn capture_window(args: &Value) -> anyhow::Result<RgbaImage> {
    let window_id_str = args["window_id"]
        .as_str()
        .context("Missing 'window_id' parameter for window capture")?;

    let windows = xcap::Window::all().context("Failed to enumerate windows")?;

    let target_id: u32 = if window_id_str.starts_with("0x") || window_id_str.starts_with("0X") {
        u32::from_str_radix(&window_id_str[2..], 16).context("Invalid hex window ID")?
    } else {
        window_id_str.parse().context("Invalid window ID")?
    };

    for win in &windows {
        if win.id() == target_id {
            return win.capture_image().context("Failed to capture window");
        }
    }

    Err(anyhow::anyhow!(
        "Window ID '{}' not found. Use screen_windows to list available windows.",
        window_id_str
    ))
}

// ── Encoding ──────────────────────────────────────────────────────

fn encode_image(img: &RgbaImage, format: &str, quality: u8) -> anyhow::Result<(Vec<u8>, &'static str)> {
    let mut buf = Cursor::new(Vec::new());

    match format {
        "jpeg" | "jpg" => {
            let rgb = DynamicImage::ImageRgba8(img.clone()).to_rgb8();
            let encoder = JpegEncoder::new_with_quality(&mut buf, quality);
            encoder
                .write_image(
                    rgb.as_raw(),
                    rgb.width(),
                    rgb.height(),
                    image::ExtendedColorType::Rgb8,
                )
                .context("Failed to encode JPEG")?;
            Ok((buf.into_inner(), "image/jpeg"))
        }
        _ => {
            let encoder = PngEncoder::new_with_quality(&mut buf, PngCompression::Fast, PngFilter::Adaptive);
            encoder
                .write_image(
                    img.as_raw(),
                    img.width(),
                    img.height(),
                    image::ExtendedColorType::Rgba8,
                )
                .context("Failed to encode PNG")?;
            Ok((buf.into_inner(), "image/png"))
        }
    }
}

// ── Helpers ───────────────────────────────────────────────────────

fn temp_capture_path(ext: &str) -> String {
    super::shm_temp_path("capture", ext)
}