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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use super::ScreenModule;
use anyhow::Context;
use serde_json::{json, Value};
use std::process::Command;

pub fn tools() -> Vec<Value> {
    vec![
        json!({
            "name": "screen_clipboard",
            "description": "Read or write the system clipboard. Combined with ctrl+c/ctrl+v, this is faster and more reliable than OCR for text extraction.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "description": "'read' to get clipboard contents, 'write' to set them",
                        "enum": ["read", "write"]
                    },
                    "text": {
                        "type": "string",
                        "description": "Text to write to clipboard (required for action='write')"
                    }
                },
                "required": ["action"]
            }
        }),
        json!({
            "name": "screen_pixel",
            "description": "Get the color of a pixel at screen coordinates. Useful for quick state detection: is a toggle on/off, is a button greyed out, has a loading indicator disappeared. Sub-millisecond, much cheaper than a screenshot.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "x": { "type": "number", "description": "X coordinate" },
                    "y": { "type": "number", "description": "Y coordinate" },
                    "sample_size": {
                        "type": "number",
                        "description": "Average NxN pixel area (default 1). Useful for anti-aliased elements."
                    }
                },
                "required": ["x", "y"]
            }
        }),
        json!({
            "name": "screen_diff",
            "description": "Compare two screenshots and return changed regions. Take a screenshot before an action, take another after, then diff them to see what changed. Accepts base64 image data or 'capture_now' to take a fresh screenshot.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "description": "'save' to save current screen as reference, 'compare' to diff against saved reference",
                        "enum": ["save", "compare"]
                    },
                    "name": {
                        "type": "string",
                        "description": "Reference name (default 'default')"
                    },
                    "threshold": {
                        "type": "number",
                        "description": "Pixel difference threshold 0-255 (default 30). Lower = more sensitive."
                    }
                },
                "required": ["action"]
            }
        }),
        json!({
            "name": "screen_process",
            "description": "Launch an application and wait for its window to appear. Returns the window ID for use with other screen tools. Atomic app-open operation.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "Command to launch (e.g. 'firefox', 'discord', 'gnome-calculator')"
                    },
                    "args": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Command arguments"
                    },
                    "window_title": {
                        "type": "string",
                        "description": "Regex pattern for the expected window title (auto-detected from command name if omitted)"
                    },
                    "timeout_ms": {
                        "type": "number",
                        "description": "Max time to wait for window (default 15000ms)"
                    }
                },
                "required": ["command"]
            }
        }),
    ]
}

// ── screen_clipboard ──────────────────────────────────────────────

pub async fn clipboard(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let action = args["action"].as_str().context("Missing 'action'")?;

    match action {
        "read" => clipboard_read(module),
        "write" => {
            let text = args["text"].as_str().context("Missing 'text' for write")?;
            clipboard_write(module, text)
        }
        _ => Err(anyhow::anyhow!("Unknown action '{}'. Use 'read' or 'write'.", action)),
    }
}

fn clipboard_read(_module: &ScreenModule) -> anyhow::Result<Value> {
    use cli_clipboard::ClipboardProvider;

    // Use cli-clipboard crate (compiled in, no external deps)
    let mut ctx = cli_clipboard::ClipboardContext::new()
        .map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
    let text = ctx.get_contents()
        .map_err(|e| anyhow::anyhow!("Failed to read clipboard: {}", e))?;

    Ok(json!({ "text": text, "length": text.len() }))
}

fn clipboard_write(_module: &ScreenModule, text: &str) -> anyhow::Result<Value> {
    use cli_clipboard::ClipboardProvider;

    let mut ctx = cli_clipboard::ClipboardContext::new()
        .map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
    ctx.set_contents(text.to_string())
        .map_err(|e| anyhow::anyhow!("Failed to write clipboard: {}", e))?;

    Ok(json!({ "success": true, "length": text.len() }))
}

// ── screen_pixel ──────────────────────────────────────────────────

pub async fn pixel(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let x = args["x"].as_u64().context("Missing 'x'")? as u32;
    let y = args["y"].as_u64().context("Missing 'y'")? as u32;
    let sample_size = args["sample_size"].as_u64().unwrap_or(1).max(1) as u32;

    let tmp = super::shm_temp_path("pixel", "png");

    if let Some(ref scrot) = module.scrot_path {
        // Capture a small region around the target pixel
        let capture_pad = 5u32;
        let cx = x.saturating_sub(capture_pad);
        let cy = y.saturating_sub(capture_pad);
        let cw = sample_size + capture_pad * 2;
        let ch = sample_size + capture_pad * 2;
        let area = format!("{},{},{},{}", cx, cy, cw, ch);
        let output = Command::new(scrot).args(["-a", &area, "-o", &tmp]).output();
        if let Ok(o) = output {
            if o.status.success() {
                if let Ok(img) = image::open(&tmp) {
                    let _ = std::fs::remove_file(&tmp);
                    let rgba = img.to_rgba8();
                    // Coords relative to captured region
                    let rel_x = x - cx;
                    let rel_y = y - cy;
                    return Ok(pixel_result(&rgba, rel_x, rel_y, sample_size, x, y));
                }
            }
        }
        let _ = std::fs::remove_file(&tmp);
    }

    // Fallback: xcap full capture (slower)
    let monitors = xcap::Monitor::all().context("Failed to enumerate monitors")?;
    let monitor = monitors.first().context("No monitors")?;
    let img = monitor.capture_image().context("Failed to capture")?;
    Ok(pixel_result(&img, x, y, sample_size, x, y))
}

