agentic_ssh 0.2.7

A minimalist, secure engineering primitive for agentic SSH execution loops.
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
//! GitHub Copilot integration.
//!
//! Handles registration of the agentic_ssh MCP server in both:
//! - VS Code's `settings.json` under `mcp.servers.agentic_ssh`
//! - Copilot CLI's `~/.copilot/mcp-config.json` under `mcpServers.agentic_ssh`

use std::path::Path;

use serde_json::json;

use crate::errors::Result;

use super::{
    AgentIntegration, DoctorCounters, HealthcheckContext, InstallContext, backup_and_write_json,
    backup_config_file, load_json_file, load_json_file_strict, load_jsonc_file,
    load_jsonc_file_strict, safe_write_json_file,
};

/// GitHub Copilot agent.
pub struct CopilotIntegration;

impl AgentIntegration for CopilotIntegration {
    fn name(&self) -> &'static str {
        "GitHub Copilot"
    }

    fn id(&self) -> &'static str {
        "copilot"
    }

    fn install(&self, ctx: &InstallContext) -> Result<()> {
        let vscode_settings_path = super::vscode_data_dir(&ctx.home).join("User/settings.json");
        let cli_settings_path = super::copilot_cli_dir(&ctx.home).join("mcp-config.json");

        install_vscode_mcp_server(&vscode_settings_path, &ctx.agentic_ssh_bin)?;
        let insiders_settings_path =
            super::vscode_insiders_data_dir(&ctx.home).join("User/settings.json");
        if insiders_settings_path
            .parent()
            .is_some_and(std::path::Path::exists)
        {
            install_vscode_mcp_server(&insiders_settings_path, &ctx.agentic_ssh_bin)?;
        }
        install_cli_mcp_server(&cli_settings_path, &ctx.agentic_ssh_bin)?;

        // Install prompt rules
        let vscode_instructions =
            super::vscode_data_dir(&ctx.home).join("User/prompts/copilot-instructions.md");
        install_prompt_rules(&vscode_instructions)?;
        let insiders_instructions =
            super::vscode_insiders_data_dir(&ctx.home).join("User/prompts/copilot-instructions.md");
        if super::vscode_insiders_data_dir(&ctx.home)
            .join("User")
            .exists()
        {
            install_prompt_rules(&insiders_instructions)?;
        }
        let cli_instructions = super::copilot_cli_dir(&ctx.home).join("copilot-instructions.md");
        install_prompt_rules(&cli_instructions)?;

        eprintln!();
        eprintln!("Setup complete. Next steps:");
        eprintln!("  1. Restart VS Code and/or start a new Copilot CLI session");
        eprintln!("     agentic_ssh tools are now available in GitHub Copilot");
        Ok(())
    }

    fn uninstall(&self, ctx: &InstallContext) -> Result<()> {
        let vscode_settings_path = super::vscode_data_dir(&ctx.home).join("User/settings.json");
        let cli_settings_path = super::copilot_cli_dir(&ctx.home).join("mcp-config.json");
        uninstall_vscode_mcp_server(&vscode_settings_path);
        let insiders_settings_path =
            super::vscode_insiders_data_dir(&ctx.home).join("User/settings.json");
        uninstall_vscode_mcp_server(&insiders_settings_path);
        uninstall_cli_mcp_server(&cli_settings_path);

        let vscode_instructions =
            super::vscode_data_dir(&ctx.home).join("User/prompts/copilot-instructions.md");
        uninstall_prompt_rules(&vscode_instructions);
        let insiders_instructions =
            super::vscode_insiders_data_dir(&ctx.home).join("User/prompts/copilot-instructions.md");
        uninstall_prompt_rules(&insiders_instructions);
        let cli_instructions = super::copilot_cli_dir(&ctx.home).join("copilot-instructions.md");
        uninstall_prompt_rules(&cli_instructions);

        eprintln!();
        eprintln!("Uninstall complete. AgenticSsh has been removed from GitHub Copilot.");
        eprintln!(
            "Restart VS Code and/or start a new Copilot CLI session for changes to take effect."
        );
        Ok(())
    }

    fn healthcheck(&self, dc: &mut DoctorCounters, ctx: &HealthcheckContext) {
        eprintln!("\n\x1b[1mGitHub Copilot integration\x1b[0m");
        doctor_check_vscode_settings(dc, &super::vscode_data_dir(&ctx.home), "VS Code");
        doctor_check_vscode_settings(
            dc,
            &super::vscode_insiders_data_dir(&ctx.home),
            "VS Code Insiders",
        );
        doctor_check_cli_settings(dc, &ctx.home);
    }

    fn is_detected(&self, home: &Path) -> bool {
        super::vscode_data_dir(home).join("User").is_dir()
            || super::vscode_insiders_data_dir(home).join("User").is_dir()
            || super::copilot_cli_dir(home).is_dir()
    }

    fn primary_config_path(&self, home: &Path) -> Option<std::path::PathBuf> {
        Some(super::vscode_data_dir(home).join("User/settings.json"))
    }

    fn has_agentic_ssh(&self, home: &Path) -> bool {
        let vscode_settings_path = super::vscode_data_dir(home).join("User/settings.json");
        let insiders_settings_path =
            super::vscode_insiders_data_dir(home).join("User/settings.json");
        let cli_settings_path = super::copilot_cli_dir(home).join("mcp-config.json");
        let current_bin = super::which_agentic_ssh();

        let check_vscode = |path: &Path| -> bool {
            if !path.exists() {
                return true;
            }
            let json = load_jsonc_file(path);
            if let Some(agentic_ssh) = json
                .get("mcp")
                .and_then(|v| v.get("servers"))
                .and_then(|v| v.get("agentic_ssh"))
            {
                if let Some(ref current) = current_bin {
                    let cmd = agentic_ssh
                        .get("command")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    cmd == current
                } else {
                    true
                }
            } else {
                false
            }
        };

        let check_cli = |path: &Path| -> bool {
            if !path.exists() {
                return true;
            }
            let json = load_json_file(path);
            if let Some(agentic_ssh) = json.get("mcpServers").and_then(|v| v.get("agentic_ssh")) {
                if let Some(ref current) = current_bin {
                    let cmd = agentic_ssh
                        .get("command")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    cmd == current
                } else {
                    true
                }
            } else {
                false
            }
        };

        if !vscode_settings_path.exists()
            && !insiders_settings_path.exists()
            && !cli_settings_path.exists()
        {
            return false;
        }

        check_vscode(&vscode_settings_path)
            && check_vscode(&insiders_settings_path)
            && check_cli(&cli_settings_path)
    }
}

