#[cfg(any(unix, windows))]
use std::future::Future;
use adk_core::AdkError;
#[cfg(any(unix, windows))]
use rmcp::RoleClient;
#[cfg(any(unix, windows))]
use rmcp::service::{RxJsonRpcMessage, TxJsonRpcMessage};
#[cfg(not(unix))]
use rmcp::transport::TokioChildProcess;
#[cfg(any(unix, windows))]
use rmcp::transport::Transport;
#[cfg(windows)]
use adk_sandbox::process_tree::JobObject;
#[cfg(unix)]
use adk_sandbox::process_tree::ProcessGroup;
#[cfg(windows)]
pub(super) type ServerTransport = JobTransport;
#[cfg(unix)]
pub(super) type ServerTransport = GroupTransport;
#[cfg(not(any(unix, windows)))]
pub(super) type ServerTransport = TokioChildProcess;
fn not_spawned(id: &str, program: &std::ffi::OsStr, error: std::io::Error) -> AdkError {
let program = program.to_string_lossy();
AdkError::tool(format!(
"failed to spawn server '{id}': command '{program}' not found. Verify it is installed and on PATH: {error}"
))
}
#[cfg(any(unix, windows))]
fn note_termination(result: std::io::Result<bool>, wait: std::time::Duration) {
match result {
Ok(true) => {}
Ok(false) => tracing::warn!(
wait = ?wait,
"a process of the MCP server had not exited when its transport closed"
),
Err(error) => {
tracing::warn!(error = %error, "could not wait for the MCP server's processes to exit")
}
}
}
#[cfg(windows)]
pub(super) fn spawn(
id: &str,
mut command: tokio::process::Command,
) -> adk_core::Result<ServerTransport> {
command.creation_flags(adk_sandbox::process_tree::CREATE_SUSPENDED);
let program = command.as_std().get_program().to_os_string();
let transport =
TokioChildProcess::new(command).map_err(|error| not_spawned(id, &program, error))?;
JobTransport::contain(transport).map_err(|error| {
AdkError::tool(format!(
"MCP server '{id}' could not be placed in a Job Object, which stops the processes \
it starts, so it was not started: {error}"
))
})
}
#[cfg(unix)]
pub(super) fn spawn(
id: &str,
mut command: tokio::process::Command,
) -> adk_core::Result<ServerTransport> {
use std::process::Stdio;
command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit());
ProcessGroup::new_session(&mut command);
let mut child =
command.spawn().map_err(|error| not_spawned(id, command.as_std().get_program(), error))?;
let pipes = (child.stdout.take(), child.stdin.take());
let group = ProcessGroup::contain(child).map_err(|error| {
AdkError::tool(format!(
"MCP server '{id}' could not be held in a process group of its own, which stops \
the processes it starts, so it was not started: {error}"
))
})?;
let (Some(stdout), Some(stdin)) = pipes else {
return Err(AdkError::tool(format!(
"MCP server '{id}' started without piped standard input and output"
)));
};
Ok(GroupTransport {
transport: rmcp::transport::async_rw::AsyncRwTransport::new_client(stdout, stdin),
group,
})
}
#[cfg(not(any(unix, windows)))]
pub(super) fn spawn(
id: &str,
command: tokio::process::Command,
) -> adk_core::Result<ServerTransport> {
let program = command.as_std().get_program().to_os_string();
TokioChildProcess::new(command).map_err(|error| not_spawned(id, &program, error))
}
#[cfg(windows)]
pub(super) struct JobTransport {
transport: TokioChildProcess,
job: JobObject,
}
#[cfg(windows)]
impl JobTransport {
fn contain(transport: TokioChildProcess) -> std::io::Result<Self> {
let pid = transport
.id()
.ok_or_else(|| std::io::Error::other("the server exited before it was started"))?;
let job = JobObject::contain_suspended(pid)?;
Ok(Self { transport, job })
}
}
#[cfg(windows)]
impl Drop for JobTransport {
fn drop(&mut self) {
note_termination(
self.job.terminate_and_wait(JobObject::TERMINATION_WAIT),
JobObject::TERMINATION_WAIT,
);
}
}
#[cfg(windows)]
impl Transport<RoleClient> for JobTransport {
type Error = std::io::Error;
fn send(
&mut self,
item: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
self.transport.send(item)
}
fn receive(&mut self) -> impl Future<Output = Option<RxJsonRpcMessage<RoleClient>>> + Send {
self.transport.receive()
}
fn close(&mut self) -> impl Future<Output = Result<(), Self::Error>> + Send {
self.transport.close()
}
}
#[cfg(unix)]
const EXIT_AFTER_INPUT_CLOSES: std::time::Duration = std::time::Duration::from_secs(3);
#[cfg(unix)]
pub(super) struct GroupTransport {
transport: rmcp::transport::async_rw::AsyncRwTransport<
RoleClient,
tokio::process::ChildStdout,
tokio::process::ChildStdin,
>,
group: ProcessGroup,
}
#[cfg(unix)]
impl Drop for GroupTransport {
fn drop(&mut self) {
note_termination(
self.group.terminate_and_wait(ProcessGroup::TERMINATION_WAIT),
ProcessGroup::TERMINATION_WAIT,
);
}
}
#[cfg(unix)]
impl Transport<RoleClient> for GroupTransport {
type Error = std::io::Error;
fn send(
&mut self,
item: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
self.transport.send(item)
}
fn receive(&mut self) -> impl Future<Output = Option<RxJsonRpcMessage<RoleClient>>> + Send {
self.transport.receive()
}
async fn close(&mut self) -> Result<(), Self::Error> {
let closed = self.transport.close().await;
if let Err(error) = self.group.wait_for_leader(EXIT_AFTER_INPUT_CLOSES).await {
tracing::warn!(error = %error, "could not wait for the MCP server to exit");
}
note_termination(
self.group.terminate_and_wait_async(ProcessGroup::TERMINATION_WAIT).await,
ProcessGroup::TERMINATION_WAIT,
);
closed
}
}