The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(mcp): route registry client calls through module bus
Steven Enamakel7dc6908836b7
diff --git a/crates/openhuman-core/src/mcp/mod.rs b/crates/openhuman-core/src/mcp/mod.rsindex 19d9dc6da5..72d75e0426 100644--- a/crates/openhuman-core/src/mcp/mod.rs+++ b/crates/openhuman-core/src/mcp/mod.rs@@ -62,11 +62,17 @@pub fn start(config: &crate::config::Config) {registry::bus::init();+ #[cfg(feature = "modules")]+ module_client::McpConfiguredClient::register_shutdown_hook();+if let Err(error) = host::init(config) {log::warn!("[mcp] the service could not be opened; continuing without it: {error}");}}+#[cfg(feature = "mcp")]+pub(crate) mod module_client;+/// Brings this domain up — the build without it, where there is nothing to do.#[cfg(not(feature = "mcp"))]pub fn start(_config: &crate::config::Config) {}@@ -102,25 +108,46 @@ pub fn start_boot_jobs(config: &crate::config::Config) {/// Lists every configured server and rewrites its cached tools.#[cfg(feature = "mcp")]pub(crate) async fn refresh_configured_tool_cache(config: &crate::config::Config) {- let registry = host::static_registry(config);- if registry.is_empty() {- return;- }- let service = match host::for_config(config) {- Ok(service) => service,+ let client = match module_client::McpConfiguredClient::for_config(config) {+ Ok(client) => client,+ Err(error) => {+ tracing::debug!(+ ?error,+ "[mcp] no module; configured tool cache not refreshed"+ );+ return;+ }+ };+ let client_config = host::client_config(config);+ let servers: Vec<String> = match client+ .call(&client_config, tinymcp_bus::names::methods::STATIC_LIST, ())+ .await+ {+ Ok(servers) => servers,Err(error) => {- tracing::debug!(?error, "[mcp] no host; configured tool cache not refreshed");+ tracing::debug!(?error, "[mcp] static server list unavailable");return;}};- for (server, outcome) in registry.refresh_tool_cache(service.dynamic().store()).await {+ for server in servers {+ let outcome: Result<Vec<tinymcp_bus::McpRemoteTool>, _> = client+ .call(+ &client_config,+ tinymcp_bus::names::methods::STATIC_LIST_TOOLS,+ (server.clone(),),+ )+ .await;match outcome {- Ok(count) => {- tracing::debug!(server = %server, tools = count, "[mcp] refreshed configured tool cache")- }- Err(error) => {- tracing::debug!(server = %server, "[mcp] configured tool cache not refreshed: {error}")- }+ Ok(tools) => tracing::debug!(+ server = %server,+ tools = tools.len(),+ "[mcp] refreshed configured tool cache"+ ),+ Err(error) => tracing::debug!(+ server = %server,+ ?error,+ "[mcp] configured tool cache not refreshed"+ ),}}}diff --git a/crates/openhuman-core/src/mcp/module_client.rs b/crates/openhuman-core/src/mcp/module_client.rsnew file mode 100644index 0000000000..df7abba1c4--- /dev/null+++ b/crates/openhuman-core/src/mcp/module_client.rs@@ -0,0 +1,462 @@+//! Serialized access to one TinyMCP object owned by a workspace.+//!+//! `OpenConfigured` carries credentials, so the root lifecycle calls always+//! use TinyBus confidential delivery. The returned child object path remains+//! private to this adapter. Its state machine retains open and close receipts+//! before polling, which lets a later call resume cleanup after its caller was+//! cancelled or lost a reply.++use std::time::Duration;+use std::{+ collections::HashMap,+ path::PathBuf,+ sync::{+ atomic::{AtomicBool, Ordering},+ Arc, Mutex, OnceLock,+ },+};++use async_trait::async_trait;+use serde::{de::DeserializeOwned, Serialize};+use serde_json::Value;+use tinymcp_bus::{+ config::{McpClientConfig, OpenConfiguredRequest, OpenConfiguredResponse, TransitionStatus},+ names,+};++use crate::{+ config::Config,+ modules::{client::ModuleCallError, client::ModuleClient},+};++const MODULE: &str = "tinymcp";+const TRANSITION_TIMEOUT: Duration = Duration::from_secs(30);+const TRANSITION_POLL_INTERVAL: Duration = Duration::from_millis(20);+static CLIENTS: OnceLock<Mutex<HashMap<PathBuf, Arc<McpConfiguredClient>>>> = OnceLock::new();+static SHUTDOWN_REGISTERED: AtomicBool = AtomicBool::new(false);++#[derive(Clone)]+struct OpenObject {+ config: McpClientConfig,+ object_path: String,+}++#[derive(Clone)]+enum State {+ Closed,+ StartingOpen {+ config: McpClientConfig,+ previous: Option<OpenObject>,+ },+ Opening {+ config: McpClientConfig,+ previous: Option<OpenObject>,+ receipt: OpenConfiguredResponse,+ },+ Open(OpenObject),+ StartingClose(OpenObject),+ Closing {+ object: OpenObject,+ transition_id: String,+ },+}++#[async_trait]+pub(crate) trait McpModulePort: Send + Sync {+ async fn open_configured(+ &self,+ data_dir: &str,+ config: &McpClientConfig,+ ) -> Result<OpenConfiguredResponse, ModuleCallError>;++ async fn close(&self, data_dir: &str) -> Result<Option<String>, ModuleCallError>;++ async fn transition_status(+ &self,+ transition_id: &str,+ ) -> Result<TransitionStatus, ModuleCallError>;++ async fn call_object(+ &self,+ object_path: &str,+ member: &str,+ args: Value,+ confidential: bool,+ ) -> Result<Value, ModuleCallError>;+}++struct TinyMcpPort {+ root: ModuleClient,+}++#[async_trait]+impl McpModulePort for TinyMcpPort {+ async fn open_configured(+ &self,+ data_dir: &str,+ config: &McpClientConfig,+ ) -> Result<OpenConfiguredResponse, ModuleCallError> {+ self.root+ .call_confidential(+ MODULE,+ names::methods::OPEN_CONFIGURED,+ (OpenConfiguredRequest {+ data_dir: data_dir.to_owned(),+ client: config.clone(),+ },),+ )+ .await+ }++ async fn close(&self, data_dir: &str) -> Result<Option<String>, ModuleCallError> {+ self.root+ .call(MODULE, names::methods::CLOSE, (data_dir.to_owned(),))+ .await+ }++ async fn transition_status(+ &self,+ transition_id: &str,+ ) -> Result<TransitionStatus, ModuleCallError> {+ self.root+ .call(+ MODULE,+ names::methods::TRANSITION_STATUS,+ (transition_id.to_owned(),),+ )+ .await+ }++ async fn call_object(+ &self,+ object_path: &str,+ member: &str,+ args: Value,+ confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ #[cfg(feature = "modules")]+ {+ let object = self.root.object_client(MODULE, object_path).await?;+ if confidential {+ object.call_confidential(member, args).await+ } else {+ object.call(member, args).await+ }+ }+ #[cfg(not(feature = "modules"))]+ {+ let _ = (object_path, member, args, confidential);+ Err(ModuleCallError::Unavailable)+ }+ }+}++/// One workspace's serialized TinyMCP lifecycle and private object proxy.+pub(crate) struct McpConfiguredClient {+ data_dir: String,+ port: Box<dyn McpModulePort>,+ state: tokio::sync::Mutex<State>,+}++impl McpConfiguredClient {+ /// The process-owned configured object for this workspace. Entries remain+ /// reachable until `close` confirms cleanup; workspace/config switching is+ /// serialized by the client itself.+ pub(crate) fn for_config(config: &Config) -> Result<Arc<Self>, ModuleCallError> {+ let data_dir = crate::core::runtime::agent_scope_dir(config);+ let clients = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));+ let mut clients = clients+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some(client) = clients.get(&data_dir) {+ return Ok(Arc::clone(client));+ }+ let client = Arc::new(Self::new(&data_dir, config)?);+ clients.insert(data_dir, Arc::clone(&client));+ Ok(client)+ }++ /// Register this runtime's cleanup. The flag is reset by the drained hook,+ /// so a later embedded-runtime start can register a fresh one.+ pub(crate) fn register_shutdown_hook() {+ if SHUTDOWN_REGISTERED.swap(true, Ordering::AcqRel) {+ return;+ }+ crate::core::shutdown::register(|| async {+ let clients = CLIENTS+ .get()+ .map(|clients| {+ clients+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .values()+ .cloned()+ .collect::<Vec<_>>()+ })+ .unwrap_or_default();+ for client in clients {+ if let Err(error) = client.close().await {+ tracing::warn!(?error, "[mcp] workspace cleanup is still pending");+ }+ }+ SHUTDOWN_REGISTERED.store(false, Ordering::Release);+ });+ }++ pub(crate) fn new(+ data_dir: &std::path::Path,+ config: &Config,+ ) -> Result<Self, ModuleCallError> {+ let data_dir = data_dir+ .to_str()+ .ok_or(ModuleCallError::IncompatibleContract)?+ .to_owned();+ Ok(Self::with_port(+ data_dir,+ Box::new(TinyMcpPort {+ root: ModuleClient::new(config.clone()),+ }),+ ))+ }++ #[cfg(test)]+ pub(crate) fn install_test_port(+ config: &Config,+ port: Box<dyn McpModulePort>,+ ) -> Result<Arc<Self>, ModuleCallError> {+ let data_dir = crate::core::runtime::agent_scope_dir(config);+ let client = Arc::new(Self::with_port(+ data_dir+ .to_str()+ .ok_or(ModuleCallError::IncompatibleContract)?+ .to_owned(),+ port,+ ));+ let clients = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));+ clients+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(data_dir, Arc::clone(&client));+ Ok(client)+ }++ fn with_port(data_dir: String, port: Box<dyn McpModulePort>) -> Self {+ Self {+ data_dir,+ port,+ state: tokio::sync::Mutex::new(State::Closed),+ }+ }++ /// Calls one member on this workspace's private configured object.+ pub(crate) async fn call<R: DeserializeOwned>(+ &self,+ config: &McpClientConfig,+ member: &str,+ args: impl Serialize,+ ) -> Result<R, ModuleCallError> {+ self.call_inner(config, member, args, false).await+ }++ /// Calls a member that accepts credentials or other sensitive values.+ pub(crate) async fn call_confidential<R: DeserializeOwned>(+ &self,+ config: &McpClientConfig,+ member: &str,+ args: impl Serialize,+ ) -> Result<R, ModuleCallError> {+ self.call_inner(config, member, args, true).await+ }++ async fn call_inner<R: DeserializeOwned>(+ &self,+ config: &McpClientConfig,+ member: &str,+ args: impl Serialize,+ confidential: bool,+ ) -> Result<R, ModuleCallError> {+ let args = serde_json::to_value(args).map_err(|_| ModuleCallError::ModuleFault)?;+ let mut state = self.state.lock().await;+ let object = self.ensure_open(&mut state, config).await?;+ let reply = self+ .port+ .call_object(&object.object_path, member, args, confidential)+ .await?;+ serde_json::from_value(reply).map_err(|_| {+ ModuleClient::report_malformed_reply(MODULE);+ ModuleCallError::ModuleFault+ })+ }++ /// Closes this workspace and returns only after TinyMCP confirms that its+ /// transports and child object are gone. A cancelled/lost response is+ /// retried from the retained transition state on the next call.+ pub(crate) async fn close(&self) -> Result<(), ModuleCallError> {+ let mut state = self.state.lock().await;+ match state.clone() {+ State::Closed => return Ok(()),+ State::Open(object) => *state = State::StartingClose(object),+ State::StartingOpen { .. } | State::Opening { .. } => {+ self.finish_open(&mut state).await?;+ if let State::Open(object) = state.clone() {+ *state = State::StartingClose(object);+ }+ }+ State::StartingClose(_) | State::Closing { .. } => {}+ }+ self.finish_close(&mut state).await+ }++ async fn ensure_open(+ &self,+ state: &mut State,+ requested: &McpClientConfig,+ ) -> Result<OpenObject, ModuleCallError> {+ loop {+ match state.clone() {+ State::Open(object) if object.config == *requested => return Ok(object),+ State::Open(object) => {+ *state = State::StartingOpen {+ config: requested.clone(),+ previous: Some(object),+ };+ }+ State::Closed => {+ *state = State::StartingOpen {+ config: requested.clone(),+ previous: None,+ };+ }+ State::StartingOpen { .. } | State::Opening { .. } => {+ self.finish_open(state).await?;+ }+ State::StartingClose(_) | State::Closing { .. } => {+ self.finish_close(state).await?;+ }+ }+ }+ }++ async fn finish_open(&self, state: &mut State) -> Result<(), ModuleCallError> {+ let mut retried_terminal_transition = false;+ loop {+ match state.clone() {+ State::StartingOpen { config, previous } => {+ // Record intent before awaiting the confidential call. If+ // the caller is cancelled after TinyMCP accepts it, retrying+ // this same configuration recovers the idempotent receipt.+ match self.port.open_configured(&self.data_dir, &config).await {+ Ok(receipt) => {+ *state = State::Opening {+ config,+ previous,+ receipt,+ };+ }+ Err(error) => {+ *state = previous.map_or(State::Closed, State::Open);+ return Err(error);+ }+ }+ }+ State::Opening {+ config,+ previous,+ receipt,+ } => {+ let status = self.poll_transition(&receipt.transition_id).await?;+ match status {+ TransitionStatus::Pending => continue,+ TransitionStatus::Complete => {+ *state = State::Open(OpenObject {+ config,+ object_path: receipt.object_path,+ });+ return Ok(());+ }+ TransitionStatus::Failed | TransitionStatus::Unknown => {+ if retried_terminal_transition {+ return Err(ModuleCallError::TransportFailed);+ }+ retried_terminal_transition = true;+ *state = State::StartingOpen { config, previous };+ }+ _ => return Err(ModuleCallError::ModuleFault),+ }+ }+ State::Open(_) | State::Closed => return Ok(()),+ State::StartingClose(_) | State::Closing { .. } => {+ return Err(ModuleCallError::TransportFailed);+ }+ }+ }+ }++ async fn finish_close(&self, state: &mut State) -> Result<(), ModuleCallError> {+ let mut retried_terminal_transition = false;+ loop {+ match state.clone() {+ State::Closed => return Ok(()),+ State::StartingClose(object) => {+ // The module returns the same pending receipt if a previous+ // Close reply was lost. `None` means cleanup already ended.+ match self.port.close(&self.data_dir).await {+ Ok(Some(transition_id)) => {+ *state = State::Closing {+ object,+ transition_id,+ };+ }+ Ok(None) => {+ *state = State::Closed;+ return Ok(());+ }+ Err(error) => return Err(error),+ }+ }+ State::Closing {+ object,+ transition_id,+ } => match self.poll_transition(&transition_id).await? {+ TransitionStatus::Pending => continue,+ TransitionStatus::Complete => {+ *state = State::Closed;+ return Ok(());+ }+ TransitionStatus::Failed | TransitionStatus::Unknown => {+ if retried_terminal_transition {+ return Err(ModuleCallError::TransportFailed);+ }+ retried_terminal_transition = true;+ *state = State::StartingClose(object);+ }+ _ => return Err(ModuleCallError::ModuleFault),+ },+ State::Open(object) => *state = State::StartingClose(object),+ State::StartingOpen { .. } | State::Opening { .. } => {+ return Err(ModuleCallError::TransportFailed);+ }+ }+ }+ }++ async fn poll_transition(+ &self,+ transition_id: &str,+ ) -> Result<TransitionStatus, ModuleCallError> {+ tokio::time::timeout(TRANSITION_TIMEOUT, async {+ loop {+ match self.port.transition_status(transition_id).await? {+ TransitionStatus::Pending => tokio::time::sleep(TRANSITION_POLL_INTERVAL).await,+ status => return Ok(status),+ }+ }+ })+ .await+ .map_err(|_| ModuleCallError::TransportFailed)?+ }+}++#[cfg(test)]+#[path = "module_client_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/mcp/module_client_tests.rs b/crates/openhuman-core/src/mcp/module_client_tests.rsnew file mode 100644index 0000000000..963227f742--- /dev/null+++ b/crates/openhuman-core/src/mcp/module_client_tests.rs@@ -0,0 +1,257 @@+use super::*;+use std::sync::{Arc, Mutex};+use tokio::sync::Notify;++#[derive(Clone, Default)]+struct FakePort {+ opened: Arc<Mutex<Vec<(String, McpClientConfig)>>>,+ closed: Arc<Mutex<Vec<String>>>,+ calls: Arc<Mutex<Vec<(String, String, Value, bool)>>>,+ open_started: Arc<Notify>,+ close_started: Arc<Notify>,+ call_started: Arc<Notify>,+ release_call: Arc<Notify>,+ block_first_open: Arc<std::sync::atomic::AtomicBool>,+ block_first_close: Arc<std::sync::atomic::AtomicBool>,+ block_calls: Arc<std::sync::atomic::AtomicBool>,+}++#[async_trait]+impl McpModulePort for FakePort {+ async fn open_configured(+ &self,+ data_dir: &str,+ config: &McpClientConfig,+ ) -> Result<OpenConfiguredResponse, ModuleCallError> {+ let index = {+ let mut opened = self.opened.lock().unwrap();+ let prior = opened+ .iter()+ .position(|(path, existing)| path == data_dir && existing == config);+ opened.push((data_dir.to_owned(), config.clone()));+ prior.map_or(opened.len(), |index| index + 1)+ };+ self.open_started.notify_one();+ if index == 1+ && self+ .block_first_open+ .swap(false, std::sync::atomic::Ordering::SeqCst)+ {+ std::future::pending::<()>().await;+ }+ Ok(OpenConfiguredResponse {+ object_path: format!("/workspace/{index}"),+ transition_id: format!("open-{index}"),+ })+ }++ async fn close(&self, data_dir: &str) -> Result<Option<String>, ModuleCallError> {+ let index = {+ let mut closed = self.closed.lock().unwrap();+ closed.push(data_dir.to_owned());+ closed.len()+ };+ self.close_started.notify_one();+ if index == 1+ && self+ .block_first_close+ .swap(false, std::sync::atomic::Ordering::SeqCst)+ {+ std::future::pending::<()>().await;+ }+ Ok(Some("close-1".to_owned()))+ }++ async fn transition_status(+ &self,+ _transition_id: &str,+ ) -> Result<TransitionStatus, ModuleCallError> {+ Ok(TransitionStatus::Complete)+ }++ async fn call_object(+ &self,+ object_path: &str,+ member: &str,+ args: Value,+ confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ self.calls.lock().unwrap().push((+ object_path.to_owned(),+ member.to_owned(),+ args,+ confidential,+ ));+ self.call_started.notify_one();+ if self.block_calls.load(std::sync::atomic::Ordering::SeqCst) {+ self.release_call.notified().await;+ }+ Ok(Value::Bool(true))+ }+}++fn client(port: FakePort) -> McpConfiguredClient {+ McpConfiguredClient::with_port("/private/workspace".to_owned(), Box::new(port))+}++fn configured(name: &str) -> McpClientConfig {+ McpClientConfig {+ servers: vec![tinymcp_bus::McpServerConfig {+ name: name.to_owned(),+ ..tinymcp_bus::McpServerConfig::default()+ }],+ ..McpClientConfig::default()+ }+}++#[tokio::test]+async fn opening_sends_configuration_confidentially_and_reuses_the_ready_object() {+ let port = FakePort::default();+ let opened = Arc::clone(&port.opened);+ let calls = Arc::clone(&port.calls);+ let client = client(port);+ let config = configured("private-server");++ assert!(client+ .call::<bool>(&config, "ConnectedOverview", ())+ .await+ .unwrap());+ assert!(client+ .call::<bool>(&config, "ConnectedOverview", ())+ .await+ .unwrap());++ assert_eq!(opened.lock().unwrap().len(), 1);+ assert_eq!(opened.lock().unwrap()[0].0, "/private/workspace");+ assert_eq!(opened.lock().unwrap()[0].1, config);+ let calls = calls.lock().unwrap();+ assert_eq!(calls.len(), 2);+ assert_eq!(calls[0].0, "/workspace/1");+ assert_eq!(calls[0].1, "ConnectedOverview");+ assert!(!calls[0].3);+}++#[tokio::test]+async fn configuration_switches_replace_the_object_before_dispatch() {+ let port = FakePort::default();+ let opened = Arc::clone(&port.opened);+ let calls = Arc::clone(&port.calls);+ let client = client(port);+ let first = configured("first");+ let second = configured("second");++ client+ .call::<bool>(&first, "ConnectedOverview", ())+ .await+ .unwrap();+ client+ .call::<bool>(&second, "ConnectedOverview", ())+ .await+ .unwrap();++ assert_eq!(opened.lock().unwrap().len(), 2);+ assert_eq!(calls.lock().unwrap()[0].0, "/workspace/1");+ assert_eq!(calls.lock().unwrap()[1].0, "/workspace/2");+}++#[tokio::test]+async fn a_cancelled_open_retries_the_same_confidential_request_and_recovers_its_receipt() {+ let port = FakePort {+ block_first_open: Arc::new(std::sync::atomic::AtomicBool::new(true)),+ ..FakePort::default()+ };+ let opened = Arc::clone(&port.opened);+ let calls = Arc::clone(&port.calls);+ let started = Arc::clone(&port.open_started);+ let client = Arc::new(client(port));+ let config = configured("private-server");+ let started_wait = started.notified();+ let task = tokio::spawn({+ let client = Arc::clone(&client);+ let config = config.clone();+ async move { client.call::<bool>(&config, "ConnectedOverview", ()).await }+ });+ started_wait.await;+ task.abort();+ let _ = task.await;++ let retry = tokio::spawn({+ let client = Arc::clone(&client);+ async move { client.call::<bool>(&config, "ConnectedOverview", ()).await }+ });+ assert_eq!(retry.await.unwrap(), Ok(true));+ let opened = opened.lock().unwrap();+ assert_eq!(opened.len(), 2);+ assert_eq!(opened[0].1, opened[1].1);+ assert_eq!(calls.lock().unwrap()[0].0, "/workspace/1");+}++#[tokio::test]+async fn close_waits_for_accepted_calls_and_confirms_cleanup() {+ let port = FakePort {+ block_calls: Arc::new(std::sync::atomic::AtomicBool::new(true)),+ ..FakePort::default()+ };+ let close_count = Arc::clone(&port.closed);+ let call_started = Arc::clone(&port.call_started);+ let release_call = Arc::clone(&port.release_call);+ let client = Arc::new(client(port));+ let config = configured("server");+ let call_started_wait = call_started.notified();+ let call = tokio::spawn({+ let client = Arc::clone(&client);+ let config = config.clone();+ async move { client.call::<bool>(&config, "ConnectedOverview", ()).await }+ });+ call_started_wait.await;+ let close = tokio::spawn({+ let client = Arc::clone(&client);+ async move { client.close().await }+ });+ tokio::task::yield_now().await;+ assert!(close_count.lock().unwrap().is_empty());+ release_call.notify_one();+ assert_eq!(call.await.unwrap(), Ok(true));+ assert_eq!(close.await.unwrap(), Ok(()));+ assert_eq!(close_count.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn a_cancelled_close_keeps_the_cleanup_operation_retryable() {+ let port = FakePort {+ block_first_close: Arc::new(std::sync::atomic::AtomicBool::new(true)),+ ..FakePort::default()+ };+ let close_count = Arc::clone(&port.closed);+ let started = Arc::clone(&port.close_started);+ let client = Arc::new(client(port));+ client+ .call::<bool>(&configured("server"), "ConnectedOverview", ())+ .await+ .unwrap();++ let started_wait = started.notified();+ let close = tokio::spawn({+ let client = Arc::clone(&client);+ async move { client.close().await }+ });+ started_wait.await;+ close.abort();+ let _ = close.await;++ let retry = tokio::spawn({+ let client = Arc::clone(&client);+ async move { client.close().await }+ });+ assert_eq!(retry.await.unwrap(), Ok(()));+ assert_eq!(close_count.lock().unwrap().len(), 2);+}++#[cfg(unix)]+#[tokio::test]+async fn non_utf8_workspace_paths_are_rejected_before_opening() {+ use std::os::unix::ffi::OsStrExt;+ let path = std::path::PathBuf::from(std::ffi::OsStr::from_bytes(b"/tmp/workspace\xff"));+ let result = McpConfiguredClient::new(&path, &Config::default());+ assert!(matches!(result, Err(ModuleCallError::IncompatibleContract)));+}diff --git a/crates/openhuman-core/src/mcp/registry/action_tool.rs b/crates/openhuman-core/src/mcp/registry/action_tool.rsindex f566d3820b..24ac6d5510 100644--- a/crates/openhuman-core/src/mcp/registry/action_tool.rs+++ b/crates/openhuman-core/src/mcp/registry/action_tool.rs@@ -141,13 +141,27 @@ impl McpToolInvoker for InstalledServerInvoker {tool: tool.to_string(),});}- let service = host::for_config(&self.config).map_err(|error| {- tracing::debug!(?error, server_id, "[mcp] no host for workspace");- not_connected()- })?;-let start = Instant::now();- let result = service.dynamic().invoke(server_id, tool, arguments).await;+ let result = async {+ let client = crate::mcp::module_client::McpConfiguredClient::for_config(&self.config)+ .map_err(|error| {+ tracing::debug!(?error, server_id, "[mcp] no module for workspace");+ not_connected()+ })?;+ let outcome: tinymcp_bus::ToolCallOutcome = client+ .call(+ &host::client_config(&self.config),+ tinymcp_bus::names::methods::TOOL_CALL,+ (server_id, tool, arguments),+ )+ .await+ .map_err(|error| {+ tracing::debug!(?error, server_id, tool, "[mcp] module tool call failed");+ not_connected()+ })?;+ Ok::<_, tinymcp::Error>(outcome.rendered)+ }+ .await;let elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);BUS.publish(DomainEvent::McpClientToolExecuted {server_id: server_id.to_string(),diff --git a/crates/openhuman-core/src/mcp/registry/mod.rs b/crates/openhuman-core/src/mcp/registry/mod.rsindex 8eaa721434..4767bcdcc1 100644--- a/crates/openhuman-core/src/mcp/registry/mod.rs+++ b/crates/openhuman-core/src/mcp/registry/mod.rs@@ -89,6 +89,16 @@ pub mod connections {use crate::mcp::host;+ async fn module_call<R: serde::de::DeserializeOwned>(+ config: &Config,+ member: &str,+ args: impl serde::Serialize,+ ) -> Result<R, crate::modules::client::ModuleCallError> {+ crate::mcp::module_client::McpConfiguredClient::for_config(config)?+ .call(&host::client_config(config), member, args)+ .await+ }+/// Every connected server's identity and advertised tools.////// Sorted by qualified name, so a prompt built from this does not reshuffle@@ -108,12 +118,12 @@ pub mod connections {/// [`disconnect_for_config`] exist: the ambient form resolves through the/// process default, which stops answering once a second workspace is open.pub async fn connected_overview_for_config(config: &Config) -> Vec<ConnectedServerOverview> {- match host::lookup(config) {- Ok(service) => service.dynamic().connected_overview().await,+ match module_call(config, tinymcp_bus::names::methods::CONNECTED_OVERVIEW, ()).await {+ Ok(overview) => overview,Err(error) => {tracing::debug!(?error,- "[mcp] no host for workspace; reporting no connections"+ "[mcp] no MCP module for workspace; reporting no connections");Vec::new()}@@ -129,18 +139,14 @@ pub mod connections {/// its connect finishes. Listing is not authorization — a call still/// needs a live connection.pub async fn cached_overview_for_config(config: &Config) -> Vec<ConnectedServerOverview> {- let service = match host::lookup(config) {- Ok(service) => service,- Err(error) => {- tracing::debug!(?error, "[mcp] no host for workspace; no cached tools");- return Vec::new();- }- };- match service.dynamic().cached_overview().await {+ match module_call(config, tinymcp_bus::names::methods::CACHED_OVERVIEW, ()).await {Ok(overview) => overview,Err(error) => {- tracing::debug!(%error, "[mcp] falling back to live servers only");- service.dynamic().connected_overview().await+ tracing::debug!(+ ?error,+ "[mcp] no module cached tools; checking live connections"+ );+ connected_overview_for_config(config).await}}}@@ -165,13 +171,18 @@ pub mod connections {pub async fn all_connected_tools_for_config(config: &Config,) -> Vec<(String, String, tinymcp_bus::McpTool)> {- match host::lookup(config) {- Ok(service) => service.dynamic().connections().all_connected_tools().await,- Err(error) => {- tracing::debug!(?error, "[mcp] no host for workspace; reporting no tools");- Vec::new()- }- }+ connected_overview_for_config(config)+ .await+ .into_iter()+ .flat_map(|server| {+ let server_id = server.server_id;+ let qualified_name = server.qualified_name;+ server+ .tools+ .into_iter()+ .map(move |tool| (server_id.clone(), qualified_name.clone(), tool))+ })+ .collect()}/// Every tool on every connected server, paired with its server.@@ -206,13 +217,11 @@ pub mod connections {config: &Config,server_id: &str,) -> Option<Vec<tinymcp_bus::McpTool>> {- match host::lookup(config) {- Ok(service) => service.dynamic().connections().tools_for(server_id).await,- Err(error) => {- tracing::debug!(?error, server_id, "[mcp] no host for workspace; no tools");- None- }- }+ connected_overview_for_config(config)+ .await+ .into_iter()+ .find(|server| server.server_id == server_id)+ .map(|server| server.tools)}/// Whether a server has a live entry.@@ -231,42 +240,23 @@ pub mod connections {/// Whether a server has a live entry in `config`'s workspace.pub async fn is_connected_for_config(config: &Config, server_id: &str) -> bool {- match host::lookup(config) {- Ok(service) => {- service- .dynamic()- .connections()- .is_connected(server_id)- .await- }- Err(error) => {- tracing::debug!(- ?error,- server_id,- "[mcp] no host for workspace; reporting not connected"- );- false- }- }+ connected_overview_for_config(config)+ .await+ .iter()+ .any(|server| server.server_id == server_id)}- /// Why a server's most recent attempt in `config`'s workspace hit a 401.+ /// Whether the last authentication failure requested OAuth.pub async fn auth_hint_for_config(config: &Config, server_id: &str) -> Option<&'static str> {- match host::lookup(config) {- Ok(service) => Some(- service- .dynamic()- .connections()- .auth_hint(server_id)- .await?- .as_code(),- ),+ let statuses: Result<Vec<tinymcp_bus::ConnStatus>, _> =+ module_call(config, tinymcp_bus::names::methods::STATUS, ()).await;+ match statuses {+ Ok(statuses) => statuses+ .iter()+ .find(|status| status.server_id == server_id)+ .and_then(|status| status.auth_hint.map(|hint| hint.as_code())),Err(error) => {- tracing::debug!(- ?error,- server_id,- "[mcp] no host for workspace; no auth hint"- );+ tracing::debug!(?error, "[mcp] no status for workspace; no auth hint");None}}@@ -283,21 +273,14 @@ pub mod connections {config: &crate::config::Config,server: &tinymcp_bus::InstalledServer,) -> anyhow::Result<Vec<tinymcp_bus::McpTool>> {- let service = host::for_config(config)?;- let client = host::client_config(config);-- service- .dynamic()- .connections()- .connect(- service.dynamic().store(),- service.dynamic().oauth(),- &client.client_identity,- client.proxy.as_ref(),- server,- )- .await- .map_err(|error| anyhow::anyhow!("failed to connect `{}`: {error}", server.server_id))+ let outcome: tinymcp_bus::ConnectOutcome = module_call(+ config,+ tinymcp_bus::names::methods::CONNECT,+ (server.server_id.clone(),),+ )+ .await+ .map_err(|error| anyhow::anyhow!("failed to connect `{}`: {error}", server.server_id))?;+ Ok(outcome.tools)}/// Drops a server's connection, reporting whether there was one.@@ -320,8 +303,14 @@ pub mod connections {/// through [`connect`] already named a workspace and should close over the/// same one.pub async fn disconnect_for_config(config: &Config, server_id: &str) -> bool {- match host::lookup(config) {- Ok(service) => service.dynamic().connections().disconnect(server_id).await,+ match module_call::<bool>(+ config,+ tinymcp_bus::names::methods::DISCONNECT,+ (server_id,),+ )+ .await+ {+ Ok(disconnected) => disconnected,Err(error) => {tracing::debug!(?error, "[mcp] no host for workspace; nothing to disconnect");false@@ -331,8 +320,17 @@ pub mod connections {/// The most recent failure message for a server in `config`'s workspace.pub async fn last_error_for_config(config: &Config, server_id: &str) -> Option<String> {- match host::lookup(config) {- Ok(service) => service.dynamic().connections().last_error(server_id).await,+ match module_call::<Vec<tinymcp_bus::ConnStatus>>(+ config,+ tinymcp_bus::names::methods::STATUS,+ (),+ )+ .await+ {+ Ok(statuses) => statuses+ .into_iter()+ .find(|status| status.server_id == server_id)+ .and_then(|status| status.last_error),Err(error) => {tracing::debug!(?error,diff --git a/crates/openhuman-core/src/mcp/registry/ops.rs b/crates/openhuman-core/src/mcp/registry/ops.rsindex eb02a50d28..d573446cc1 100644--- a/crates/openhuman-core/src/mcp/registry/ops.rs+++ b/crates/openhuman-core/src/mcp/registry/ops.rs@@ -3,8 +3,8 @@//! Every function here maps one-to-one with a `schemas.rs` handler and keeps//! the signature and the JSON shape it had before the client moved out to//! `tinymcp` — the frontend calls these methods and nothing about its contract-//! changed. What changed is underneath: each one now delegates to the service-//! [`super::super::host`] holds.+//! changed. Registry, connection, and tool calls delegate to the configured+//! TinyMCP module object; host configuration and event projection remain here.//!//! # What stayed here on purpose//!@@ -33,7 +33,31 @@ use crate::core::events::DomainEvent;use crate::core::Outcome;use crate::mcp::host;-use super::helpers::{encode, inject_required_env_keys, require, resolve};+use super::helpers::{encode, inject_required_env_keys, require};++async fn module_call<R: serde::de::DeserializeOwned>(+ config: &Config,+ member: &str,+ args: impl serde::Serialize,+) -> Result<R, String> {+ super::super::module_client::McpConfiguredClient::for_config(config)+ .map_err(|error| error.to_string())?+ .call(&host::client_config(config), member, args)+ .await+ .map_err(|error| error.to_string())+}++async fn module_call_confidential<R: serde::de::DeserializeOwned>(+ config: &Config,+ member: &str,+ args: impl serde::Serialize,+) -> Result<R, String> {+ super::super::module_client::McpConfiguredClient::for_config(config)+ .map_err(|error| error.to_string())?+ .call_confidential(&host::client_config(config), member, args)+ .await+ .map_err(|error| error.to_string())+}// ── registry_search ──────────────────────────────────────────────────────────@@ -51,16 +75,20 @@ pub async fn mcp_clients_registry_search(let page = page.unwrap_or(1);let page_size = page_size.unwrap_or(20);- let mut found = resolve(config)?- .dynamic()- .registry_search(query.as_deref(), page, page_size)- .await- .map_err(|error| error.to_string())?;-- // Badging and the strict filter are presentation choices, applied here so a- // caller assembling its own view does not have to undo them.- tinymcp::registry::curation::tag_official(&mut found.servers);- tinymcp::registry::curation::float_official_first(&mut found.servers);+ let found: tinymcp_bus::RegistrySearchPage = module_call(+ config,+ tinymcp_bus::names::methods::REGISTRY_SEARCH_CURATED,+ (+ query,+ page,+ page_size,+ tinymcp_bus::SearchCuration {+ tag_official: true,+ official_first: true,+ },+ ),+ )+ .await?;let count = found.servers.len();Ok(Outcome::new(@@ -81,22 +109,23 @@ pub async fn mcp_clients_registry_get() -> Result<Outcome<Value>, String> {let qualified_name = require(&qualified_name, "qualified_name")?;- let (detail, required_env_keys) = resolve(config)?- .dynamic()- .registry_get(&qualified_name)- .await- .map_err(|error| error.to_string())?;+ let detail: tinymcp_bus::ServerDetail = module_call(+ config,+ tinymcp_bus::names::methods::REGISTRY_GET,+ (qualified_name.clone(),),+ )+ .await?;// The registry tab shows what a server would ask for, and fetching the two// separately would be two catalog round trips for one screen.- let mut server = encode(&detail)?;- inject_required_env_keys(&mut server, &required_env_keys);+ let mut server = encode(&detail.server)?;+ inject_required_env_keys(&mut server, &detail.required_env_keys);Ok(Outcome::new(json!({ "server": server }),vec![format!("registry_get ok: {qualified_name} env_keys={}",- required_env_keys.len()+ detail.required_env_keys.len())],))}@@ -104,10 +133,8 @@ pub async fn mcp_clients_registry_get(// ── installed_list ───────────────────────────────────────────────────────────pub async fn mcp_clients_installed_list(config: &Config) -> Result<Outcome<Value>, String> {- let installed = resolve(config)?- .dynamic()- .installed_list()- .map_err(|error| error.to_string())?;+ let installed: Vec<tinymcp_bus::InstalledServer> =+ module_call(config, tinymcp_bus::names::methods::INSTALLED_LIST, ()).await?;let count = installed.len();Ok(Outcome::new(@@ -124,11 +151,12 @@ pub async fn mcp_clients_uninstall() -> Result<Outcome<Value>, String> {let server_id = require(&server_id, "server_id")?;- let removed = resolve(config)?- .dynamic()- .uninstall(&server_id)- .await- .map_err(|error| error.to_string())?;+ let removed: bool = module_call(+ config,+ tinymcp_bus::names::methods::UNINSTALL,+ (server_id.clone(),),+ )+ .await?;Ok(Outcome::new(json!({ "server_id": server_id, "removed": removed }),@@ -144,11 +172,12 @@ pub async fn mcp_clients_detect_auth() -> Result<Outcome<Value>, String> {let server_id = require(&server_id, "server_id")?;- let detection = resolve(config)?- .dynamic()- .detect_auth(&server_id)- .await- .map_err(|error| error.to_string())?;+ let detection: tinymcp_bus::AuthDetection = module_call(+ config,+ tinymcp_bus::names::methods::DETECT_AUTH,+ (server_id.clone(),),+ )+ .await?;let kind = detection.kind.as_str();let value = encode(&detection)?;@@ -165,11 +194,12 @@ pub async fn mcp_clients_oauth_begin() -> Result<Outcome<Value>, String> {let server_id = require(&server_id, "server_id")?;- let authorize_url = resolve(config)?- .dynamic()- .oauth_begin(&server_id, &host::oauth_redirect_uri())- .await- .map_err(|error| error.to_string())?;+ let authorize_url: String = module_call(+ config,+ tinymcp_bus::names::methods::OAUTH_BEGIN,+ (server_id.clone(), host::oauth_redirect_uri()),+ )+ .await?;Ok(Outcome::new(json!({ "authorize_url": authorize_url }),@@ -185,11 +215,12 @@ pub async fn mcp_clients_connect() -> Result<Outcome<Value>, String> {let server_id = require(&server_id, "server_id")?;- let outcome = resolve(config)?- .dynamic()- .connect(&server_id)- .await- .map_err(|error| error.to_string())?;+ let outcome: tinymcp_bus::ConnectOutcome = module_call(+ config,+ tinymcp_bus::names::methods::CONNECT,+ (server_id.clone(),),+ )+ .await?;let tools = super::tools_safe_for_agent(&server_id, outcome.tools);let tool_count = u32::try_from(tools.len()).unwrap_or(u32::MAX);@@ -216,11 +247,12 @@ pub async fn mcp_clients_set_enabled() -> Result<Outcome<Value>, String> {let server_id = require(&server_id, "server_id")?;- resolve(config)?- .dynamic()- .set_enabled(&server_id, enabled)- .await- .map_err(|error| error.to_string())?;+ let _: () = module_call(+ config,+ tinymcp_bus::names::methods::SET_ENABLED,+ (server_id.clone(), enabled),+ )+ .await?;if !enabled {BUS.publish(DomainEvent::McpServerDisconnected {@@ -245,11 +277,12 @@ pub async fn mcp_clients_disconnect() -> Result<Outcome<Value>, String> {let server_id = require(&server_id, "server_id")?;- resolve(config)?- .dynamic()- .disconnect(&server_id)- .await- .map_err(|error| error.to_string())?;+ let _: bool = module_call(+ config,+ tinymcp_bus::names::methods::DISCONNECT,+ (server_id.clone(),),+ )+ .await?;BUS.publish(DomainEvent::McpServerDisconnected {server_id: server_id.clone(),@@ -273,11 +306,16 @@ pub async fn mcp_clients_update_env(let server_id = require(&server_id, "server_id")?;- let outcome = resolve(config)?- .dynamic()- .update_env(&server_id, env.into_iter().collect())- .await- .map_err(|error| error.to_string())?;+ let outcome: tinymcp_bus::UpdateEnvOutcome = module_call_confidential(+ config,+ tinymcp_bus::names::methods::UPDATE_ENV,+ (+ server_id.clone(),+ env.into_iter()+ .collect::<std::collections::BTreeMap<_, _>>(),+ ),+ )+ .await?;match outcome.status {UpdateEnvStatus::Connected => {@@ -348,7 +386,12 @@ pub async fn mcp_clients_update_env(// ── registry settings ────────────────────────────────────────────────────────pub async fn mcp_clients_registry_settings_get(config: &Config) -> Result<Outcome<Value>, String> {- let settings = resolve(config)?.dynamic().registry_settings();+ let settings: tinymcp_bus::RegistrySettings = module_call(+ config,+ tinymcp_bus::names::methods::REGISTRY_SETTINGS_GET,+ (),+ )+ .await?;Ok(Outcome::new(encode(&settings)?,@@ -381,11 +424,12 @@ pub async fn mcp_clients_registry_settings_set(config.save().await.map_err(|error| error.to_string())?;- let settings = resolve(config)?.dynamic().set_registry_settings(- smithery_api_key,- mcp_official_base,- mcp_official_token,- );+ let settings: tinymcp_bus::RegistrySettings = module_call_confidential(+ config,+ tinymcp_bus::names::methods::REGISTRY_SETTINGS_SET,+ (smithery_api_key, mcp_official_base, mcp_official_token),+ )+ .await?;Ok(Outcome::new(encode(&settings)?,@@ -396,11 +440,8 @@ pub async fn mcp_clients_registry_settings_set(// ── status ───────────────────────────────────────────────────────────────────pub async fn mcp_clients_status(config: &Config) -> Result<Outcome<Value>, String> {- let statuses = resolve(config)?- .dynamic()- .status()- .await- .map_err(|error| error.to_string())?;+ let statuses: Vec<tinymcp_bus::ConnStatus> =+ module_call(config, tinymcp_bus::names::methods::STATUS, ()).await?;let count = statuses.len();Ok(Outcome::new(@@ -511,35 +552,44 @@ pub async fn mcp_clients_list_tools(caller: Caller,) -> Result<Outcome<Value>, String> {let mut server_id = require(&server_id, "server_id")?;- let registry = resolve(config)?;- let registry = registry.dynamic();-- let tools = match registry.list_tools(&server_id).await {+ let tools: Vec<tinymcp_bus::McpTool> = match module_call(+ config,+ tinymcp_bus::names::methods::LIST_TOOLS,+ (server_id.clone(),),+ )+ .await+ {Ok(tools) => tools,- Err(tinymcp::Error::NotConnected { .. }) => {- let installs = registry.status().await.map_err(|error| error.to_string())?;+ Err(error) => {+ let installs: Vec<tinymcp_bus::ConnStatus> =+ module_call(config, tinymcp_bus::names::methods::STATUS, ()).await?;+ if installs.iter().any(|install| {+ install.server_id == server_id+ && install.status == tinymcp_bus::ServerStatus::Connected+ }) {+ return Err(error);+ }match explain_not_connected(&server_id, &installs, caller) {NotConnected::Resolved(resolved) => {- tracing::debug!(- "[mcp-client] list_tools: {server_id} resolved to server_id={resolved}"- );- // `resolved` came from `installs`, so the lookup always finds it.- let tools = registry.list_tools(&resolved).await.map_err(|error| {+ server_id = resolved;+ module_call(+ config,+ tinymcp_bus::names::methods::LIST_TOOLS,+ (server_id.clone(),),+ )+ .await+ .map_err(|_| {installs.iter()- .find(|s| s.server_id == resolved)- .map_or_else(|| error.to_string(), |i| not_connected_message(i, caller))- })?;- server_id = resolved;- tools+ .find(|install| install.server_id == server_id)+ .map_or(error.clone(), |install| {+ not_connected_message(install, caller)+ })+ })?}NotConnected::Refused(message) => return Err(message),}}- Err(error) => {- tracing::debug!("[mcp-client] list_tools ({server_id}) failed: {error}");- return Err(error.to_string());- }};let tools = super::tools_safe_for_agent(&server_id, tools);@@ -565,10 +615,12 @@ pub async fn mcp_clients_tool_call(let tool_name = require(&tool_name, "tool_name")?;let start = Instant::now();- let result = resolve(config)?- .dynamic()- .tool_call(&server_id, &tool_name, arguments)- .await;+ let result: Result<tinymcp_bus::ToolCallOutcome, String> = module_call(+ config,+ tinymcp_bus::names::methods::TOOL_CALL,+ (server_id.clone(), tool_name.clone(), arguments),+ )+ .await;let elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);BUS.publish(DomainEvent::McpClientToolExecuted {@@ -586,7 +638,7 @@ pub async fn mcp_clients_tool_call()],)),Err(error) => Ok(Outcome::new(- json!({ "result": error.to_string(), "is_error": true }),+ json!({ "result": error, "is_error": true }),vec![format!("tool_call error server_id={server_id} tool={tool_name}: {error}")],diff --git a/crates/openhuman-core/src/mcp/registry/ops_tests.rs b/crates/openhuman-core/src/mcp/registry/ops_tests.rsindex 748c70b195..2c38e9b2b1 100644--- a/crates/openhuman-core/src/mcp/registry/ops_tests.rs+++ b/crates/openhuman-core/src/mcp/registry/ops_tests.rs@@ -6,6 +6,12 @@//! can pin without connecting anything.use super::*;+use crate::mcp::module_client::{McpConfiguredClient, McpModulePort};+use crate::modules::client::ModuleCallError;+use async_trait::async_trait;+use serde_json::Value;+use std::sync::{Arc, Mutex};+use tinymcp_bus::{OpenConfiguredResponse, TransitionStatus};#[test]fn a_blank_identifier_is_refused_with_the_field_name() {@@ -21,8 +27,8 @@ fn an_identifier_is_trimmed_before_it_is_used() {// ── list_tools refusals (#6313) ─────────────────────────────────────────────//-// A real host over a temp workspace. `apply_config_doc` writes the install-// store and dials nothing, so an installed server stays disconnected.+// A per-workspace fake module port keeps these handler tests independent of a+// live module process while exercising the production TinyBus adapter.const QUALIFIED: &str = "io.github.ryudi84/uuid";@@ -35,27 +41,117 @@ fn temp_config(workspace: &tempfile::TempDir) -> Config {}}-/// Installs one stdio server under [`QUALIFIED`] and returns its `server_id`.-async fn install_one(config: &Config) -> String {- let registry = resolve(config).unwrap();- let doc = json!({ "mcpServers": { QUALIFIED: { "command": "uuid-mcp" } } });- registry.dynamic().apply_config_doc(&doc).await.unwrap();- let installs = registry.dynamic().status().await.unwrap();- assert_eq!(installs.len(), 1, "{installs:?}");- assert_ne!(- installs[0].server_id, QUALIFIED,- "fixture: the install's id must differ from its registry name"- );- installs[0].server_id.clone()+#[derive(Clone, Default)]+struct RegistryPort {+ statuses: Arc<Mutex<Vec<tinymcp_bus::ConnStatus>>>,+}++#[async_trait]+impl McpModulePort for RegistryPort {+ async fn open_configured(+ &self,+ _data_dir: &str,+ _config: &tinymcp_bus::McpClientConfig,+ ) -> Result<OpenConfiguredResponse, ModuleCallError> {+ Ok(OpenConfiguredResponse {+ object_path: "/test/mcp".to_owned(),+ transition_id: "open-test".to_owned(),+ })+ }++ async fn close(&self, _data_dir: &str) -> Result<Option<String>, ModuleCallError> {+ Ok(None)+ }++ async fn transition_status(+ &self,+ _transition_id: &str,+ ) -> Result<TransitionStatus, ModuleCallError> {+ Ok(TransitionStatus::Complete)+ }++ async fn call_object(+ &self,+ _object_path: &str,+ member: &str,+ args: Value,+ _confidential: bool,+ ) -> Result<Value, ModuleCallError> {+ match member {+ tinymcp_bus::names::methods::STATUS => {+ serde_json::to_value(self.statuses.lock().unwrap().clone())+ .map_err(|_| ModuleCallError::ModuleFault)+ }+ tinymcp_bus::names::methods::CONNECT => {+ let server_id = args+ .get(0)+ .and_then(Value::as_str)+ .ok_or(ModuleCallError::ModuleFault)?;+ let mut statuses = self.statuses.lock().unwrap();+ let status = statuses+ .iter_mut()+ .find(|status| status.server_id == server_id)+ .ok_or(ModuleCallError::ModuleFault)?;+ status.status = tinymcp_bus::ServerStatus::Connected;+ status.tool_count = 1;+ let outcome = tinymcp_bus::ConnectOutcome {+ server_id: server_id.to_owned(),+ tools: vec![tinymcp_bus::McpTool::new("forecast")],+ };+ serde_json::to_value(outcome).map_err(|_| ModuleCallError::ModuleFault)+ }+ tinymcp_bus::names::methods::LIST_TOOLS => {+ let server_id = args+ .get(0)+ .and_then(Value::as_str)+ .ok_or(ModuleCallError::ModuleFault)?;+ let statuses = self.statuses.lock().unwrap();+ let connected = statuses.iter().any(|status| {+ status.server_id == server_id+ && status.status == tinymcp_bus::ServerStatus::Connected+ });+ if connected {+ serde_json::to_value(vec![tinymcp_bus::McpTool::new("forecast")])+ .map_err(|_| ModuleCallError::ModuleFault)+ } else {+ Err(ModuleCallError::ModuleFault)+ }+ }+ _ => Err(ModuleCallError::IncompatibleContract),+ }+ }+}++fn status(server_id: &str, qualified_name: &str) -> tinymcp_bus::ConnStatus {+ tinymcp_bus::ConnStatus {+ server_id: server_id.to_owned(),+ qualified_name: qualified_name.to_owned(),+ display_name: "fixture".to_owned(),+ status: tinymcp_bus::ServerStatus::Disconnected,+ tool_count: 0,+ last_error: None,+ auth_hint: None,+ }+}++fn install_port(config: &Config, statuses: Vec<tinymcp_bus::ConnStatus>) {+ McpConfiguredClient::install_test_port(+ config,+ Box::new(RegistryPort {+ statuses: Arc::new(Mutex::new(statuses)),+ }),+ )+ .unwrap();}#[tokio::test]async fn agent_refusal_names_no_rpc_method() {let workspace = tempfile::tempdir().unwrap();let config = temp_config(&workspace);- let server_id = install_one(&config).await;+ let server_id = "fixture-install";+ install_port(&config, vec![status(server_id, QUALIFIED)]);- let error = mcp_clients_list_tools(&config, server_id.clone(), Caller::Agent)+ let error = mcp_clients_list_tools(&config, server_id.to_owned(), Caller::Agent).await.expect_err("a disconnected server has no tools to list");assert!(!error.contains("mcp_clients_"), "{error}");@@ -132,9 +228,10 @@ fn refusals_name_only_tools_on_every_listing_belt() {async fn rpc_refusal_still_names_the_rpc_method() {let workspace = tempfile::tempdir().unwrap();let config = temp_config(&workspace);- let server_id = install_one(&config).await;+ let server_id = "fixture-install";+ install_port(&config, vec![status(server_id, QUALIFIED)]);- let error = mcp_clients_list_tools(&config, server_id, Caller::Rpc)+ let error = mcp_clients_list_tools(&config, server_id.to_owned(), Caller::Rpc).await.expect_err("a disconnected server has no tools to list");assert!(error.contains("mcp_clients_connect"), "{error}");@@ -145,7 +242,8 @@ async fn rpc_refusal_still_names_the_rpc_method() {async fn a_qualified_name_resolves_to_its_install() {let workspace = tempfile::tempdir().unwrap();let config = temp_config(&workspace);- let server_id = install_one(&config).await;+ let server_id = "fixture-install";+ install_port(&config, vec![status(server_id, QUALIFIED)]);// Resolved, then refused for the install it names — in terms of that// install's server_id, not the registry name the caller passed.@@ -162,7 +260,7 @@ async fn a_qualified_name_resolves_to_its_install() {async fn an_uninstalled_id_is_not_reported_as_not_connected() {let workspace = tempfile::tempdir().unwrap();let config = temp_config(&workspace);- install_one(&config).await;+ install_port(&config, vec![]);let error = mcp_clients_list_tools(&config, "io.github.other/absent".into(), Caller::Agent).await@@ -172,36 +270,15 @@ async fn an_uninstalled_id_is_not_reported_as_not_connected() {assert!(error.contains("mcp_registry_status"), "{error}");}-/// The #6313 case itself: the server is connected, and the caller passes its-/// registry name. The listing is answered for the install that name resolves-/// to, under that install's `server_id`.-///-/// The server is OpenHuman's own MCP endpoint on an ephemeral loopback port,-/// so nothing leaves the machine.-#[cfg(feature = "http-server")]+/// The #6313 case itself: the module owns the connection and answers a+/// qualified-name lookup with the connected install's tools.#[tokio::test]async fn a_qualified_name_lists_the_tools_of_its_connected_install() {- let (bound_tx, bound_rx) = tokio::sync::oneshot::channel();- let serve = crate::mcp::server::HttpServerConfig {- bind_addr: "127.0.0.1:0".parse().unwrap(),- auth_token: None,- };- let server = tokio::spawn(crate::mcp::server::run_http_reporting(- serve,- Some(bound_tx),- ));- let endpoint = format!("http://{}/", bound_rx.await.unwrap());-let workspace = tempfile::tempdir().unwrap();let config = temp_config(&workspace);- let registry = resolve(&config).unwrap();- let doc = json!({ "mcpServers": { QUALIFIED: { "url": endpoint } } });- registry.dynamic().apply_config_doc(&doc).await.unwrap();- let server_id = registry.dynamic().status().await.unwrap()[0]- .server_id- .clone();- assert_ne!(server_id, QUALIFIED, "fixture: id and registry name differ");- mcp_clients_connect(&config, server_id.clone())+ let server_id = "fixture-install";+ install_port(&config, vec![status(server_id, QUALIFIED)]);+ mcp_clients_connect(&config, server_id.to_owned()).await.unwrap();@@ -214,9 +291,6 @@ async fn a_qualified_name_lists_the_tools_of_its_connected_install() {"{}",listed.value);-- registry.dynamic().disconnect(&server_id).await.unwrap();- server.abort();}#[test]diff --git a/crates/openhuman-core/src/mcp/registry/tools_tests.rs b/crates/openhuman-core/src/mcp/registry/tools_tests.rsindex bbd524388f..e0cbda38d1 100644--- a/crates/openhuman-core/src/mcp/registry/tools_tests.rs+++ b/crates/openhuman-core/src/mcp/registry/tools_tests.rs@@ -1,5 +1,7 @@use super::*;+use async_trait::async_trait;use serde_json::json;+use std::sync::{Arc as SharedArc, Mutex};use tinytools::ToolScope;fn cfg() -> Arc<Config> {@@ -62,7 +64,14 @@ async fn list_tools_requires_server_id() {async fn list_tools_errors_for_unconnected_server() {// A server_id that is not installed errors rather than succeeding empty,// and says so rather than claiming it is merely not connected (#6313).- let err = McpRegistryListToolsTool::new(cfg())+ let dir = tempfile::tempdir().expect("temp workspace");+ let config = workspace_config(dir.path());+ crate::mcp::module_client::McpConfiguredClient::install_test_port(+ &config,+ Box::new(ToolCallPort::default()),+ )+ .expect("test module port");+ let err = McpRegistryListToolsTool::new(Arc::clone(&config)).execute(json!({ "server_id": "definitely-not-connected-uuid" })).await.expect_err("unconnected server must error");@@ -225,70 +234,113 @@ fn workspace_config(dir: &std::path::Path) -> Arc<Config> {})}-/// Answers the MCP handshake and one tool over Streamable HTTP.-struct LoopbackMcp;+#[derive(Clone, Default)]+struct ToolCallPort {+ arguments: SharedArc<Mutex<Vec<Value>>>,+ connected: bool,+}-impl wiremock::Respond for LoopbackMcp {- fn respond(&self, request: &wiremock::Request) -> wiremock::ResponseTemplate {- let body: Value = serde_json::from_slice(&request.body).unwrap_or_default();- let result = match body["method"].as_str().unwrap_or_default() {- "initialize" => json!({- "protocolVersion": tinymcp_bus::LATEST_PROTOCOL_VERSION,- "capabilities": { "tools": {} },- "serverInfo": { "name": "loopback", "version": "1.0.0" },- }),- "notifications/initialized" => return wiremock::ResponseTemplate::new(202),- "tools/list" => json!({- "tools": [{ "name": "forecast", "inputSchema": { "type": "object" } }]- }),- "tools/call" => json!({ "content": [{ "type": "text", "text": "sunny" }] }),- _ => json!({}),- };- wiremock::ResponseTemplate::new(200).set_body_json(json!({- "jsonrpc": "2.0",- "id": body["id"].clone(),- "result": result,- }))+#[async_trait]+impl crate::mcp::module_client::McpModulePort for ToolCallPort {+ async fn open_configured(+ &self,+ _data_dir: &str,+ _config: &tinymcp_bus::McpClientConfig,+ ) -> Result<tinymcp_bus::OpenConfiguredResponse, crate::modules::client::ModuleCallError> {+ Ok(tinymcp_bus::OpenConfiguredResponse {+ object_path: "/test/mcp".to_owned(),+ transition_id: "open-test".to_owned(),+ })+ }++ async fn close(+ &self,+ _data_dir: &str,+ ) -> Result<Option<String>, crate::modules::client::ModuleCallError> {+ Ok(None)+ }++ async fn transition_status(+ &self,+ _transition_id: &str,+ ) -> Result<tinymcp_bus::TransitionStatus, crate::modules::client::ModuleCallError> {+ Ok(tinymcp_bus::TransitionStatus::Complete)+ }++ async fn call_object(+ &self,+ _object_path: &str,+ member: &str,+ args: Value,+ _confidential: bool,+ ) -> Result<Value, crate::modules::client::ModuleCallError> {+ match member {+ tinymcp_bus::names::methods::STATUS => {+ let statuses = self.connected.then(|| tinymcp_bus::ConnStatus {+ server_id: "srv-1".to_owned(),+ qualified_name: "loopback".to_owned(),+ display_name: "loopback".to_owned(),+ status: tinymcp_bus::ServerStatus::Connected,+ tool_count: 1,+ last_error: None,+ auth_hint: None,+ });+ serde_json::to_value(statuses.into_iter().collect::<Vec<_>>())+ .map_err(|_| crate::modules::client::ModuleCallError::ModuleFault)+ }+ tinymcp_bus::names::methods::LIST_TOOLS => {+ if self.connected {+ serde_json::to_value(vec![tinymcp_bus::McpTool::new("forecast")])+ .map_err(|_| crate::modules::client::ModuleCallError::ModuleFault)+ } else {+ Err(crate::modules::client::ModuleCallError::ModuleFault)+ }+ }+ tinymcp_bus::names::methods::CONNECTED_OVERVIEW => {+ let overview = self+ .connected+ .then(|| tinymcp_bus::ConnectedServerOverview {+ server_id: "srv-1".to_owned(),+ qualified_name: "loopback".to_owned(),+ display_name: "loopback".to_owned(),+ description: None,+ instructions: None,+ tools: vec![tinymcp_bus::McpTool::new("forecast")],+ });+ serde_json::to_value(overview.into_iter().collect::<Vec<_>>())+ .map_err(|_| crate::modules::client::ModuleCallError::ModuleFault)+ }+ tinymcp_bus::names::methods::TOOL_CALL => {+ let arguments = args+ .get(2)+ .cloned()+ .ok_or(crate::modules::client::ModuleCallError::ModuleFault)?;+ self.arguments.lock().unwrap().push(arguments);+ serde_json::to_value(tinymcp_bus::ToolCallOutcome {+ result: json!({"content":[{"type":"text","text":"sunny"}]}),+ is_error: false,+ rendered: tinymcp_bus::McpToolResult::success("sunny"),+ })+ .map_err(|_| crate::modules::client::ModuleCallError::ModuleFault)+ }+ _ => Err(crate::modules::client::ModuleCallError::IncompatibleContract),+ }}}#[tokio::test]-async fn tool_call_with_string_arguments_reaches_the_server_as_an_object() {- // The reported failure: a model called `mcp_registry_tool_call` with+async fn tool_call_with_string_arguments_reaches_the_module_as_an_object() {+ // A model can call `mcp_registry_tool_call` with// `"arguments": "{...}"`, a JSON-encoded string where MCP needs an object.- let server = wiremock::MockServer::start().await;- wiremock::Mock::given(wiremock::matchers::method("POST"))- .respond_with(LoopbackMcp)- .mount(&server)- .await;let dir = tempfile::tempdir().expect("temp workspace");let config = workspace_config(dir.path());- let host = crate::mcp::host::for_config(&config).expect("host");- host.dynamic()- .store()- .insert_server(&crate::mcp::registry::InstalledServer {- server_id: "srv-1".into(),- qualified_name: "loopback".into(),- display_name: "loopback".into(),- description: None,- icon_url: None,- command_kind: tinymcp_bus::CommandKind::Node,- command: String::new(),- args: Vec::new(),- env_keys: Vec::new(),- config: None,- installed_at: 1,- last_connected_at: None,- transport: tinymcp_bus::Transport::HttpRemote {- url: format!("{}/mcp", server.uri()),- },- enabled: true,- })- .expect("insert");- McpRegistryConnectTool::new(Arc::clone(&config))- .execute(json!({ "server_id": "srv-1" }))- .await- .expect("connect");+ let port = ToolCallPort {+ connected: true,+ ..ToolCallPort::default()+ };+ let arguments = SharedArc::clone(&port.arguments);+ crate::mcp::module_client::McpConfiguredClient::install_test_port(&config, Box::new(port))+ .expect("test module port");let result = McpRegistryToolCallTool::new(Arc::clone(&config)).execute(json!({@@ -300,14 +352,8 @@ async fn tool_call_with_string_arguments_reaches_the_server_as_an_object() {.expect("call");assert!(!result.is_error, "{}", result.text());- let calls: Vec<Value> = server- .received_requests()- .await- .expect("recording")- .iter()- .filter_map(|request| serde_json::from_slice::<Value>(&request.body).ok())- .filter(|body| body["method"] == "tools/call")- .collect();- assert_eq!(calls.len(), 1);- assert_eq!(calls[0]["params"]["arguments"], json!({ "city": "Paris" }));+ assert_eq!(+ arguments.lock().unwrap().as_slice(),+ &[json!({ "city": "Paris" })]+ );}diff --git a/crates/openhuman-core/src/modules/client.rs b/crates/openhuman-core/src/modules/client.rsindex 14e9811212..14d759d568 100644--- a/crates/openhuman-core/src/modules/client.rs+++ b/crates/openhuman-core/src/modules/client.rs@@ -128,6 +128,42 @@ impl ModuleClient {decode_module_json(module, &response)}+ /// Resolve a private proxy for an object returned by an owning module.+ ///+ /// Object paths are kept inside the owning host adapter; callers should+ /// wrap this in a domain-specific client rather than expose the path as+ /// product state.+ #[cfg(feature = "modules")]+ pub(crate) async fn object_client(+ &self,+ module: &str,+ object_path: &str,+ ) -> Result<ModuleObjectClient, ModuleCallError> {+ let Some(record) = registry::find(module) else {+ failure::report_unknown_module();+ return Err(ModuleCallError::Unavailable);+ };+ if !self.config.modules.enabled {+ failure::report(record, failure::Reason::Disabled);+ return Err(ModuleCallError::Unavailable);+ }+ super::ops::ensure_loaded(&self.config, module)+ .await+ .map_err(|_| ModuleCallError::Unavailable)?;+ let runtime = super::host::runtime().await.map_err(|_| {+ failure::report(record, failure::Reason::TransportFailed);+ ModuleCallError::TransportFailed+ })?;+ let proxy = runtime.proxy(record.bus_name, object_path).map_err(|_| {+ failure::report(record, failure::Reason::IncompatibleContract);+ ModuleCallError::IncompatibleContract+ })?;+ let proxy = self+ .timeout+ .map_or(proxy.clone(), |timeout| proxy.with_timeout(timeout));+ Ok(ModuleObjectClient { record, proxy })+ }+/// Report a structurally invalid reply from a known module invocation.pub(crate) fn report_malformed_reply(module: &str) {if let Some(record) = registry::find(module) {@@ -201,6 +237,35 @@ impl ModuleClient {}}+/// A validated proxy for a module-owned object path.+///+/// This stays crate-private so bus object identities do not become product+/// state or leak into logs and controller responses.+#[cfg(feature = "modules")]+pub(crate) struct ModuleObjectClient {+ record: &'static super::types::ModuleRecord,+ proxy: tinybus::Proxy,+}++#[cfg(feature = "modules")]+impl ModuleObjectClient {+ pub(crate) async fn call<R: DeserializeOwned>(+ &self,+ member: &str,+ args: impl Serialize,+ ) -> Result<R, ModuleCallError> {+ invoke_proxy(self.record, &self.proxy, member, args, false).await+ }++ pub(crate) async fn call_confidential<R: DeserializeOwned>(+ &self,+ member: &str,+ args: impl Serialize,+ ) -> Result<R, ModuleCallError> {+ invoke_proxy(self.record, &self.proxy, member, args, true).await+ }+}+fn decode_module_json<R: DeserializeOwned>(module: &str,response: &str,diff --git a/crates/openhuman-core/src/modules/client_tests.rs b/crates/openhuman-core/src/modules/client_tests.rsindex a45cc0cfd1..ae607ed4f6 100644--- a/crates/openhuman-core/src/modules/client_tests.rs+++ b/crates/openhuman-core/src/modules/client_tests.rs@@ -288,6 +288,50 @@ async fn bus_calls_preserve_tuple_arity_and_never_downgrade_confidentiality() {);}+#[cfg(feature = "modules")]+#[tokio::test]+async fn private_object_clients_dispatch_only_to_the_configured_object() {+ use tinybus::{broker::Broker, transport::memory::MemoryBus, Connection, ObjectPath};+ let bus = MemoryBus::new();+ Broker::new().spawn(bus.clone());+ let service = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let caller = Connection::connect(bus.connect().await.unwrap())+ .await+ .unwrap();+ let root_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let child_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ service+ .serve_at(+ ObjectPath::new("/test/ModuleClient").unwrap(),+ BusFixture(root_calls.clone()),+ )+ .await+ .unwrap();+ service+ .serve_at(+ ObjectPath::new("/test/ModuleClient/workspace_1").unwrap(),+ BusFixture(child_calls.clone()),+ )+ .await+ .unwrap();+ service.request_name("test.ModuleClient").await.unwrap();+ let proxy = caller+ .proxy(+ "test.ModuleClient",+ "/test/ModuleClient/workspace_1",+ "test.ModuleClient",+ )+ .unwrap();+ let record = registry::find("tinysearch").unwrap();+ let object = ModuleObjectClient { record, proxy };++ assert_eq!(object.call::<u32>("Sum", (20_u32, 22_u32)).await, Ok(42));+ assert_eq!(root_calls.load(std::sync::atomic::Ordering::SeqCst), 0);+ assert_eq!(child_calls.load(std::sync::atomic::Ordering::SeqCst), 1);+}+#[cfg(feature = "modules")]#[test]fn configured_client_timeout_overrides_the_default_for_fixture_calls() {