Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(mcp): await agent MCP cleanup before purging workspaces

Steven Enamakelbcaaca371b95
diff --git a/crates/openhuman-core/src/mcp/host.rs b/crates/openhuman-core/src/mcp/host.rs
index 306bce8e36..e2cd644271 100644
--- a/crates/openhuman-core/src/mcp/host.rs
+++ b/crates/openhuman-core/src/mcp/host.rs
@@ -30,6 +30,36 @@ pub fn ambient_config() -> Option<Config> {
}
}
+/// Closes an already-cached agent-scoped MCP client and returns only after the
+/// module acknowledges cleanup. A failed close remains unavailable in the
+/// cache so a later retry or runtime shutdown can finish it.
+#[cfg(feature = "mcp")]
+pub async fn close_agent(workspace_dir: &std::path::Path, agent_id: &str) -> bool {
+ crate::mcp::module_client::McpConfiguredClient::close_agent_data_dir(
+ &workspace_dir.join("agents").join(agent_id),
+ )
+ .await
+}
+
+/// Schedules cleanup for a dropped agent without opening a client. The exact
+/// cached client is marked retired before the cleanup task is spawned.
+#[cfg(feature = "mcp")]
+pub fn schedule_agent_close(workspace_dir: &std::path::Path, agent_id: &str) {
+ crate::mcp::module_client::McpConfiguredClient::schedule_agent_close_data_dir(
+ &workspace_dir.join("agents").join(agent_id),
+ );
+}
+
+/// The MCP feature is disabled, so there is no configured client to close.
+#[cfg(not(feature = "mcp"))]
+pub async fn close_agent(_workspace_dir: &std::path::Path, _agent_id: &str) -> bool {
+ true
+}
+
+/// The MCP feature is disabled, so there is no configured client to close.
+#[cfg(not(feature = "mcp"))]
+pub fn schedule_agent_close(_workspace_dir: &std::path::Path, _agent_id: &str) {}
+
/// Converts the MCP section of product configuration to the module contract.
pub fn client_config(config: &Config) -> tinymcp_bus::McpClientConfig {
let mut client = tinymcp_bus::McpClientConfig {
diff --git a/crates/openhuman-core/src/mcp/module_client.rs b/crates/openhuman-core/src/mcp/module_client.rs
index f3e418bb68..f68394c6ac 100644
--- a/crates/openhuman-core/src/mcp/module_client.rs
+++ b/crates/openhuman-core/src/mcp/module_client.rs
@@ -286,7 +286,7 @@ impl McpConfiguredClient {
limit: usize,
) -> Result<Option<SupervisorBatch>, ModuleCallError> {
let state = self.state.lock().await;
- if SHUTTING_DOWN.load(Ordering::Acquire) {
+ if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {
return Err(ModuleCallError::Unavailable);
}
let State::Open(object) = &*state else {
@@ -328,7 +328,9 @@ impl McpConfiguredClient {
})
.unwrap_or_default();
for client in clients {
- if let Err(error) = client.close().await {
+ if client.retiring.load(Ordering::Acquire) {
+ Self::close_retired_client(PathBuf::from(&client.data_dir), client).await;
+ } else if let Err(error) = client.close().await {
tracing::warn!(?error, "[mcp] workspace cleanup is still pending");
}
}
diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rs
index 13ea47e015..8d35fa7bfc 100644
--- a/crates/openhuman-embed/src/agent/mod.rs
+++ b/crates/openhuman-embed/src/agent/mod.rs
@@ -76,6 +76,11 @@ pub enum AgentError {
source: std::io::Error,
},
+ /// A module-owned agent resource did not acknowledge cleanup, so its
+ /// workspace could not be purged safely.
+ #[error("agent cleanup is still pending; its workspace was retained")]
+ CleanupPending,
+
/// A spec input could not be honoured.
#[error("{0}")]
Invalid(String),
@@ -139,8 +144,8 @@ pub(crate) struct AgentInner {
impl AgentInner {
/// Releases what the core keeps for this agent: parked approvals are
- /// denied with `resolution`, its state slots and MCP host are dropped,
- /// and its context leaves the registry. Runs once.
+ /// denied with `resolution`, its state slots are cleared, cached MCP
+ /// cleanup is scheduled, and its context leaves the registry. Runs once.
pub(crate) fn teardown(&self, resolution: &str) {
if !self.lifecycle.begin_teardown() {
return;
@@ -153,14 +158,7 @@ impl AgentInner {
);
self.deny_approvals(resolution);
self.ctx.agent_state().clear();
- if openhuman_core::mcp::host::take_agent_host(&self.config.workspace_dir, &self.id)
- .is_some()
- {
- log::debug!(
- "[embed][agent] teardown id={} evicted its MCP host",
- self.id
- );
- }
+ openhuman_core::mcp::host::schedule_agent_close(&self.config.workspace_dir, &self.id);
openhuman_core::core::runtime::AgentContextRegistry::deregister(&self.id, &self.ctx);
log::debug!("[embed][agent] teardown complete id={}", self.id);
}
diff --git a/crates/openhuman-embed/src/runtime/lifecycle.rs b/crates/openhuman-embed/src/runtime/lifecycle.rs
index 13587a4c90..40af66e66e 100644
--- a/crates/openhuman-embed/src/runtime/lifecycle.rs
+++ b/crates/openhuman-embed/src/runtime/lifecycle.rs
@@ -17,6 +17,7 @@ struct RemovalSlot<'a> {
runtime: &'a Runtime,
inner: Arc<crate::agent::AgentInner>,
purge: bool,
+ mcp_cleanup_confirmed: bool,
}
impl RemovalSlot<'_> {
@@ -24,6 +25,9 @@ impl RemovalSlot<'_> {
if !std::mem::take(&mut self.purge) {
return Ok(());
}
+ if !self.mcp_cleanup_confirmed {
+ return Err(AgentError::CleanupPending);
+ }
let home = &self.inner.layout.home;
if home.exists() {
std::fs::remove_dir_all(home).map_err(|source| AgentError::Workspace {
@@ -38,6 +42,12 @@ impl RemovalSlot<'_> {
impl Drop for RemovalSlot<'_> {
fn drop(&mut self) {
self.inner.teardown("agent_removed");
+ if self.purge && !self.mcp_cleanup_confirmed {
+ self.purge = false;
+ log::warn!(
+ "[embed][runtime] retaining agent home until MCP cleanup is acknowledged"
+ );
+ }
if let Err(error) = self.purge_home() {
log::warn!("[embed][runtime] cancelled removal purge failed: {error}");
}
@@ -90,8 +100,9 @@ impl Runtime {
/// [`CoreError::AgentRemoved`](crate::CoreError::AgentRemoved); its parked
/// approvals are denied with resolution `agent_removed`; turns in
/// flight end with the same error, waited on for up to ten seconds; its
- /// state slots and MCP host are dropped and its context deregistered, so
- /// its cron jobs stay dormant. The id is free for reuse once cleanup ends.
+ /// state slots are cleared and its configured MCP client is closed before
+ /// its context is deregistered, so its cron jobs stay dormant. The id is
+ /// free for reuse once cleanup ends.
/// Cancelling an already-started removal still tears down the old instance
/// and performs a requested purge before releasing its id.
///
@@ -123,6 +134,7 @@ impl Runtime {
runtime: self,
inner,
purge,
+ mcp_cleanup_confirmed: false,
};
let inner = &removal.inner;
log::debug!("[embed][runtime] removing agent id={id} purge={purge}");
@@ -132,6 +144,12 @@ impl Runtime {
REMOVE_IDLE_WAIT.as_secs()
);
}
+ removal.mcp_cleanup_confirmed =
+ openhuman_core::mcp::host::close_agent(&inner.config.workspace_dir, &inner.id).await;
+ if !removal.mcp_cleanup_confirmed && removal.purge {
+ removal.purge = false;
+ return Err(AgentError::CleanupPending);
+ }
inner.teardown("agent_removed");
removal.purge_home()?;
log::debug!("[embed][runtime] agent removed id={id}");