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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
use super::ScreenModule;
use anyhow::Context;
use enigo::{
    Button, Coordinate, Direction, Key, Keyboard, Mouse,
};
use serde_json::{json, Value};

pub fn tools() -> Vec<Value> {
    vec![
        json!({
            "name": "screen_click",
            "description": "Click at screen coordinates. Supports left/right/middle buttons, single/double/triple click, and modifier keys (ctrl, shift, alt, super).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "x": { "type": "number", "description": "X coordinate (pixels)" },
                    "y": { "type": "number", "description": "Y coordinate (pixels)" },
                    "button": {
                        "type": "string",
                        "description": "Mouse button: 'left', 'right', or 'middle' (default 'left')",
                        "enum": ["left", "right", "middle"]
                    },
                    "count": {
                        "type": "number",
                        "description": "Click count: 1 (single), 2 (double), 3 (triple). Default 1."
                    },
                    "modifiers": {
                        "type": "array",
                        "items": { "type": "string", "enum": ["ctrl", "shift", "alt", "super"] },
                        "description": "Modifier keys to hold during click"
                    }
                },
                "required": ["x", "y"]
            }
        }),
        json!({
            "name": "screen_type",
            "description": "Type a text string into the currently focused window. Simulates keyboard input character by character.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "text": { "type": "string", "description": "Text to type" },
                    "delay_ms": {
                        "type": "number",
                        "description": "Delay in ms between keystrokes (default 0 for instant)"
                    }
                },
                "required": ["text"]
            }
        }),
        json!({
            "name": "screen_key",
            "description": "Press a key combination, or hold a key for a duration. Examples: 'ctrl+c', 'alt+Tab', 'Return', 'F5', 'ctrl+shift+s', 'super'. Use hold_ms to hold the key(s) for sustained press. Supported keys: a-z, 0-9, F1-F12, Return/Enter, Tab, Escape/Esc, Backspace, Delete, Space, Up/Down/Left/Right, Home, End, PageUp, PageDown, plus modifiers ctrl/shift/alt/super.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "keys": {
                        "type": "string",
                        "description": "Key combination, e.g. 'ctrl+c', 'Return', 'alt+Tab'"
                    },
                    "hold_ms": {
                        "type": "number",
                        "description": "Hold duration in ms. If set, keys are pressed, held for this duration, then released."
                    }
                },
                "required": ["keys"]
            }
        }),
        json!({
            "name": "screen_move",
            "description": "Move the mouse cursor to the specified screen coordinates.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "x": { "type": "number", "description": "X coordinate (pixels)" },
                    "y": { "type": "number", "description": "Y coordinate (pixels)" }
                },
                "required": ["x", "y"]
            }
        }),
        json!({
            "name": "screen_scroll",
            "description": "Scroll at the specified screen position. Use 'lines' for simple scrolling (positive = down, negative = up) or 'delta_x'/'delta_y' for pixel-precise control.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "x": { "type": "number", "description": "X coordinate to scroll at" },
                    "y": { "type": "number", "description": "Y coordinate to scroll at" },
                    "lines": {
                        "type": "number",
                        "description": "Lines to scroll (positive = down, negative = up)"
                    },
                    "delta_x": { "type": "number", "description": "Horizontal scroll pixels" },
                    "delta_y": { "type": "number", "description": "Vertical scroll pixels (negative = down)" }
                },
                "required": ["x", "y"]
            }
        }),
        json!({
            "name": "screen_drag",
            "description": "Click and drag from one position to another. Useful for moving windows, selecting text, or drag-and-drop operations.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "from_x": { "type": "number", "description": "Start X coordinate" },
                    "from_y": { "type": "number", "description": "Start Y coordinate" },
                    "to_x": { "type": "number", "description": "End X coordinate" },
                    "to_y": { "type": "number", "description": "End Y coordinate" },
                    "button": {
                        "type": "string",
                        "description": "Mouse button: 'left' or 'right' (default 'left')",
                        "enum": ["left", "right"]
                    },
                    "duration_ms": {
                        "type": "number",
                        "description": "Duration of drag in ms (default 300). Longer = smoother."
                    }
                },
                "required": ["from_x", "from_y", "to_x", "to_y"]
            }
        }),
    ]
}

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

