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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use super::ScreenModule;
use anyhow::Context;
use serde_json::{json, Value};
use std::process::Command;

pub fn tools() -> Vec<Value> {
    vec![
        json!({
            "name": "screen_windows",
            "description": "List all open windows with their IDs, titles, positions, and sizes. Use the window ID with screen_capture (target='window') or screen_focus. Optionally filter by title pattern.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "filter": {
                        "type": "string",
                        "description": "Optional regex pattern to filter window titles"
                    }
                },
                "required": []
            }
        }),
        json!({
            "name": "screen_focus",
            "description": "Manage a window: focus, minimize, maximize, close, resize, or move it. Target by window_id or title pattern. Uses xdotool (no extra install needed).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "window_id": {
                        "type": "string",
                        "description": "Window ID (hex from screen_windows, or decimal)"
                    },
                    "title": {
                        "type": "string",
                        "description": "Window title pattern (used if window_id not provided)"
                    },
                    "action": {
                        "type": "string",
                        "description": "Action to perform",
                        "enum": ["focus", "minimize", "maximize", "close", "resize", "move"]
                    },
                    "width": { "type": "number", "description": "New width (for resize)" },
                    "height": { "type": "number", "description": "New height (for resize)" },
                    "x": { "type": "number", "description": "New X position (for move)" },
                    "y": { "type": "number", "description": "New Y position (for move)" }
                },
                "required": ["action"]
            }
        }),
        json!({
            "name": "screen_wait",
            "description": "Wait for a specified time or until a window with a matching title appears.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "ms": {
                        "type": "number",
                        "description": "Milliseconds to wait (simple delay)"
                    },
                    "window_title": {
                        "type": "string",
                        "description": "Wait until a window with this title pattern appears"
                    },
                    "timeout_ms": {
                        "type": "number",
                        "description": "Timeout for window_title wait (default 10000ms)"
                    }
                },
                "required": []
            }
        }),
    ]
}

// ── Tool implementations ──────────────────────────────────────────

pub async fn list_windows(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let filter = args["filter"].as_str();

    let filter_regex = if let Some(pattern) = filter {
        Some(regex::Regex::new(pattern).context("Invalid filter regex")?)
    } else {
        None
    };

    let mut windows: Vec<Value> = Vec::new();

    // Try xcap first (works on both X11 and Wayland)
    if let Ok(xcap_windows) = xcap::Window::all() {
        let active_id = get_active_window_id(module);

        for win in &xcap_windows {
            let title = win.title();
            if title.is_empty() {
                continue;
            }

            if let Some(ref re) = filter_regex {
                if !re.is_match(title) {
                    continue;
                }
            }

            let id = win.id();
            windows.push(json!({
                "id": format!("0x{:08x}", id),
                "title": title,
                "x": win.x(),
                "y": win.y(),
                "width": win.width(),
                "height": win.height(),
                "is_focused": active_id.map_or(false, |aid| aid == id),
                "is_minimized": win.is_minimized(),
            }));
        }
    } else if let Some(ref wmctrl) = module.wmctrl_path {
        // Fast fallback: wmctrl -lG (single subprocess, all windows)
        windows = list_windows_wmctrl(wmctrl, &filter_regex, module)?;
    } else if let Some(ref xdotool) = module.xdotool_path {
        // Slow fallback: xdotool (O(n) subprocess calls per window)
        windows = list_windows_xdotool(xdotool, &filter_regex)?;
    }

    Ok(json!({
        "window_count": windows.len(),
        "windows": windows
    }))
}

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

    if window_id.is_none() && title.is_none() {
        return Err(anyhow::anyhow!("Provide either 'window_id' or 'title' to target a window"));
    }

    // Resolve window ID
    let resolved_id = resolve_window_id(module, window_id, title)?;
    let target_desc = if let Some(id) = window_id {
        format!("window {}", id)
    } else {
        format!("window titled '{}'", title.unwrap_or("?"))
    };

    // Try xdotool first (most commonly available), then wmctrl
    if let Some(ref xdotool) = module.xdotool_path {
        return focus_with_xdotool(xdotool, &resolved_id, action, &args, &target_desc);
    }

    if let Some(ref wmctrl) = module.wmctrl_path {
        return focus_with_wmctrl(wmctrl, &resolved_id, action, &args, &target_desc);
    }

    Err(anyhow::anyhow!(
        "Neither xdotool nor wmctrl found. Install one: sudo apt install xdotool"
    ))
}

