use std::{
env,
ffi::{OsStr, OsString},
io,
path::Path,
process::{Command, Stdio},
};
use anyhow::{Context, bail};
use super::MCP_NAME;
pub(super) const CLAUDE_VAR: &str = "ALLOT_CLAUDE";
pub(super) fn add(exe: &Path, replace: bool) -> anyhow::Result<bool> {
if replace && !remove(MCP_NAME)? {
return Ok(false);
}
claude(&[
"mcp".as_ref(),
"add".as_ref(),
"--scope".as_ref(),
"user".as_ref(),
MCP_NAME.as_ref(),
"--".as_ref(),
exe.as_os_str(),
])
}
pub(super) fn remove(name: &str) -> anyhow::Result<bool> {
claude(&[
"mcp".as_ref(),
"remove".as_ref(),
"--scope".as_ref(),
"user".as_ref(),
name.as_ref(),
])
}
fn claude(args: &[&OsStr]) -> anyhow::Result<bool> {
let programs: Vec<OsString> = match env::var_os(CLAUDE_VAR) {
Some(program) => vec![program],
None => vec!["claude".into(), "claude.cmd".into()],
};
let shown = args
.iter()
.map(|arg| arg.to_string_lossy())
.collect::<Vec<_>>()
.join(" ");
for program in programs {
let output = match Command::new(&program)
.args(args)
.stdin(Stdio::null())
.output()
{
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
result => result.with_context(|| format!("running claude {shown}"))?,
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let reason = if stderr.trim().is_empty() {
stdout
} else {
stderr
};
bail!("claude {shown} failed: {}", reason.trim());
}
return Ok(true);
}
Ok(false)
}