/// Register MCP server in VS Code settings.json.
fn install_vscode_mcp_server(settings_path: &Path, agentic_ssh_bin: &str) -> Result<()> {
    if let Some(parent) = settings_path.parent() {
        std::fs::create_dir_all(parent).ok();
    }

    let backup = backup_config_file(settings_path)?;
    let mut settings = match load_jsonc_file_strict(settings_path) {
        Ok(v) => v,
        Err(e) => {
            if let Some(ref b) = backup {
                eprintln!("  Backup preserved at: {}", b.display());
            }
            return Err(e);
        }
    };
    settings["mcp"]["servers"]["agentic_ssh"] = json!({
        "type": "stdio",
        "command": agentic_ssh_bin,
        "args": ["serve"]
    });

    safe_write_json_file(settings_path, &settings, backup.as_deref())?;
    eprintln!(
        "\x1b[32m✔\x1b[0m Added agentic_ssh MCP server to {}",
        settings_path.display()
    );
    Ok(())
}

/// Register MCP server in Copilot CLI's ~/.copilot/mcp-config.json.
fn install_cli_mcp_server(settings_path: &Path, agentic_ssh_bin: &str) -> Result<()> {
    if let Some(parent) = settings_path.parent() {
        std::fs::create_dir_all(parent).ok();
    }

    let backup = backup_config_file(settings_path)?;
    let mut settings = match load_json_file_strict(settings_path) {
        Ok(v) => v,
        Err(e) => {
            if let Some(ref b) = backup {
                eprintln!("  Backup preserved at: {}", b.display());
            }
            return Err(e);
        }
    };
    settings["mcpServers"]["agentic_ssh"] = json!({
        "type": "stdio",
        "command": agentic_ssh_bin,
        "args": ["serve"]
    });

    safe_write_json_file(settings_path, &settings, backup.as_deref())?;
    eprintln!(
        "\x1b[32m✔\x1b[0m Added agentic_ssh MCP server to {}",
        settings_path.display()
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Uninstall helpers
// ---------------------------------------------------------------------------

/// Remove MCP server entry from VS Code settings.json.
/// Does not delete the file even if the object becomes empty (other VS Code
/// settings may still exist).
fn uninstall_vscode_mcp_server(settings_path: &Path) {
    if !settings_path.exists() {
        eprintln!("  {} not found, skipping", settings_path.display());
        return;
    }

    let mut settings = load_jsonc_file(settings_path);

    // Remove mcpServers.agentic_ssh
    let removed = settings
        .get_mut("mcp")
        .and_then(|mcp| mcp.get_mut("servers"))
        .and_then(|servers| servers.as_object_mut())
        .and_then(|map| map.remove("agentic_ssh"))
        .is_some();

    if !removed {
        eprintln!(
            "  No agentic_ssh MCP server in {}, skipping",
            settings_path.display()
        );
        return;
    }

    // Clean up empty "servers" object
    if let Some(mcp) = settings.get_mut("mcp") {
        let servers_empty = mcp
            .get("servers")
            .and_then(|v| v.as_object())
            .is_some_and(serde_json::Map::is_empty);
        if servers_empty {
            mcp.as_object_mut().map(|o| o.remove("servers"));
        }

        // Clean up empty "mcp" object
        let mcp_empty = settings
            .get("mcp")
            .and_then(|v| v.as_object())
            .is_some_and(serde_json::Map::is_empty);
        if mcp_empty {
            settings.as_object_mut().map(|o| o.remove("mcp"));
        }
    }

    // Always write back (never delete settings.json — it has other VS Code settings).
    // backup_and_write_json leaves a .bak so any mistake is recoverable (issue #63).
    if backup_and_write_json(settings_path, &settings) {
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed agentic_ssh MCP server from {}",
            settings_path.display()
        );
    }
}

/// Remove MCP server entry from Copilot CLI's ~/.copilot/mcp-config.json.
fn uninstall_cli_mcp_server(settings_path: &Path) {
    if !settings_path.exists() {
        return;
    }
    let Ok(contents) = std::fs::read_to_string(settings_path) else {
        return;
    };
    let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(&contents) else {
        return;
    };
    let Some(servers) = settings
        .get_mut("mcpServers")
        .and_then(|v| v.as_object_mut())
    else {
        return;
    };
    if servers.remove("agentic_ssh").is_none() {
        eprintln!(
            "  No agentic_ssh MCP server in {}, skipping",
            settings_path.display()
        );
        return;
    }
    if servers.is_empty() {
        settings.as_object_mut().map(|o| o.remove("mcpServers"));
    }
    let is_empty = settings.as_object().is_some_and(serde_json::Map::is_empty);
    if is_empty {
        std::fs::remove_file(settings_path).ok();
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed {} (was empty)",
            settings_path.display()
        );
    } else if backup_and_write_json(settings_path, &settings) {
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed agentic_ssh MCP server from {}",
            settings_path.display()
        );
    }
}

