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 serde_json::{json, Value};
use std::process::Command;

pub fn tools() -> Vec<Value> {
    vec![json!({
        "name": "screen_elements",
        "description": "Get the UI accessibility tree (AT-SPI) for a running application. Returns buttons, text fields, menus, labels with their exact bounding boxes and states. This eliminates coordinate guessing for labeled UI elements. Works best with GTK/Qt apps. Electron apps (Discord, VS Code) need --force-renderer-accessibility flag.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "app": {
                    "type": "string",
                    "description": "Application name filter (e.g. 'firefox', 'discord'). If omitted, lists all apps."
                },
                "max_depth": {
                    "type": "number",
                    "description": "Max depth to traverse (default 3). Higher = more detail but slower."
                },
                "roles": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Filter by role (e.g. ['push button', 'text', 'menu item']). Omit for all roles."
                }
            },
            "required": []
        }
    })]
}

pub async fn elements(args: Value) -> anyhow::Result<Value> {
    let app_filter = args["app"].as_str();
    let max_depth = args["max_depth"].as_u64().unwrap_or(3) as usize;
    let role_filter: Vec<String> = args["roles"]
        .as_array()
        .map(|a| a.iter().filter_map(|v| v.as_str().map(|s| s.to_lowercase())).collect())
        .unwrap_or_default();

    // Get AT-SPI bus address
    let bus_addr = get_atspi_bus()?;

    // Get application list from registry
    let children_raw = atspi_call(
        &bus_addr,
        "org.a11y.atspi.Registry",
        "/org/a11y/atspi/accessible/root",
        "org.a11y.atspi.Accessible",
        "GetChildren",
    )?;

    let app_refs = parse_child_refs(&children_raw);

    // First pass: filter apps by name (sequential, fast — one gdbus per app)
    let mut filtered_apps: Vec<(String, String, String)> = Vec::new();
    for (dest, path) in &app_refs {
        let name = atspi_prop(&bus_addr, dest, path, "org.a11y.atspi.Accessible", "Name")
            .unwrap_or_default();
        if let Some(filter) = app_filter {
            if !name.to_lowercase().contains(&filter.to_lowercase()) {
                continue;
            }
        }
        filtered_apps.push((dest.clone(), path.clone(), name));
    }

    // Second pass: collect elements in parallel (one blocking task per app)
    let mut handles = Vec::new();
    for (dest, path, name) in filtered_apps {
        let bus = bus_addr.clone();
        let roles = role_filter.clone();
        handles.push(tokio::task::spawn_blocking(move || {
            let mut elements: Vec<Value> = Vec::new();
            collect_elements(&bus, &dest, &path, &roles, max_depth, 0, &mut elements);
            json!({
                "app": name,
                "bus_name": dest,
                "element_count": elements.len(),
                "elements": elements
            })
        }));
    }

    let mut apps: Vec<Value> = Vec::new();
    for handle in handles {
        if let Ok(app) = handle.await {
            apps.push(app);
        }
    }

    Ok(json!({
        "app_count": apps.len(),
        "apps": apps,
        "note": if apps.is_empty() && app_filter.is_some() {
            "No matching apps found. Electron apps need --force-renderer-accessibility flag."
        } else { "" }
    }))
}

// ── AT-SPI queries via gdbus subprocess ───────────────────────────

fn get_atspi_bus() -> anyhow::Result<String> {
    let r = Command::new("gdbus")
        .args([
            "call", "--session", "--dest", "org.a11y.Bus",
            "--object-path", "/org/a11y/bus",
            "--method", "org.a11y.Bus.GetAddress",
        ])
        .output()
        .map_err(|_| anyhow::anyhow!("gdbus not found. AT-SPI requires GNOME/GTK environment."))?;

    if !r.status.success() {
        return Err(anyhow::anyhow!("AT-SPI bus not available: {}", String::from_utf8_lossy(&r.stderr)));
    }

    let raw = String::from_utf8_lossy(&r.stdout);
    // Parse ('unix:path=...',) format
    let addr = raw.trim().trim_start_matches("('").split("',").next()
        .ok_or_else(|| anyhow::anyhow!("Failed to parse AT-SPI bus address"))?;
    Ok(addr.to_string())
}

fn atspi_call(bus: &str, dest: &str, path: &str, iface: &str, method: &str) -> anyhow::Result<String> {
    let r = Command::new("gdbus")
        .args([
            "call", "--address", bus, "--dest", dest,
            "--object-path", path,
            "--method", &format!("{}.{}", iface, method),
        ])
        .output()
        .map_err(|e| anyhow::anyhow!("gdbus call failed: {}", e))?;

    if r.status.success() {
        Ok(String::from_utf8_lossy(&r.stdout).trim().to_string())
    } else {
        Err(anyhow::anyhow!("AT-SPI call failed: {}", String::from_utf8_lossy(&r.stderr)))
    }
}