pub async fn click(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let x = args["x"].as_i64().context("Missing 'x' parameter")? as i32;
    let y = args["y"].as_i64().context("Missing 'y' parameter")? as i32;
    let button_str = args["button"].as_str().unwrap_or("left");
    let count = args["count"].as_u64().unwrap_or(1).min(3) as usize;

    let modifiers = args["modifiers"]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    // Try enigo first, fall back to xdotool subprocess
    if let Ok(mut enigo) = module.create_enigo() {
        let button = parse_button(button_str)?;
        return click_enigo(&mut enigo, x, y, button, button_str, count, &modifiers);
    }

    // Fallback: xdotool subprocess
    if let Some(ref xdotool) = module.xdotool_path {
        return click_xdotool(xdotool, x, y, button_str, count);
    }

    Err(anyhow::anyhow!("No input backend available. Install xdotool: sudo apt install xdotool"))
}

fn click_enigo(
    enigo: &mut enigo::Enigo,
    x: i32, y: i32,
    button: Button,
    button_str: &str,
    count: usize,
    modifiers: &[&str],
) -> anyhow::Result<Value> {
    // Move to position
    enigo.move_mouse(x, y, Coordinate::Abs)
        .map_err(|e| anyhow::anyhow!("Failed to move mouse: {}", e))?;

    // Hold modifiers
    for m in modifiers {
        if let Some(key) = modifier_key(m) {
            enigo.key(key, Direction::Press)
                .map_err(|e| anyhow::anyhow!("Failed to press modifier {}: {}", m, e))?;
        }
    }

    // Click
    for _ in 0..count {
        enigo.button(button, Direction::Click)
            .map_err(|e| anyhow::anyhow!("Failed to click: {}", e))?;
    }

    // Release modifiers (reverse order)
    for m in modifiers.iter().rev() {
        if let Some(key) = modifier_key(m) {
            enigo.key(key, Direction::Release)
                .map_err(|e| anyhow::anyhow!("Failed to release modifier {}: {}", m, e))?;
        }
    }

    Ok(json!({
        "success": true,
        "x": x,
        "y": y,
        "button": button_str,
        "count": count
    }))
}

fn click_xdotool(
    xdotool: &std::path::Path,
    x: i32, y: i32,
    button_str: &str,
    count: usize,
) -> anyhow::Result<Value> {
    let btn = match button_str {
        "right" => "3",
        "middle" => "2",
        _ => "1",
    };

    // Move then click
    let output = std::process::Command::new(xdotool)
        .args(["mousemove", &x.to_string(), &y.to_string(),
               "click", "--repeat", &count.to_string(), btn])
        .output()
        .map_err(|e| anyhow::anyhow!("xdotool failed: {}", e))?;

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

    Ok(json!({
        "success": true,
        "x": x, "y": y,
        "button": button_str,
        "count": count,
        "backend": "xdotool"
    }))
}

pub async fn type_text(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let text = args["text"].as_str().context("Missing 'text' parameter")?;
    let delay_ms = args["delay_ms"].as_u64().unwrap_or(0);

    // Try enigo first
    if let Ok(mut enigo) = module.create_enigo() {
        if delay_ms == 0 {
            enigo.text(text)
                .map_err(|e| anyhow::anyhow!("Failed to type text: {}", e))?;
        } else {
            for ch in text.chars() {
                enigo.text(&ch.to_string())
                    .map_err(|e| anyhow::anyhow!("Failed to type char '{}': {}", ch, e))?;
                tokio::time::sleep(tokio::time::Duration::from_millis(delay_ms)).await;
            }
        }
        return Ok(json!({ "success": true, "chars_typed": text.len() }));
    }

    // Fallback: xdotool type
    if let Some(ref xdotool) = module.xdotool_path {
        let mut cmd_args = vec!["type"];
        let delay_str;
        if delay_ms > 0 {
            delay_str = delay_ms.to_string();
            cmd_args.extend(["--delay", &delay_str]);
        }
        cmd_args.push(text);

        let output = std::process::Command::new(xdotool)
            .args(&cmd_args)
            .output()
            .map_err(|e| anyhow::anyhow!("xdotool type failed: {}", e))?;

        if !output.status.success() {
            return Err(anyhow::anyhow!("xdotool type failed: {}", String::from_utf8_lossy(&output.stderr)));
        }
        return Ok(json!({ "success": true, "chars_typed": text.len(), "backend": "xdotool" }));
    }

    Err(anyhow::anyhow!("No input backend available"))
}