pub async fn wait(_module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let ms = args["ms"].as_u64();
    let window_title = args["window_title"].as_str();
    let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(10000);

    if let Some(delay) = ms {
        tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
        return Ok(json!({
            "success": true,
            "waited_ms": delay
        }));
    }

    if let Some(title_pattern) = window_title {
        let re = regex::Regex::new(title_pattern).context("Invalid window_title pattern")?;
        let start = std::time::Instant::now();
        let poll_interval = tokio::time::Duration::from_millis(200);

        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,
                            "waited_ms": elapsed,
                            "found_window": win.title()
                        }));
                    }
                }
            }

            if start.elapsed().as_millis() as u64 >= timeout_ms {
                return Ok(json!({
                    "success": false,
                    "waited_ms": timeout_ms,
                    "error": format!("Timed out waiting for window matching '{}'", title_pattern)
                }));
            }

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

    Ok(json!({
        "success": true,
        "waited_ms": 0,
        "note": "No wait condition specified. Provide 'ms' or 'window_title'."
    }))
}

// ── xdotool backend ───────────────────────────────────────────────

fn resolve_window_id(
    module: &ScreenModule,
    window_id: Option<&str>,
    title: Option<&str>,
) -> anyhow::Result<String> {
    if let Some(id) = window_id {
        // Convert hex to decimal for xdotool
        if id.starts_with("0x") || id.starts_with("0X") {
            let decimal = u64::from_str_radix(&id[2..], 16)
                .context("Invalid hex window ID")?;
            return Ok(decimal.to_string());
        }
        return Ok(id.to_string());
    }

    // Search by title using xdotool
    if let Some(pattern) = title {
        if let Some(ref xdotool) = module.xdotool_path {
            let output = Command::new(xdotool)
                .args(["search", "--name", pattern])
                .output()
                .context("Failed to search for window")?;

            if output.status.success() {
                let stdout = String::from_utf8_lossy(&output.stdout);
                if let Some(first_id) = stdout.lines().next() {
                    if !first_id.trim().is_empty() {
                        return Ok(first_id.trim().to_string());
                    }
                }
            }
        }
    }

    Err(anyhow::anyhow!("Could not resolve window target"))
}

fn focus_with_xdotool(
    xdotool: &std::path::Path,
    window_id: &str,
    action: &str,
    args: &Value,
    target_desc: &str,
) -> anyhow::Result<Value> {
    let result = match action {
        "focus" => run_cmd(xdotool, &["windowactivate", window_id]),
        "minimize" => run_cmd(xdotool, &["windowminimize", window_id]),
        "maximize" => {
            // xdotool doesn't have maximize directly — use windowsize 100% 100%
            run_cmd(xdotool, &["windowsize", window_id, "100%", "100%"])
        }
        "close" => run_cmd(xdotool, &["windowclose", window_id]),
        "resize" => {
            let w = args["width"].as_i64().context("Missing 'width' for resize")?;
            let h = args["height"].as_i64().context("Missing 'height' for resize")?;
            run_cmd(xdotool, &["windowsize", window_id, &w.to_string(), &h.to_string()])
        }
        "move" => {
            let x = args["x"].as_i64().context("Missing 'x' for move")?;
            let y = args["y"].as_i64().context("Missing 'y' for move")?;
            run_cmd(xdotool, &["windowmove", window_id, &x.to_string(), &y.to_string()])
        }
        _ => return Err(anyhow::anyhow!(
            "Unknown action '{}'. Use: focus, minimize, maximize, close, resize, move",
            action
        )),
    };

    match result {
        Ok(()) => Ok(json!({
            "success": true,
            "action": action,
            "target": target_desc,
            "backend": "xdotool"
        })),
        Err(e) => Err(anyhow::anyhow!("Failed to {} {}: {}", action, target_desc, e)),
    }
}