// ---------------------------------------------------------------------------
// Prompt rules helpers
// ---------------------------------------------------------------------------

/// Append prompt rules to a copilot-instructions.md file (idempotent).
fn install_prompt_rules(instructions_path: &Path) -> Result<()> {
    use std::io::Write;
    let marker = "## Prefer agentic_ssh MCP tools";
    let existing = if instructions_path.exists() {
        std::fs::read_to_string(instructions_path).unwrap_or_default()
    } else {
        String::new()
    };
    if existing.contains(marker) {
        if existing.contains("agentic_ssh_context") || existing.contains("knowledge graph") {
            uninstall_prompt_rules(instructions_path);
        } else {
            eprintln!(
                "  {} already contains agentic_ssh rules, skipping",
                instructions_path.display()
            );
            return Ok(());
        }
    }
    if let Some(parent) = instructions_path.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(instructions_path)
        .map_err(|e| crate::errors::AgenticSshError::Config {
            message: format!("failed to open {}: {e}", instructions_path.display()),
        })?;
    write!(
        f,
        "\n{marker}\n\n\
        When you need to discover, query, monitor, or execute commands on remote SSH hosts, \
        ALWAYS use the `agentic_ssh` MCP tools:\n\
        - **Discovering Hosts:** Use the `list_hosts` tool to retrieve the list of configured remote SSH hosts. Do NOT read or parse `~/.ssh/config` manually.\n\
        - **Executing Commands:** Use the `run_command` tool to run shell commands on one or more hosts concurrently.\n\
        - **Monitoring Logs:** Use `tail_log` (for files) or `tail_container_logs` (for Docker containers) to read recent logs. To verify startup, services, or events across cluster nodes without polling, use `wait_for_log_pattern` to block and stream logs until a regex pattern is matched.\n\
        - **Checking System & Network Status:** Use `get_system_stats` to fetch structured CPU, memory, and disk usage metrics. Use `list_ports` to see active listening TCP/UDP ports. Use `search_processes` to find running processes.\n\
        - **Custom Tools:** Use custom commands registered dynamically through the configuration file (e.g., `find_large_files`, `check_service_status`, `check_docker_status`).\n\n\
        These tools leverage an automatic connection pool (reusing active sessions and closing them after 5 minutes of inactivity), handle SSH key-based authentication seamlessly, and support output abbreviation to prevent token bloat.\n"
    )
    .map_err(|e| crate::errors::AgenticSshError::Config {
        message: format!("failed to write {}: {e}", instructions_path.display()),
    })?;
    eprintln!(
        "\x1b[32m✔\x1b[0m Added agentic_ssh rules to {}",
        instructions_path.display()
    );
    Ok(())
}

