Skip to content

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

feat(mcp): expose agent cleanup helpers and module runtime spawn

Steven Enamakelbd615a1fd8c7
diff --git a/crates/openhuman-core/src/mcp/agent_cleanup.rs b/crates/openhuman-core/src/mcp/agent_cleanup.rs
new file mode 100644
index 0000000000..688993c59c
--- /dev/null
+++ b/crates/openhuman-core/src/mcp/agent_cleanup.rs
@@ -0,0 +1,92 @@
+//! Captured cleanup of an agent's existing configured module object.
+use super::*;
+
+/// A retired agent's original MCP owner and its retryable close receipts.
+/// Capturing this handle never creates a client or loads a module.
+#[derive(Clone)]
+pub struct AgentMcpCleanup {
+ directory: PathBuf,
+ client: Arc<McpConfiguredClient>,
+}
+
+/// Retire the existing configured client for this exact agent directory.
+/// An absent entry requires no cleanup and leaves the module loader untouched.
+pub fn take_agent_cleanup(workspace: &std::path::Path, agent_id: &str) -> Option<AgentMcpCleanup> {
+ let directory = workspace.join("agents").join(agent_id);
+ let clients = CLIENTS
+ .get()?
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let client = Arc::clone(clients.get(&directory)?);
+ client.retired.store(true, Ordering::Release);
+ Some(AgentMcpCleanup { directory, client })
+}
+
+pub(super) fn agent_is_removed() -> bool {
+ crate::core::runtime::CoreContext::current().is_some_and(|ctx| {
+ ctx.session_agent().is_some()
+ && ctx
+ .host_overrides()
+ .and_then(|overrides| overrides.approval_scope())
+ .is_some_and(|scope| scope.is_closed())
+ })
+}
+
+impl AgentMcpCleanup {
+ /// Close the original object and evict it only after confirmed cleanup.
+ /// Cancellation or error retains the same client and transition receipt.
+ pub async fn finish(&self) -> Result<(), ModuleCallError> {
+ self.client.close().await?;
+ self.evict();
+ Ok(())
+ }
+
+ /// Finish an unused client without starting an asynchronous executor.
+ /// An accepted call holding the lifecycle lock requires asynchronous drain.
+ pub fn finish_if_idle(&self) -> bool {
+ let Ok(state) = self.client.state.try_lock() else {
+ return false;
+ };
+ if !matches!(*state, State::Closed) {
+ return false;
+ }
+ self.evict();
+ true
+ }
+
+ fn evict(&self) {
+ let Some(clients) = CLIENTS.get() else {
+ return;
+ };
+ let mut clients = clients
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if clients
+ .get(&self.directory)
+ .is_some_and(|current| Arc::ptr_eq(current, &self.client))
+ {
+ clients.remove(&self.directory);
+ }
+ }
+}
+
+/// Run captured cleanup independently of the caller's Tokio runtime.
+/// This creates no configured client and loads no MCP artifact.
+pub fn spawn_agent_cleanup<F>(
+ future: F,
+) -> Result<tokio::task::JoinHandle<F::Output>, ModuleCallError>
+where
+ F: std::future::Future + Send + 'static,
+ F::Output: Send + 'static,
+{
+ #[cfg(feature = "modules")]
+ {
+ crate::modules::host::spawn_cleanup(future).map_err(|_| ModuleCallError::TransportFailed)
+ }
+ #[cfg(not(feature = "modules"))]
+ {
+ tokio::runtime::Handle::try_current()
+ .map(|handle| handle.spawn(future))
+ .map_err(|_| ModuleCallError::Unavailable)
+ }
+}
diff --git a/crates/openhuman-core/src/mcp/host.rs b/crates/openhuman-core/src/mcp/host.rs
index 306bce8e36..13928fc145 100644
--- a/crates/openhuman-core/src/mcp/host.rs
+++ b/crates/openhuman-core/src/mcp/host.rs
@@ -9,6 +9,10 @@ use std::sync::OnceLock;
use crate::config::Config;
+pub use super::module_client::agent_cleanup::{
+ spawn_agent_cleanup, take_agent_cleanup, AgentMcpCleanup,
+};
+
const PROXY_SERVICE_KEY: &str = "tool.mcp_client";
const DEFAULT_CORE_PORT: u16 = 7788;
static DEFAULT_CONFIG: OnceLock<Config> = OnceLock::new();
diff --git a/crates/openhuman-core/src/modules/host.rs b/crates/openhuman-core/src/modules/host.rs
index 96a5f99f40..57fe5ccc0c 100644
--- a/crates/openhuman-core/src/modules/host.rs
+++ b/crates/openhuman-core/src/modules/host.rs
@@ -111,6 +111,19 @@ impl ModuleRuntime {
///
/// Does not panic: a lost initialisation race reuses the winner's runtime.
pub async fn runtime() -> tinybus::Result<&'static ModuleRuntime> {
+ runtime_now()
+}
+
+/// Spawn lifecycle cleanup on the process executor, without loading an artifact.
+pub(crate) fn spawn_cleanup<F>(future: F) -> tinybus::Result<tokio::task::JoinHandle<F::Output>>
+where
+ F: std::future::Future + Send + 'static,
+ F::Output: Send + 'static,
+{
+ Ok(runtime_now()?.spawn(future))
+}
+
+fn runtime_now() -> tinybus::Result<&'static ModuleRuntime> {
if let Some(existing) = RUNTIME.get() {
return Ok(existing);
}