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
mod capture;
mod elements;
mod extras;
mod info;
mod input;
mod ocr;
mod windows;

use serde_json::Value;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};

static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Display server type detected at runtime.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SessionType {
    X11,
    Wayland,
    Unknown,
}

/// Screen control module — capture, input simulation, and window management.
pub struct ScreenModule {
    pub(crate) session_type: SessionType,
    pub(crate) xdotool_path: Option<PathBuf>,
    pub(crate) wmctrl_path: Option<PathBuf>,
    pub(crate) ydotool_path: Option<PathBuf>,
    pub(crate) wlrctl_path: Option<PathBuf>,
    pub(crate) scrot_path: Option<PathBuf>,
    pub(crate) grim_path: Option<PathBuf>,
}

impl ScreenModule {
    pub fn new() -> Self {
        let session_type = detect_session_type();

        Self {
            session_type,
            xdotool_path: which("xdotool"),
            wmctrl_path: which("wmctrl"),
            ydotool_path: which("ydotool"),
            wlrctl_path: which("wlrctl"),
            scrot_path: which("scrot"),
            grim_path: which("grim"),
        }
    }

    /// Create a fresh Enigo instance for input simulation.
    /// Created per-call because Enigo (xdo backend) is !Send.
    pub(crate) fn create_enigo(&self) -> anyhow::Result<enigo::Enigo> {
        let settings = enigo::Settings::default();
        enigo::Enigo::new(&settings)
            .map_err(|e| anyhow::anyhow!("Failed to initialize input simulation: {}. Ensure a display server (X11/Wayland) is running.", e))
    }

    pub fn get_tools(&self) -> Vec<Value> {
        let mut tools = Vec::new();
        tools.extend(capture::tools());
        tools.extend(input::tools());
        tools.extend(info::tools());
        tools.extend(windows::tools());
        tools.extend(ocr::tools());
        tools.extend(elements::tools());
        tools.extend(extras::tools());
        tools
    }

    // ── Tool dispatch methods ──────────────────────────────────────

    pub async fn capture(&self, args: Value) -> anyhow::Result<Value> {
        capture::capture(self, args).await
    }

    pub async fn click(&self, args: Value) -> anyhow::Result<Value> {
        input::click(self, args).await
    }

    pub async fn type_text(&self, args: Value) -> anyhow::Result<Value> {
        input::type_text(self, args).await
    }

    pub async fn key(&self, args: Value) -> anyhow::Result<Value> {
        input::key(self, args).await
    }

    pub async fn move_mouse(&self, args: Value) -> anyhow::Result<Value> {
        input::move_mouse(self, args).await
    }

    pub async fn scroll(&self, args: Value) -> anyhow::Result<Value> {
        input::scroll(self, args).await
    }

    pub async fn drag(&self, args: Value) -> anyhow::Result<Value> {
        input::drag(self, args).await
    }

    pub async fn info(&self, _args: Value) -> anyhow::Result<Value> {
        info::info(self).await
    }

    pub async fn windows(&self, args: Value) -> anyhow::Result<Value> {
        windows::list_windows(self, args).await
    }

    pub async fn focus(&self, args: Value) -> anyhow::Result<Value> {
        windows::focus_window(self, args).await
    }

    pub async fn wait(&self, args: Value) -> anyhow::Result<Value> {
        windows::wait(self, args).await
    }

    // ── New tools ─────────────────────────────────────────────────

    pub async fn ocr(&self, args: Value) -> anyhow::Result<Value> {
        ocr::ocr(self, args).await
    }

    pub async fn find_text(&self, args: Value) -> anyhow::Result<Value> {
        ocr::find(self, args).await
    }

    pub async fn elements(&self, args: Value) -> anyhow::Result<Value> {
        elements::elements(args).await
    }

    pub async fn clipboard(&self, args: Value) -> anyhow::Result<Value> {
        extras::clipboard(self, args).await
    }

    pub async fn pixel(&self, args: Value) -> anyhow::Result<Value> {
        extras::pixel(self, args).await
    }

    pub async fn diff(&self, args: Value) -> anyhow::Result<Value> {
        extras::diff(self, args).await
    }

    pub async fn process(&self, args: Value) -> anyhow::Result<Value> {
        extras::process(args).await
    }
}

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

fn detect_session_type() -> SessionType {
    if let Ok(session) = std::env::var("XDG_SESSION_TYPE") {
        match session.to_lowercase().as_str() {
            "x11" => return SessionType::X11,
            "wayland" => return SessionType::Wayland,
            _ => {}
        }
    }
    if std::env::var("WAYLAND_DISPLAY").is_ok() {
        return SessionType::Wayland;
    }
    if std::env::var("DISPLAY").is_ok() {
        return SessionType::X11;
    }
    SessionType::Unknown
}

/// RAM-backed temp file path (/dev/shm if available, else /tmp).
/// Uses PID + atomic counter to guarantee uniqueness across concurrent calls.
pub(crate) fn shm_temp_path(prefix: &str, ext: &str) -> String {
    let base = if std::path::Path::new("/dev/shm").exists() {
        "/dev/shm"
    } else {
        "/tmp"
    };
    let id = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("{}/poly_mcp_{}_{}_{}.{}", base, prefix, std::process::id(), id, ext)
}

fn which(name: &str) -> Option<PathBuf> {
    std::process::Command::new("which")
        .arg(name)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim()))
}