fn focus_with_wmctrl(
    wmctrl: &std::path::Path,
    window_id: &str,
    action: &str,
    args: &Value,
    target_desc: &str,
) -> anyhow::Result<Value> {
    let result = match action {
        "focus" => run_cmd(wmctrl, &["-i", "-a", window_id]),
        "minimize" => run_cmd(wmctrl, &["-i", "-r", window_id, "-b", "add,hidden"]),
        "maximize" => run_cmd(wmctrl, &["-i", "-r", window_id, "-b", "add,maximized_vert,maximized_horz"]),
        "close" => run_cmd(wmctrl, &["-i", "-c", window_id]),
        "resize" => {
            let w = args["width"].as_i64().context("Missing 'width' for resize")?;
            let h = args["height"].as_i64().context("Missing 'height' for resize")?;
            let geom = format!("0,-1,-1,{},{}", w, h);
            run_cmd(wmctrl, &["-i", "-r", window_id, "-e", &geom])
        }
        "move" => {
            let x = args["x"].as_i64().context("Missing 'x' for move")?;
            let y = args["y"].as_i64().context("Missing 'y' for move")?;
            let geom = format!("0,{},{},-1,-1", x, y);
            run_cmd(wmctrl, &["-i", "-r", window_id, "-e", &geom])
        }
        _ => return Err(anyhow::anyhow!(
            "Unknown action '{}'. Use: focus, minimize, maximize, close, resize, move",
            action
        )),
    };

    match result {
        Ok(()) => Ok(json!({
            "success": true,
            "action": action,
            "target": target_desc,
            "backend": "wmctrl"
        })),
        Err(e) => Err(anyhow::anyhow!("Failed to {} {}: {}", action, target_desc, e)),
    }
}