fn pixel_result(img: &image::RgbaImage, img_x: u32, img_y: u32, sample_size: u32, screen_x: u32, screen_y: u32) -> Value {
    if img.width() == 0 || img.height() == 0 {
        return json!({"error": "Captured image has zero dimensions", "x": screen_x, "y": screen_y});
    }
    if sample_size <= 1 {
        let px = img_x.min(img.width().saturating_sub(1));
        let py = img_y.min(img.height().saturating_sub(1));
        let p = img.get_pixel(px, py);
        let hex = format!("#{:02x}{:02x}{:02x}", p[0], p[1], p[2]);
        return json!({
            "x": screen_x, "y": screen_y,
            "r": p[0], "g": p[1], "b": p[2], "a": p[3],
            "hex": hex
        });
    }

    // Average NxN area
    let half = sample_size / 2;
    let mut r_sum = 0u64;
    let mut g_sum = 0u64;
    let mut b_sum = 0u64;
    let mut count = 0u64;

    for dy in 0..sample_size {
        for dx in 0..sample_size {
            let px = (img_x + dx).saturating_sub(half);
            let py = (img_y + dy).saturating_sub(half);
            if px < img.width() && py < img.height() {
                let p = img.get_pixel(px, py);
                r_sum += p[0] as u64;
                g_sum += p[1] as u64;
                b_sum += p[2] as u64;
                count += 1;
            }
        }
    }

    if count == 0 {
        return json!({"error": "Coordinates out of bounds"});
    }

    let r = (r_sum / count) as u8;
    let g = (g_sum / count) as u8;
    let b = (b_sum / count) as u8;
    let hex = format!("#{:02x}{:02x}{:02x}", r, g, b);

    json!({
        "x": screen_x, "y": screen_y, "sample_size": sample_size,
        "r": r, "g": g, "b": b, "hex": hex
    })
}

// ── screen_diff ───────────────────────────────────────────────────

/// Max stored diff references. Oldest entries evicted when exceeded.
const MAX_DIFF_REFS: usize = 10;

/// Ordered storage for diff references — Vec maintains insertion order for FIFO eviction.
static DIFF_REFS: std::sync::Mutex<Option<Vec<(String, Vec<u8>)>>> =
    std::sync::Mutex::new(None);

pub async fn diff(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let action = args["action"].as_str().context("Missing 'action'")?;
    let name = args["name"].as_str().unwrap_or("default");
    let threshold = args["threshold"].as_u64().unwrap_or(30) as u8;

    match action {
        "save" => {
            // Capture current screen and save as reference
            let tmp = super::shm_temp_path("diff", "png");
            let img_bytes = if let Some(ref scrot) = module.scrot_path {
                let _ = Command::new(scrot).args(["-o", &tmp]).output();
                let bytes = std::fs::read(&tmp).context("Failed to read capture")?;
                let _ = std::fs::remove_file(&tmp);
                bytes
            } else {
                let monitors = xcap::Monitor::all()?;
                let monitor = monitors.first().context("No monitors")?;
                let img = monitor.capture_image()?;
                let tmp2 = super::shm_temp_path("diff_xcap", "png");
                img.save(&tmp2).context("Failed to save capture")?;
                let bytes = std::fs::read(&tmp2).context("Failed to read capture")?;
                let _ = std::fs::remove_file(&tmp2);
                bytes
            };

            let size = img_bytes.len();
            let mut refs = DIFF_REFS.lock().unwrap_or_else(|p| p.into_inner());
            let list = refs.get_or_insert_with(Vec::new);
            // Remove existing entry with same name (will re-add at end)
            list.retain(|(k, _)| k != name);
            // Evict oldest (first) entries if over limit
            while list.len() >= MAX_DIFF_REFS {
                list.remove(0);
            }
            list.push((name.to_string(), img_bytes));

            Ok(json!({
                "success": true,
                "action": "save",
                "name": name,
                "bytes": size
            }))
        }
        "compare" => {
            // Capture current and diff against reference
            let ref_bytes = {
                let refs = DIFF_REFS.lock().unwrap_or_else(|p| p.into_inner());
                refs.as_ref()
                    .and_then(|list| list.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone()))
                    .ok_or_else(|| anyhow::anyhow!(
                        "No reference '{}' saved. Call screen_diff with action='save' first.", name
                    ))?
            };

            let ref_img = image::load_from_memory(&ref_bytes)
                .context("Failed to decode reference image")?
                .to_rgba8();

            // Capture current
            let tmp = super::shm_temp_path("diff_now", "png");
            let current_img = if let Some(ref scrot) = module.scrot_path {
                let _ = Command::new(scrot).args(["-o", &tmp]).output();
                let img = image::open(&tmp).context("Failed to open capture")?.to_rgba8();
                let _ = std::fs::remove_file(&tmp);
                img
            } else {
                let monitors = xcap::Monitor::all()?;
                let monitor = monitors.first().context("No monitors")?;
                monitor.capture_image()?
            };

            // Compare pixel by pixel, find changed regions
            let (changed_pixels, regions) = compare_images(&ref_img, &current_img, threshold);
            let total_pixels = ref_img.width() as u64 * ref_img.height() as u64;
            let change_pct = if total_pixels > 0 {
                (changed_pixels as f64 / total_pixels as f64) * 100.0
            } else {
                0.0
            };

            Ok(json!({
                "changed": changed_pixels > 0,
                "changed_pixels": changed_pixels,
                "total_pixels": total_pixels,
                "change_percent": format!("{:.2}", change_pct),
                "regions": regions
            }))
        }
        _ => Err(anyhow::anyhow!("Unknown action '{}'. Use 'save' or 'compare'.", action)),
    }
}

