use std::io;
use std::process::{Child, ExitStatus};
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::time::{Duration, Instant};
use anyhow::{Context as _, Result, bail};
#[cfg(not(unix))]
mod other;
#[cfg(unix)]
mod unix;
#[cfg(not(unix))]
use other as platform;
#[cfg(unix)]
use unix as platform;
pub(super) use platform::own;
const GRACE: Duration = Duration::from_secs(5);
const TERM_GRACE: Duration = Duration::from_secs(5);
pub(super) enum Pump {
Host,
Server(Result<()>),
}
pub(super) fn supervise(
mut child: Child,
finished: &Receiver<Pump>,
note: fn(&str),
) -> Result<bool> {
let ended = drain(finished, GRACE).and_then(|()| match wait(&mut child, GRACE)? {
Some(status) => Ok(status),
None => bail!("the MCP server did not exit after closing its output"),
});
match ended {
Ok(status) => Ok(status.success()),
Err(why) => {
note(&format!("{why:#}; stopping it"));
stop(&mut child, TERM_GRACE)?;
Ok(false)
}
}
}
fn drain(finished: &Receiver<Pump>, grace: Duration) -> Result<()> {
let mut next = finished
.recv()
.context("the MCP relay stopped without reporting its result")?;
loop {
if let Pump::Server(result) = next {
return result;
}
next = match finished.recv_timeout(grace) {
Ok(event) => event,
Err(RecvTimeoutError::Timeout) => {
bail!("the MCP server did not close its output after the agent closed its input")
}
Err(error) => {
return Err(error)
.context("the MCP server's side stopped without reporting its result");
}
};
}
}
fn wait(child: &mut Child, within: Duration) -> Result<Option<ExitStatus>> {
let deadline = Instant::now() + within;
loop {
match child.try_wait() {
Ok(Some(status)) => return Ok(Some(status)),
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
Ok(None) => return Ok(None),
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error).context("waiting for the MCP server"),
}
}
}
fn stop(child: &mut Child, grace: Duration) -> Result<ExitStatus> {
platform::terminate(child);
if let Some(status) = wait(child, grace)? {
return Ok(status);
}
platform::kill(child);
child.wait().context("reaping the stopped MCP server")
}
#[cfg(all(test, unix))]
mod tests;