/// Fast batch window listing — one subprocess call for all windows.
/// `wmctrl -lG` output: `ID DESKTOP X Y WIDTH HEIGHT HOST TITLE...`
fn list_windows_wmctrl(
    wmctrl: &std::path::Path,
    filter: &Option<regex::Regex>,
    module: &ScreenModule,
) -> anyhow::Result<Vec<Value>> {
    let output = Command::new(wmctrl)
        .args(["-lG"])
        .output()
        .context("Failed to run wmctrl -lG")?;

    if !output.status.success() {
        return Err(anyhow::anyhow!("wmctrl -lG failed: {}", String::from_utf8_lossy(&output.stderr)));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let active_id = get_active_window_id(module);
    let mut windows = Vec::new();

    // Parse wmctrl -lG output with regex for reliability
    // Format: 0x04e00003  0 100  50  800  600  hostname Title of Window
    let re = regex::Regex::new(r"(0x\w+)\s+\d+\s+(-?\d+)\s+(-?\d+)\s+(\d+)\s+(\d+)\s+\S+\s+(.*)")
        .context("Invalid regex")?;

    for line in stdout.lines() {
        let caps = match re.captures(line) {
            Some(c) => c,
            None => continue,
        };

        let id_hex = caps.get(1).unwrap().as_str();
        let x: i64 = caps[2].parse().unwrap_or(0);
        let y: i64 = caps[3].parse().unwrap_or(0);
        let w: i64 = caps[4].parse().unwrap_or(0);
        let h: i64 = caps[5].parse().unwrap_or(0);
        let title = caps.get(6).unwrap().as_str().trim();

        if title.is_empty() || title == "N/A" {
            continue;
        }

        if let Some(ref re) = filter {
            if !re.is_match(title) {
                continue;
            }
        }

        let id_decimal: u32 = if id_hex.starts_with("0x") || id_hex.starts_with("0X") {
            u32::from_str_radix(&id_hex[2..], 16).unwrap_or(0)
        } else {
            id_hex.parse().unwrap_or(0)
        };

        windows.push(json!({
            "id": id_hex,
            "title": title,
            "x": x,
            "y": y,
            "width": w,
            "height": h,
            "is_focused": active_id.map_or(false, |aid| aid == id_decimal),
        }));
    }

    Ok(windows)
}

fn list_windows_xdotool(
    xdotool: &std::path::Path,
    filter: &Option<regex::Regex>,
) -> anyhow::Result<Vec<Value>> {
    // Get all window IDs
    let search_args = if let Some(ref re) = filter {
        vec!["search", "--name", re.as_str()]
    } else {
        vec!["search", "--name", ""]
    };

    let output = Command::new(xdotool)
        .args(&search_args)
        .output()
        .context("Failed to run xdotool search")?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let active_id = get_active_window_id_str(xdotool);
    let mut windows = Vec::new();

    for line in stdout.lines() {
        let wid = line.trim();
        if wid.is_empty() {
            continue;
        }

        // Get window name
        let name_output = Command::new(xdotool)
            .args(["getwindowname", wid])
            .output();

        let title = name_output
            .ok()
            .filter(|o| o.status.success())
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap_or_default();

        if title.is_empty() {
            continue;
        }

        // Get window geometry
        let geom_output = Command::new(xdotool)
            .args(["getwindowgeometry", "--shell", wid])
            .output();

        let (x, y, w, h) = parse_xdotool_geometry(
            &geom_output
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
                .unwrap_or_default(),
        );

        let id_num: u64 = wid.parse().unwrap_or(0);

        windows.push(json!({
            "id": format!("0x{:08x}", id_num),
            "title": title,
            "x": x,
            "y": y,
            "width": w,
            "height": h,
            "is_focused": active_id.as_deref() == Some(wid),
        }));
    }

    Ok(windows)
}

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

fn get_active_window_id(module: &ScreenModule) -> Option<u32> {
    if let Some(ref path) = module.xdotool_path {
        if let Ok(output) = Command::new(path).arg("getactivewindow").output() {
            if output.status.success() {
                let s = String::from_utf8_lossy(&output.stdout);
                return s.trim().parse().ok();
            }
        }
    }
    None
}

fn get_active_window_id_str(xdotool: &std::path::Path) -> Option<String> {
    Command::new(xdotool)
        .arg("getactivewindow")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

fn parse_xdotool_geometry(shell_output: &str) -> (i64, i64, i64, i64) {
    let mut x = 0i64;
    let mut y = 0i64;
    let mut w = 0i64;
    let mut h = 0i64;

    for line in shell_output.lines() {
        let line = line.trim();
        if let Some(val) = line.strip_prefix("X=") {
            x = val.parse().unwrap_or(0);
        } else if let Some(val) = line.strip_prefix("Y=") {
            y = val.parse().unwrap_or(0);
        } else if let Some(val) = line.strip_prefix("WIDTH=") {
            w = val.parse().unwrap_or(0);
        } else if let Some(val) = line.strip_prefix("HEIGHT=") {
            h = val.parse().unwrap_or(0);
        }
    }

    (x, y, w, h)
}

fn run_cmd(bin: &std::path::Path, args: &[&str]) -> anyhow::Result<()> {
    let output = Command::new(bin)
        .args(args)
        .output()
        .context(format!("Failed to run {}", bin.display()))?;

    if output.status.success() {
        Ok(())
    } else {
        Err(anyhow::anyhow!(
            "{} exited with {}: {}",
            bin.display(),
            output.status,
            String::from_utf8_lossy(&output.stderr)
        ))
    }
}