fn compare_images(a: &image::RgbaImage, b: &image::RgbaImage, threshold: u8) -> (u64, Vec<Value>) {
    let w = a.width().min(b.width());
    let h = a.height().min(b.height());
    let threshold = threshold as i16;

    let mut changed_pixels = 0u64;
    // Track changed regions using a grid (divide screen into 64x64 cells)
    let cell_size = 64u32;
    let cols = (w + cell_size - 1) / cell_size;
    let rows = (h + cell_size - 1) / cell_size;
    let mut grid = vec![false; (cols * rows) as usize];

    for py in 0..h {
        for px in 0..w {
            let pa = a.get_pixel(px, py);
            let pb = b.get_pixel(px, py);
            let dr = (pa[0] as i16 - pb[0] as i16).abs();
            let dg = (pa[1] as i16 - pb[1] as i16).abs();
            let db = (pa[2] as i16 - pb[2] as i16).abs();

            if dr > threshold || dg > threshold || db > threshold {
                changed_pixels += 1;
                let cx = px / cell_size;
                let cy = py / cell_size;
                grid[(cy * cols + cx) as usize] = true;
            }
        }
    }

    // Convert grid to bounding box regions
    let mut regions: Vec<Value> = Vec::new();
    for cy in 0..rows {
        for cx in 0..cols {
            if grid[(cy * cols + cx) as usize] {
                regions.push(json!({
                    "x": cx * cell_size,
                    "y": cy * cell_size,
                    "width": cell_size.min(w - cx * cell_size),
                    "height": cell_size.min(h - cy * cell_size),
                    "center_x": cx * cell_size + cell_size / 2,
                    "center_y": cy * cell_size + cell_size / 2,
                }));
            }
        }
    }

    (changed_pixels, regions)
}

// ── screen_process ────────────────────────────────────────────────

pub async fn process(args: Value) -> anyhow::Result<Value> {
    let command = args["command"].as_str().context("Missing 'command'")?;
    let cmd_args: Vec<String> = args["args"]
        .as_array()
        .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
        .unwrap_or_default();
    let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(15000);

    // Determine window title pattern
    let window_pattern = args["window_title"]
        .as_str()
        .map(String::from)
        .unwrap_or_else(|| {
            // Auto-derive from command name (e.g. "firefox" → "(?i)firefox")
            let base = command.rsplit('/').next().unwrap_or(command);
            format!("(?i){}", regex::escape(base))
        });

    let re = regex::Regex::new(&window_pattern)
        .context("Invalid window_title pattern")?;

    // Launch the process (detached — reap in background to avoid zombies)
    let mut child = Command::new(command)
        .args(&cmd_args)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .context(format!("Failed to launch '{}'", command))?;

    let pid = child.id();

    // Spawn a background task to reap the child process (prevents zombie)
    tokio::task::spawn_blocking(move || {
        let _ = child.wait();
    });

    // Poll for window
    let start = std::time::Instant::now();
    let poll_interval = tokio::time::Duration::from_millis(300);

    loop {
        if let Ok(windows) = xcap::Window::all() {
            for win in &windows {
                if re.is_match(win.title()) {
                    let elapsed = start.elapsed().as_millis();
                    return Ok(json!({
                        "success": true,
                        "command": command,
                        "pid": pid,
                        "window_id": format!("0x{:08x}", win.id()),
                        "window_title": win.title(),
                        "x": win.x(),
                        "y": win.y(),
                        "width": win.width(),
                        "height": win.height(),
                        "waited_ms": elapsed
                    }));
                }
            }
        }

        if start.elapsed().as_millis() as u64 >= timeout_ms {
            return Ok(json!({
                "success": false,
                "command": command,
                "pid": pid,
                "error": format!("Window matching '{}' did not appear within {}ms", window_pattern, timeout_ms),
                "waited_ms": timeout_ms
            }));
        }

        tokio::time::sleep(poll_interval).await;
    }
}