/// Remove agentic_ssh rules from a copilot-instructions.md file.
fn uninstall_prompt_rules(instructions_path: &Path) {
    if !instructions_path.exists() {
        return;
    }
    let Ok(contents) = std::fs::read_to_string(instructions_path) else {
        return;
    };
    if !contents.contains("agentic_ssh") {
        return;
    }
    let marker = "## Prefer agentic_ssh MCP tools";
    let Some(start) = contents.find(marker) else {
        return;
    };
    let after_marker = start + marker.len();
    let end = contents[after_marker..]
        .find("\n## ")
        .map_or(contents.len(), |pos| after_marker + pos);
    let mut new_contents = String::new();
    new_contents.push_str(contents[..start].trim_end());
    let remainder = &contents[end..];
    if !remainder.is_empty() {
        new_contents.push_str("\n\n");
        new_contents.push_str(remainder.trim_start());
    }
    let new_contents = new_contents.trim().to_string();
    if new_contents.is_empty() {
        std::fs::remove_file(instructions_path).ok();
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed {} (was empty)",
            instructions_path.display()
        );
    } else {
        std::fs::write(instructions_path, format!("{new_contents}\n")).ok();
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed agentic_ssh rules from {}",
            instructions_path.display()
        );
    }
}

// ---------------------------------------------------------------------------
// Healthcheck helpers
// ---------------------------------------------------------------------------

/// Check VS Code (or VS Code Insiders) settings.json has agentic_ssh MCP server registered.
fn doctor_check_vscode_settings(dc: &mut DoctorCounters, vscode_dir: &Path, label: &str) {
    let settings_path = vscode_dir.join("User/settings.json");

    if !settings_path.exists() {
        dc.warn(&format!(
            "{} not found — run `agentic_ssh install --agent copilot` if you use GitHub Copilot in {label}",
            settings_path.display()
        ));
        return;
    }

    let settings = load_jsonc_file(&settings_path);
    let server = settings
        .get("mcp")
        .and_then(|v| v.get("servers"))
        .and_then(|v| v.get("agentic_ssh"));

    let Some(server) = server.and_then(|v| v.as_object()) else {
        dc.fail(&format!(
            "MCP server NOT registered in {} — run `agentic_ssh install --agent copilot`",
            settings_path.display()
        ));
        return;
    };
    dc.pass(&format!(
        "MCP server registered in {}",
        settings_path.display()
    ));

    // Check args include "serve"
    let has_serve = server
        .get("args")
        .and_then(|v| v.as_array())
        .is_some_and(|arr| arr.iter().any(|v| v.as_str() == Some("serve")));
    if has_serve {
        dc.pass("MCP server args include \"serve\"");
    } else {
        dc.fail("MCP server args missing \"serve\" — run `agentic_ssh install --agent copilot`");
    }
}

/// Check Copilot CLI mcp-config.json has agentic_ssh MCP server registered.
fn doctor_check_cli_settings(dc: &mut DoctorCounters, home: &Path) {
    let settings_path = super::copilot_cli_dir(home).join("mcp-config.json");

    if !settings_path.exists() {
        dc.warn(&format!(
            "{} not found — run `agentic_ssh install --agent copilot` if you use Copilot CLI",
            settings_path.display()
        ));
        return;
    }

    let settings = load_json_file(&settings_path);
    let server = settings
        .get("mcpServers")
        .and_then(|v| v.get("agentic_ssh"));

    let Some(server) = server.and_then(|v| v.as_object()) else {
        dc.fail(&format!(
            "MCP server NOT registered in {} — run `agentic_ssh install --agent copilot`",
            settings_path.display()
        ));
        return;
    };
    dc.pass(&format!(
        "MCP server registered in {}",
        settings_path.display()
    ));

    let has_serve = server
        .get("args")
        .and_then(|v| v.as_array())
        .is_some_and(|arr| arr.iter().any(|v| v.as_str() == Some("serve")));
    if has_serve {
        dc.pass("MCP server args include \"serve\"");
    } else {
        dc.fail("MCP server args missing \"serve\" — run `agentic_ssh install --agent copilot`");
    }
}