fn atspi_prop(bus: &str, dest: &str, path: &str, iface: &str, prop: &str) -> Option<String> {
    let r = Command::new("gdbus")
        .args([
            "call", "--address", bus, "--dest", dest,
            "--object-path", path,
            "--method", "org.freedesktop.DBus.Properties.Get",
            iface, prop,
        ])
        .output()
        .ok()?;

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

    let raw = String::from_utf8_lossy(&r.stdout);
    // Parse (<'value'>,) format
    extract_variant_string(&raw)
}

fn atspi_extents(bus: &str, dest: &str, path: &str) -> Option<(i64, i64, i64, i64)> {
    // GetExtents(coord_type=0 means screen coords)
    let r = Command::new("gdbus")
        .args([
            "call", "--address", bus, "--dest", dest,
            "--object-path", path,
            "--method", "org.a11y.atspi.Component.GetExtents",
            "0", // ATSPI_COORD_TYPE_SCREEN
        ])
        .output()
        .ok()?;

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

    let raw = String::from_utf8_lossy(&r.stdout);
    // Parse ((x, y, width, height),) format
    parse_extents(&raw)
}

// ── Tree traversal ────────────────────────────────────────────────

fn collect_elements(
    bus: &str,
    dest: &str,
    path: &str,
    role_filter: &[String],
    max_depth: usize,
    depth: usize,
    elements: &mut Vec<Value>,
) {
    if depth > max_depth {
        return;
    }

    // Get role
    let role = atspi_call(bus, dest, path, "org.a11y.atspi.Accessible", "GetRoleName")
        .ok()
        .map(|s| extract_variant_string(&s).unwrap_or(s))
        .unwrap_or_default();

    // Get name
    let name = atspi_prop(bus, dest, path, "org.a11y.atspi.Accessible", "Name")
        .unwrap_or_default();

    // Get extents (bounding box)
    let extents = atspi_extents(bus, dest, path);

    // Filter by role
    let role_matches = role_filter.is_empty()
        || role_filter.iter().any(|r| role.to_lowercase().contains(r));

    // Add this element if it has useful info
    if role_matches && (!name.is_empty() || extents.is_some()) {
        let mut el = json!({
            "role": role,
            "name": name,
            "depth": depth,
        });

        if let Some((x, y, w, h)) = extents {
            if w > 0 && h > 0 {
                el["x"] = json!(x);
                el["y"] = json!(y);
                el["width"] = json!(w);
                el["height"] = json!(h);
                el["center_x"] = json!(x + w / 2);
                el["center_y"] = json!(y + h / 2);
            }
        }

        elements.push(el);
    }

    // Recurse into children
    if depth < max_depth {
        let children = atspi_call(bus, dest, path, "org.a11y.atspi.Accessible", "GetChildren")
            .unwrap_or_default();
        let child_refs = parse_child_refs(&children);

        for (cdest, cpath) in &child_refs {
            collect_elements(bus, cdest, cpath, role_filter, max_depth, depth + 1, elements);
        }
    }
}

// ── Parsing helpers ───────────────────────────────────────────────

fn parse_child_refs(raw: &str) -> Vec<(String, String)> {
    let mut refs = Vec::new();

    // Match patterns like ('bus_name', objectpath '/path') or ('bus_name', '/path')
    let re_obj = regex::Regex::new(r"\('([^']+)',\s*objectpath\s*'([^']+)'\)").ok();
    let re_str = regex::Regex::new(r"\('([^']+)',\s*'(/[^']+)'\)").ok();

    if let Some(re) = &re_obj {
        for cap in re.captures_iter(raw) {
            refs.push((cap[1].to_string(), cap[2].to_string()));
        }
    }

    if refs.is_empty() {
        if let Some(re) = &re_str {
            for cap in re.captures_iter(raw) {
                refs.push((cap[1].to_string(), cap[2].to_string()));
            }
        }
    }

    refs
}

fn extract_variant_string(raw: &str) -> Option<String> {
    // Handles gdbus output formats:
    //   (<'value'>,)
    //   ('value',)
    //   (<'value'>,) with extra whitespace
    let s = raw.trim();

    // Try regex extraction for the common pattern
    if let Some(re) = regex::Regex::new(r"'([^']*)'").ok() {
        if let Some(cap) = re.captures(s) {
            let val = cap[1].to_string();
            if !val.is_empty() {
                return Some(val);
            }
        }
    }

    // Fallback: manual stripping
    let trimmed = s.trim_start_matches('(').trim_end_matches(')');
    let trimmed = trimmed.trim().trim_start_matches('<').trim_end_matches('>');
    let trimmed = trimmed.trim().trim_start_matches('\'').trim_end_matches('\'');
    let trimmed = trimmed.trim().trim_end_matches(',');
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

fn parse_extents(raw: &str) -> Option<(i64, i64, i64, i64)> {
    // Format: ((x, y, w, h),)
    let re = regex::Regex::new(r"\((\-?\d+),\s*(\-?\d+),\s*(\d+),\s*(\d+)\)").ok()?;
    let cap = re.captures(raw)?;
    Some((
        cap[1].parse().ok()?,
        cap[2].parse().ok()?,
        cap[3].parse().ok()?,
        cap[4].parse().ok()?,
    ))
}