Skip to content

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

feat(mcp): read UI resources through tinymcp

oxoxDev88223ecca1df
diff --git a/crates/openhuman-core/src/mcp/module_client/lifecycle.rs b/crates/openhuman-core/src/mcp/module_client/lifecycle.rs
index 15bd234f30..c20a90e5ca 100644
--- a/crates/openhuman-core/src/mcp/module_client/lifecycle.rs
+++ b/crates/openhuman-core/src/mcp/module_client/lifecycle.rs
@@ -146,6 +146,11 @@ impl McpConfiguredClient {
}
}
+ #[cfg(test)]
+ pub(crate) fn with_test_port(data_dir: String, port: Box<dyn McpModulePort>) -> Self {
+ Self::with_port(data_dir, port)
+ }
+
/// Close an already-open agent-scoped client without creating one. A
/// failed close remains in the cache, marked unavailable, so shutdown or
/// a later cleanup attempt can retry the module's retained transition.
diff --git a/crates/openhuman-core/src/mcp/ui/port.rs b/crates/openhuman-core/src/mcp/ui/port.rs
index 736dbbfb36..d2c1505396 100644
--- a/crates/openhuman-core/src/mcp/ui/port.rs
+++ b/crates/openhuman-core/src/mcp/ui/port.rs
@@ -2,9 +2,8 @@
//!
//! [`HostUiPort`] answers them through this workspace's TinyMCP module:
//! installed servers by their connection, configured servers by the static
-//! set. The module contract has no `resources/read`, so a widget document is
-//! only available when the tool result embedded it. Tests substitute their
-//! own port.
+//! set. Widget documents are read through the module's resource members.
+//! Tests substitute their own port.
use std::sync::Arc;
@@ -42,16 +41,31 @@ pub trait UiServerPort: Send + Sync {
/// [`UiServerPort`] over `config`'s TinyMCP module.
pub struct HostUiPort {
config: Arc<Config>,
+ client: Option<Arc<McpConfiguredClient>>,
}
impl HostUiPort {
#[must_use]
pub fn new(config: Arc<Config>) -> Self {
- Self { config }
+ Self {
+ config,
+ client: None,
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn with_client(config: Arc<Config>, client: Arc<McpConfiguredClient>) -> Self {
+ Self {
+ config,
+ client: Some(client),
+ }
}
fn client(&self) -> Option<Arc<McpConfiguredClient>> {
- McpConfiguredClient::for_config(&self.config).ok()
+ match &self.client {
+ Some(client) => Some(Arc::clone(client)),
+ None => McpConfiguredClient::for_config(&self.config).ok(),
+ }
}
async fn is_static(&self, server_id: &str) -> bool {
@@ -107,9 +121,9 @@ impl UiServerPort for HostUiPort {
.await
.ok()?;
let safe = crate::mcp::registry::tools_safe_for_agent(server_id, live);
- safe.iter().find(|candidate| candidate.name == tool)?;
+ let candidate = safe.into_iter().find(|candidate| candidate.name == tool)?;
return Some(UiToolDescriptor {
- meta: None,
+ meta: candidate.meta,
annotations: None,
});
}
@@ -140,6 +154,7 @@ impl UiServerPort for HostUiPort {
description: remote.description.or(remote.title),
name: remote.name,
input_schema: remote.input_schema,
+ meta: None,
})
.collect(),
);
@@ -151,12 +166,28 @@ impl UiServerPort for HostUiPort {
}
async fn read_resource(&self, server_id: &str, uri: &str) -> Result<Vec<Value>, String> {
- tracing::debug!(
- server_id,
- uri,
- "[mcp_ui] resources/read is not part of the TinyMCP module contract"
- );
- Err("this server's widget document is not embedded in its tool result".to_string())
+ let client = self.client().ok_or("MCP module is unavailable")?;
+ let member = if self.is_installed_connected(server_id).await {
+ tinymcp_bus::names::methods::READ_RESOURCE
+ } else {
+ tinymcp_bus::names::methods::STATIC_READ_RESOURCE
+ };
+ let contents: Vec<tinymcp_bus::McpResourceContents> = client
+ .call(&host::client_config(&self.config), member, (server_id, uri))
+ .await
+ .map_err(|error| {
+ tracing::debug!(
+ server_id,
+ uri,
+ ?error,
+ "[mcp_ui] widget resource read failed"
+ );
+ "MCP resource read failed".to_string()
+ })?;
+ contents
+ .iter()
+ .map(|content| serde_json::to_value(content).map_err(|error| error.to_string()))
+ .collect()
}
async fn call_tool(
diff --git a/crates/openhuman-core/src/mcp/ui/port_tests.rs b/crates/openhuman-core/src/mcp/ui/port_tests.rs
index b8d4ff78f3..031093fe68 100644
--- a/crates/openhuman-core/src/mcp/ui/port_tests.rs
+++ b/crates/openhuman-core/src/mcp/ui/port_tests.rs
@@ -31,3 +31,205 @@ async fn calling_a_tool_on_an_unknown_server_fails() {
let (_workspace, port) = port();
assert!(port.call_tool("nowhere", "order", json!({})).await.is_err());
}
+
+mod module_backed {
+ use super::*;
+ use std::sync::Mutex;
+
+ use crate::mcp::module_client::{McpConfiguredClient, McpModulePort};
+ use crate::modules::client::ModuleCallError;
+ use tinymcp_bus::{
+ agent_tools::{McpToolPresentation, PrepareAgentToolsRequest},
+ config::{McpClientConfig, OpenConfiguredResponse, TransitionStatus},
+ names, ServerArgumentsValidation, ValidateServerArgumentsRequest,
+ };
+
+ #[derive(Default)]
+ struct ModulePort {
+ installed: Vec<&'static str>,
+ statics: Vec<&'static str>,
+ fail_reads: bool,
+ members: Mutex<Vec<String>>,
+ }
+
+ impl ModulePort {
+ fn called(&self) -> Vec<String> {
+ self.members.lock().unwrap().clone()
+ }
+ }
+
+ fn resource(uri: &str) -> tinymcp_bus::McpResourceContents {
+ tinymcp_bus::McpResourceContents {
+ uri: uri.to_string(),
+ mime_type: Some("text/html;profile=mcp-app".to_string()),
+ text: Some("<p>card</p>".to_string()),
+ blob: None,
+ meta: Some(json!({"ui": {"prefersBorder": true}})),
+ }
+ }
+
+ #[async_trait]
+ impl McpModulePort for std::sync::Arc<ModulePort> {
+ async fn open_configured(
+ &self,
+ _data_dir: &str,
+ _config: &McpClientConfig,
+ ) -> Result<OpenConfiguredResponse, ModuleCallError> {
+ Ok(OpenConfiguredResponse {
+ object_path: "/workspace/1".to_string(),
+ transition_id: "open-1".to_string(),
+ })
+ }
+
+ 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> {
+ self.members.lock().unwrap().push(member.to_string());
+ let uri = args
+ .get(1)
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ match member {
+ names::methods::STATUS => Ok(serde_json::to_value(
+ self.installed
+ .iter()
+ .map(|id| tinymcp_bus::ConnStatus {
+ server_id: (*id).to_string(),
+ qualified_name: (*id).to_string(),
+ display_name: (*id).to_string(),
+ status: tinymcp_bus::ServerStatus::Connected,
+ tool_count: 1,
+ last_error: None,
+ auth_hint: None,
+ })
+ .collect::<Vec<_>>(),
+ )
+ .unwrap()),
+ names::methods::STATIC_LIST => Ok(json!(self.statics)),
+ names::methods::LIST_TOOLS => Ok(json!([{
+ "name": "show",
+ "description": "Shows a card",
+ "input_schema": {},
+ "_meta": {"ui": {"resourceUri": "ui://card"}}
+ }])),
+ names::methods::READ_RESOURCE | names::methods::STATIC_READ_RESOURCE
+ if self.fail_reads =>
+ {
+ Err(ModuleCallError::ModuleFault)
+ }
+ names::methods::READ_RESOURCE | names::methods::STATIC_READ_RESOURCE => {
+ Ok(serde_json::to_value(vec![resource(&uri)]).unwrap())
+ }
+ _ => Err(ModuleCallError::ModuleFault),
+ }
+ }
+
+ async fn prepare_agent_tools(
+ &self,
+ _request: PrepareAgentToolsRequest,
+ ) -> Result<Vec<McpToolPresentation>, ModuleCallError> {
+ Ok(Vec::new())
+ }
+
+ async fn validate_server_arguments(
+ &self,
+ _request: ValidateServerArgumentsRequest,
+ ) -> Result<ServerArgumentsValidation, ModuleCallError> {
+ Err(ModuleCallError::ModuleFault)
+ }
+ }
+
+ fn port_over(fake: &Arc<ModulePort>) -> HostUiPort {
+ let client = McpConfiguredClient::with_test_port(
+ "/private/workspace".to_string(),
+ Box::new(Arc::clone(fake)),
+ );
+ HostUiPort::with_client(Arc::new(Config::default()), Arc::new(client))
+ }
+
+ #[tokio::test]
+ async fn an_installed_servers_resource_is_read_through_the_module() {
+ let fake = Arc::new(ModulePort {
+ installed: vec!["srv-1"],
+ ..ModulePort::default()
+ });
+ let contents = port_over(&fake)
+ .read_resource("srv-1", "ui://card")
+ .await
+ .expect("contents");
+ assert_eq!(
+ contents,
+ vec![json!({
+ "uri": "ui://card",
+ "mimeType": "text/html;profile=mcp-app",
+ "text": "<p>card</p>",
+ "_meta": {"ui": {"prefersBorder": true}}
+ })]
+ );
+ let called = fake.called();
+ assert!(called.contains(&names::methods::READ_RESOURCE.to_string()));
+ assert!(!called.contains(&names::methods::STATIC_READ_RESOURCE.to_string()));
+ }
+
+ #[tokio::test]
+ async fn a_static_servers_resource_is_read_through_the_static_member() {
+ let fake = Arc::new(ModulePort {
+ statics: vec!["docs"],
+ ..ModulePort::default()
+ });
+ let contents = port_over(&fake)
+ .read_resource("docs", "ui://card")
+ .await
+ .expect("contents");
+ assert_eq!(contents[0]["text"], json!("<p>card</p>"));
+ let called = fake.called();
+ assert!(called.contains(&names::methods::STATIC_READ_RESOURCE.to_string()));
+ assert!(!called.contains(&names::methods::READ_RESOURCE.to_string()));
+ }
+
+ #[tokio::test]
+ async fn a_failed_resource_read_reports_a_generic_error() {
+ let fake = Arc::new(ModulePort {
+ installed: vec!["srv-1"],
+ fail_reads: true,
+ ..ModulePort::default()
+ });
+ let error = port_over(&fake)
+ .read_resource("srv-1", "ui://card")
+ .await
+ .expect_err("read must fail");
+ assert_eq!(error, "MCP resource read failed");
+ }
+
+ #[tokio::test]
+ async fn an_installed_tool_descriptor_carries_the_tools_meta() {
+ let fake = Arc::new(ModulePort {
+ installed: vec!["srv-1"],
+ ..ModulePort::default()
+ });
+ let descriptor = port_over(&fake)
+ .tool_descriptor("srv-1", "show")
+ .await
+ .expect("descriptor");
+ assert_eq!(
+ descriptor.meta,
+ Some(json!({"ui": {"resourceUri": "ui://card"}}))
+ );
+ }
+}