pub async fn key(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let keys_str = args["keys"].as_str().context("Missing 'keys' parameter")?;
    let hold_ms = args["hold_ms"].as_u64();

    // Try enigo first
    if let Ok(mut enigo) = module.create_enigo() {
        let (modifier_keys, main_key) = parse_key_combo(keys_str)?;

        for mk in &modifier_keys {
            enigo.key(*mk, Direction::Press)
                .map_err(|e| anyhow::anyhow!("Failed to press modifier: {}", e))?;
        }

        if let Some(duration) = hold_ms {
            enigo.key(main_key, Direction::Press)
                .map_err(|e| anyhow::anyhow!("Failed to press key: {}", e))?;
            tokio::time::sleep(tokio::time::Duration::from_millis(duration)).await;
            enigo.key(main_key, Direction::Release)
                .map_err(|e| anyhow::anyhow!("Failed to release key: {}", e))?;
        } else {
            enigo.key(main_key, Direction::Click)
                .map_err(|e| anyhow::anyhow!("Failed to press key: {}", e))?;
        }

        for mk in modifier_keys.iter().rev() {
            enigo.key(*mk, Direction::Release)
                .map_err(|e| anyhow::anyhow!("Failed to release modifier: {}", e))?;
        }

        return Ok(json!({ "success": true, "keys": keys_str, "held_ms": hold_ms }));
    }

    // Fallback: xdotool key
    if let Some(ref xdotool) = module.xdotool_path {
        let output = std::process::Command::new(xdotool)
            .args(["key", keys_str])
            .output()
            .map_err(|e| anyhow::anyhow!("xdotool key failed: {}", e))?;

        if !output.status.success() {
            return Err(anyhow::anyhow!("xdotool key failed: {}", String::from_utf8_lossy(&output.stderr)));
        }
        return Ok(json!({ "success": true, "keys": keys_str, "backend": "xdotool" }));
    }

    Err(anyhow::anyhow!("No input backend available"))
}

pub async fn move_mouse(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let x = args["x"].as_i64().context("Missing 'x' parameter")? as i32;
    let y = args["y"].as_i64().context("Missing 'y' parameter")? as i32;

    if let Ok(mut enigo) = module.create_enigo() {
        enigo.move_mouse(x, y, Coordinate::Abs)
            .map_err(|e| anyhow::anyhow!("Failed to move mouse: {}", e))?;
        return Ok(json!({ "success": true, "x": x, "y": y }));
    }

    // Fallback: xdotool
    if let Some(ref xdotool) = module.xdotool_path {
        let output = std::process::Command::new(xdotool)
            .args(["mousemove", &x.to_string(), &y.to_string()])
            .output()
            .map_err(|e| anyhow::anyhow!("xdotool mousemove failed: {}", e))?;

        if output.status.success() {
            return Ok(json!({ "success": true, "x": x, "y": y, "backend": "xdotool" }));
        }
    }

    Err(anyhow::anyhow!("No input backend available"))
}

pub async fn scroll(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let x = args["x"].as_i64().context("Missing 'x' parameter")? as i32;
    let y = args["y"].as_i64().context("Missing 'y' parameter")? as i32;
    let lines_arg = args["lines"].as_i64();

    // Try enigo first
    if let Ok(mut enigo) = module.create_enigo() {
        enigo.move_mouse(x, y, Coordinate::Abs)
            .map_err(|e| anyhow::anyhow!("Failed to move mouse: {}", e))?;

        if let Some(lines) = lines_arg {
            enigo.scroll(-lines as i32, enigo::Axis::Vertical)
                .map_err(|e| anyhow::anyhow!("Failed to scroll: {}", e))?;
        } else {
            if let Some(dy) = args["delta_y"].as_i64() {
                let scroll_lines = (dy as f64 / 120.0).round() as i32;
                if scroll_lines != 0 {
                    enigo.scroll(scroll_lines, enigo::Axis::Vertical)
                        .map_err(|e| anyhow::anyhow!("Failed to scroll vertically: {}", e))?;
                }
            }
            if let Some(dx) = args["delta_x"].as_i64() {
                let cols = (dx as f64 / 120.0).round() as i32;
                if cols != 0 {
                    enigo.scroll(cols, enigo::Axis::Horizontal)
                        .map_err(|e| anyhow::anyhow!("Failed to scroll horizontally: {}", e))?;
                }
            }
        }

        return Ok(json!({ "success": true, "x": x, "y": y }));
    }

    // Fallback: xdotool
    if let Some(ref xdotool) = module.xdotool_path {
        let scroll_lines = lines_arg.unwrap_or_else(|| {
            args["delta_y"].as_i64().map(|dy| (dy as f64 / 120.0).round() as i64).unwrap_or(3)
        });
        // xdotool: button 4 = scroll up, button 5 = scroll down
        let (btn, count) = if scroll_lines >= 0 {
            ("5", scroll_lines.unsigned_abs() as usize)
        } else {
            ("4", scroll_lines.unsigned_abs() as usize)
        };
        let output = std::process::Command::new(xdotool)
            .args(["mousemove", &x.to_string(), &y.to_string(),
                   "click", "--repeat", &count.to_string(), btn])
            .output()
            .map_err(|e| anyhow::anyhow!("xdotool scroll failed: {}", e))?;
        if !output.status.success() {
            return Err(anyhow::anyhow!("xdotool scroll failed: {}", String::from_utf8_lossy(&output.stderr)));
        }
        return Ok(json!({ "success": true, "x": x, "y": y, "backend": "xdotool" }));
    }

    Err(anyhow::anyhow!("No input backend available"))
}

pub async fn drag(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
    let from_x = args["from_x"].as_i64().context("Missing 'from_x'")? as i32;
    let from_y = args["from_y"].as_i64().context("Missing 'from_y'")? as i32;
    let to_x = args["to_x"].as_i64().context("Missing 'to_x'")? as i32;
    let to_y = args["to_y"].as_i64().context("Missing 'to_y'")? as i32;
    let button_str = args["button"].as_str().unwrap_or("left");
    let duration_ms = args["duration_ms"].as_u64().unwrap_or(300);

    let button = parse_button(button_str)?;

    let mut enigo = module.create_enigo()?;

    // Move to start
    enigo.move_mouse(from_x, from_y, Coordinate::Abs)
        .map_err(|e| anyhow::anyhow!("Failed to move to start: {}", e))?;

    // Mouse down
    enigo.button(button, Direction::Press)
        .map_err(|e| anyhow::anyhow!("Failed to press button: {}", e))?;

    // Interpolate movement
    let steps = 20u32;
    let step_delay = duration_ms / steps as u64;

    for i in 1..=steps {
        let t = i as f64 / steps as f64;
        let cx = from_x as f64 + (to_x - from_x) as f64 * t;
        let cy = from_y as f64 + (to_y - from_y) as f64 * t;

        enigo.move_mouse(cx as i32, cy as i32, Coordinate::Abs)
            .map_err(|e| anyhow::anyhow!("Failed to move during drag: {}", e))?;

        if step_delay > 0 {
            tokio::time::sleep(tokio::time::Duration::from_millis(step_delay)).await;
        }
    }

    // Mouse up
    enigo.button(button, Direction::Release)
        .map_err(|e| anyhow::anyhow!("Failed to release button: {}", e))?;

    Ok(json!({
        "success": true,
        "from": [from_x, from_y],
        "to": [to_x, to_y],
        "button": button_str,
        "duration_ms": duration_ms
    }))
}

// ── Key parsing ────────────────────────────────────────────────────

fn parse_button(s: &str) -> anyhow::Result<Button> {
    match s {
        "left" => Ok(Button::Left),
        "right" => Ok(Button::Right),
        "middle" => Ok(Button::Middle),
        _ => Err(anyhow::anyhow!("Unknown button '{}'. Use 'left', 'right', or 'middle'.", s)),
    }
}

fn modifier_key(name: &str) -> Option<Key> {
    match name.to_lowercase().as_str() {
        "ctrl" | "control" => Some(Key::Control),
        "shift" => Some(Key::Shift),
        "alt" => Some(Key::Alt),
        "super" | "meta" | "win" | "command" | "cmd" => Some(Key::Meta),
        _ => None,
    }
}

/// Parse a key combo string like "ctrl+shift+a" into (modifiers, main_key).
fn parse_key_combo(s: &str) -> anyhow::Result<(Vec<Key>, Key)> {
    let parts: Vec<&str> = s.split('+').map(str::trim).collect();

    if parts.is_empty() {
        return Err(anyhow::anyhow!("Empty key combination"));
    }

    let mut modifiers = Vec::new();
    let mut main_key = None;

    for (i, part) in parts.iter().enumerate() {
        if i < parts.len() - 1 {
            // Everything before the last part must be a modifier
            let mk = modifier_key(part).ok_or_else(|| {
                anyhow::anyhow!("'{}' is not a valid modifier (use ctrl, shift, alt, super)", part)
            })?;
            modifiers.push(mk);
        } else {
            // Last part is the main key (could also be a modifier used alone, e.g. "super")
            if let Some(mk) = modifier_key(part) {
                // If it's the only part, treat it as a standalone key press
                if parts.len() == 1 {
                    main_key = Some(mk);
                } else {
                    modifiers.push(mk);
                    // No main key — just modifiers pressed together
                    // Use the last modifier as the "main" key click
                    main_key = Some(mk);
                }
            } else {
                main_key = Some(parse_single_key(part)?);
            }
        }
    }

    let key = main_key.context("No key specified in combination")?;
    Ok((modifiers, key))
}

fn parse_single_key(s: &str) -> anyhow::Result<Key> {
    match s.to_lowercase().as_str() {
        "return" | "enter" => Ok(Key::Return),
        "tab" => Ok(Key::Tab),
        "escape" | "esc" => Ok(Key::Escape),
        "backspace" => Ok(Key::Backspace),
        "delete" | "del" => Ok(Key::Delete),
        "space" => Ok(Key::Space),
        "up" => Ok(Key::UpArrow),
        "down" => Ok(Key::DownArrow),
        "left" => Ok(Key::LeftArrow),
        "right" => Ok(Key::RightArrow),
        "home" => Ok(Key::Home),
        "end" => Ok(Key::End),
        "pageup" | "pgup" => Ok(Key::PageUp),
        "pagedown" | "pgdn" | "pgdown" => Ok(Key::PageDown),
        "f1" => Ok(Key::F1),
        "f2" => Ok(Key::F2),
        "f3" => Ok(Key::F3),
        "f4" => Ok(Key::F4),
        "f5" => Ok(Key::F5),
        "f6" => Ok(Key::F6),
        "f7" => Ok(Key::F7),
        "f8" => Ok(Key::F8),
        "f9" => Ok(Key::F9),
        "f10" => Ok(Key::F10),
        "f11" => Ok(Key::F11),
        "f12" => Ok(Key::F12),
        "capslock" | "caps" => Ok(Key::CapsLock),
        "insert" | "ins" => Ok(Key::Other(0xff63)),       // XK_Insert
        "printscreen" | "print" | "prtsc" | "sysrq" => Ok(Key::Other(0xff61)), // XK_Print
        "numlock" | "num_lock" => Ok(Key::Other(0xff7f)),  // XK_Num_Lock
        "scrolllock" | "scroll_lock" => Ok(Key::Other(0xff14)), // XK_Scroll_Lock
        "pause" | "break" => Ok(Key::Other(0xff13)),       // XK_Pause
        "menu" | "contextmenu" | "apps" => Ok(Key::Other(0xff67)), // XK_Menu
        other => {
            // Single character
            let chars: Vec<char> = other.chars().collect();
            if chars.len() == 1 {
                Ok(Key::Unicode(chars[0]))
            } else {
                Err(anyhow::anyhow!(
                    "Unknown key '{}'. Use named keys (Return, Tab, F1-F12, etc.) or single characters.",
                    s
                ))
            }
        }
    }
}