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
feat(mcp): resolve tool UI presentations and serve widget documents
oxoxDevba5b75c4d28c
diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rsindex fad5d9974d..b3231c16b8 100644--- a/crates/openhuman-core/src/core/all.rs+++ b/crates/openhuman-core/src/core/all.rs@@ -358,6 +358,12 @@ fn build_registered_controllers() -> Vec<GroupedController> {DomainGroup::Mcp,crate::mcp::registry::all_mcp_registry_registered_controllers(),);+ #[cfg(feature = "mcp")]+ push(+ &mut controllers,+ DomainGroup::Mcp,+ crate::mcp::ui::all_mcp_ui_registered_controllers(),+ );// Agent definition and prompt inspectionpush(&mut controllers,@@ -815,6 +821,9 @@ pub fn namespace_description(namespace: &str) -> Option<&'static str> {"mcp_clients" => Some("Browse the MCP registries, declare the user's servers in one mcp.json document, manage their connections and credentials, and expose their tools to the agent.",),+ "mcp_ui" => Some(+ "Serve tool-provided widgets their documents and run the tool calls a widget asks for, under the agent's tool policy.",+ ),"decrypt" => Some("Decrypt secure values managed by secret storage."),"doctor" => Some("Run diagnostics for workspace and runtime health."),"hooks" => Some(diff --git a/crates/openhuman-core/src/mcp/host.rs b/crates/openhuman-core/src/mcp/host.rsindex 16f416caca..f570cf8202 100644--- a/crates/openhuman-core/src/mcp/host.rs+++ b/crates/openhuman-core/src/mcp/host.rs@@ -449,6 +449,10 @@ pub fn client_config(config: &Config) -> McpClientConfig {client.client_identity.name = config.mcp_client.client_identity.name.clone();client.client_identity.title = config.mcp_client.client_identity.title.clone();client.client_identity.version = config.mcp_client.client_identity.version.clone();+ #[cfg(feature = "mcp")]+ {+ client.client_identity.capabilities = crate::mcp::ui::client_capabilities();+ }client.registry_auth = config.mcp_client.registry_auth.clone();diff --git a/crates/openhuman-core/src/mcp/mod.rs b/crates/openhuman-core/src/mcp/mod.rsindex 72d75e0426..1180308344 100644--- a/crates/openhuman-core/src/mcp/mod.rs+++ b/crates/openhuman-core/src/mcp/mod.rs@@ -181,6 +181,8 @@ pub mod audit;pub mod host;pub mod registry;pub mod server;+#[cfg(feature = "mcp")]+pub mod ui;/// The Streamable HTTP transport, from the wire contract's implementation.///diff --git a/crates/openhuman-core/src/mcp/ui/cache.rs b/crates/openhuman-core/src/mcp/ui/cache.rsnew file mode 100644index 0000000000..306e31751e--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/cache.rs@@ -0,0 +1,103 @@+//! In-memory widget documents.+//!+//! Two maps, both process-local and bounded: inline documents a tool result+//! embedded (or `show_ui` supplied), addressed by an opaque id, and documents+//! read from a server, keyed by server and `ui://` URI. Nothing here is+//! persisted, so a widget whose document has expired falls back to its links.++use std::collections::HashMap;+use std::sync::LazyLock;+use std::time::{Duration, Instant};++use parking_lot::Mutex;++use super::types::UiResource;++const INLINE_TTL: Duration = Duration::from_secs(6 * 60 * 60);+const READ_TTL: Duration = Duration::from_secs(5 * 60);+const MAX_ENTRIES: usize = 64;++/// An inline document and who may load it.+#[derive(Debug, Clone)]+pub struct InlineEntry {+ pub server_id: Option<String>,+ pub resource: UiResource,+}++struct Timed<T> {+ at: Instant,+ value: T,+}++#[derive(Default)]+struct Store {+ inline: HashMap<String, Timed<InlineEntry>>,+ reads: HashMap<(String, String), Timed<UiResource>>,+}++static STORE: LazyLock<Mutex<Store>> = LazyLock::new(|| Mutex::new(Store::default()));++fn evict<K: Clone + Eq + std::hash::Hash, T>(map: &mut HashMap<K, Timed<T>>, ttl: Duration) {+ map.retain(|_, entry| entry.at.elapsed() < ttl);+ while map.len() >= MAX_ENTRIES {+ let Some(oldest) = map+ .iter()+ .min_by_key(|(_, entry)| entry.at)+ .map(|(key, _)| key.clone())+ else {+ break;+ };+ map.remove(&oldest);+ }+}++/// Stores an inline document and returns its id.+pub fn put_inline(entry: InlineEntry) -> String {+ let id = uuid::Uuid::new_v4().simple().to_string();+ let mut store = STORE.lock();+ evict(&mut store.inline, INLINE_TTL);+ store.inline.insert(+ id.clone(),+ Timed {+ at: Instant::now(),+ value: entry,+ },+ );+ tracing::debug!(inline_id = %id, "[mcp_ui] cached an inline widget document");+ id+}++/// The inline document stored under `id`, while it is fresh.+#[must_use]+pub fn get_inline(id: &str) -> Option<InlineEntry> {+ let store = STORE.lock();+ store+ .inline+ .get(id)+ .filter(|entry| entry.at.elapsed() < INLINE_TTL)+ .map(|entry| entry.value.clone())+}++/// A fresh earlier read of `uri` on `server_id`.+#[must_use]+pub fn get_read(server_id: &str, uri: &str) -> Option<UiResource> {+ let store = STORE.lock();+ store+ .reads+ .get(&(server_id.to_string(), uri.to_string()))+ .filter(|entry| entry.at.elapsed() < READ_TTL)+ .map(|entry| entry.value.clone())+}++/// Remembers a read of `uri` on `server_id`.+pub fn put_read(server_id: &str, uri: &str, resource: UiResource) {+ let mut store = STORE.lock();+ evict(&mut store.reads, READ_TTL);+ store.reads.insert(+ (server_id.to_string(), uri.to_string()),+ Timed {+ at: Instant::now(),+ value: resource,+ },+ );+}diff --git a/crates/openhuman-core/src/mcp/ui/decorate.rs b/crates/openhuman-core/src/mcp/ui/decorate.rsnew file mode 100644index 0000000000..b102d2dc4f--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/decorate.rs@@ -0,0 +1,251 @@+//! Turning a tool result's `mcp_result` envelope into the presentation the+//! chat surface reads, on every path an MCP tool call takes.+//!+//! The envelope is replaced, never forwarded: it carries the server's raw+//! payload, embedded widget HTML included, and only the bounded presentation+//! may reach events and transcripts. A call that offered neither a widget nor+//! a link keeps no metadata at all.++use std::any::Any;+use std::sync::Arc;++use async_trait::async_trait;+use serde_json::Value;+use tinytools::{+ PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolExposure, ToolInjectedArgument,+ ToolPolicy, ToolResult, ToolRunContext, ToolScope, ToolSpec, ToolTimeout,+};++use crate::config::Config;+use crate::mcp::config_servers::McpServerRegistry;+use crate::mcp::host;++use super::resolve::{presentation_from_view, view_from_envelope};+use super::types::MCP_RESULT_KIND;++/// Whether `metadata` is an `mcp_result` envelope.+#[must_use]+pub fn is_envelope(metadata: &Value) -> bool {+ metadata.get("kind").and_then(Value::as_str) == Some(MCP_RESULT_KIND)+}++/// Replaces an `mcp_result` envelope in `result.metadata` with its+/// presentation, or with nothing. Any other metadata is left alone.+pub fn decorate_result(tool_meta: Option<&Value>, tool_input: &Value, result: &mut ToolResult) {+ let Some(metadata) = result.metadata.as_ref() else {+ return;+ };+ if !is_envelope(metadata) {+ return;+ }+ let Some(view) = view_from_envelope(+ metadata,+ tool_meta.cloned(),+ tool_input.clone(),+ &result.text(),+ ) else {+ result.metadata = None;+ return;+ };+ result.metadata = presentation_from_view(&view).map(|presentation| presentation.to_metadata());+}++/// Rewrites every string in `value` through `scrub`.+pub fn scrub_strings(value: &mut Value, scrub: &dyn Fn(&str) -> String) {+ match value {+ Value::String(text) => *text = scrub(text),+ Value::Array(items) => items.iter_mut().for_each(|item| scrub_strings(item, scrub)),+ Value::Object(map) => map.values_mut().for_each(|item| scrub_strings(item, scrub)),+ _ => {}+ }+}++/// Where a wrapped tool's descriptor `_meta` comes from, keyed by the server+/// and tool the envelope names.+pub enum MetaLookup {+ /// Installed servers: the live connection's listing.+ Installed(Arc<Config>),+ /// Configured servers: the registry's last listing.+ Configured(Arc<McpServerRegistry>),+}++impl MetaLookup {+ async fn tool_meta(&self, server: &str, tool: &str) -> Option<Value> {+ match self {+ Self::Installed(config) => {+ let service = host::for_config(config).ok()?;+ service+ .dynamic()+ .connections()+ .tool_meta(server, tool)+ .await+ }+ Self::Configured(registry) => registry.tool_meta(server, tool),+ }+ }+}++/// Which part of a call's arguments the remote tool received.+#[derive(Debug, Clone, Copy)]+pub enum ToolInput {+ /// The arguments are the remote tool's.+ Direct,+ /// The remote arguments sit under this key (`mcp_call_tool`).+ Nested(&'static str),+}++impl ToolInput {+ fn of(self, args: &Value) -> Value {+ match self {+ Self::Direct => args.clone(),+ Self::Nested(key) => args.get(key).cloned().unwrap_or(Value::Null),+ }+ }+}++/// An MCP tool whose results carry a presentation instead of the raw+/// envelope.+pub struct UiAwareTool {+ inner: Box<dyn Tool>,+ lookup: MetaLookup,+ input: ToolInput,+}++impl UiAwareTool {+ #[must_use]+ pub fn new(inner: Box<dyn Tool>, lookup: MetaLookup, input: ToolInput) -> Self {+ Self {+ inner,+ lookup,+ input,+ }+ }++ async fn finish(+ &self,+ args: &Value,+ outcome: anyhow::Result<ToolResult>,+ ) -> anyhow::Result<ToolResult> {+ let mut result = outcome?;+ let Some(metadata) = result.metadata.as_ref().filter(|value| is_envelope(value)) else {+ return Ok(result);+ };+ let server = metadata+ .get("server")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ let tool = metadata+ .get("tool")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ let tool_meta = self.lookup.tool_meta(&server, &tool).await;+ decorate_result(tool_meta.as_ref(), &self.input.of(args), &mut result);+ if result.metadata.as_ref().is_some_and(is_envelope) {+ result.metadata = None;+ }+ Ok(result)+ }+}++#[async_trait]+impl Tool for UiAwareTool {+ fn name(&self) -> &str {+ self.inner.name()+ }+ fn description(&self) -> &str {+ self.inner.description()+ }+ fn parameters_schema(&self) -> Value {+ self.inner.parameters_schema()+ }+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {+ let outcome = self.inner.execute(args.clone()).await;+ self.finish(&args, outcome).await+ }+ async fn execute_with_options(+ &self,+ args: Value,+ options: ToolCallOptions,+ ) -> anyhow::Result<ToolResult> {+ let outcome = self.inner.execute_with_options(args.clone(), options).await;+ self.finish(&args, outcome).await+ }+ async fn execute_with_context(+ &self,+ args: Value,+ options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let outcome = self+ .inner+ .execute_with_context(args.clone(), options, context)+ .await;+ self.finish(&args, outcome).await+ }+ fn policy(&self) -> ToolPolicy {+ self.inner.policy()+ }+ fn injected_arguments(&self) -> Vec<ToolInjectedArgument> {+ self.inner.injected_arguments()+ }+ fn supports_markdown(&self) -> bool {+ self.inner.supports_markdown()+ }+ fn permission_level(&self) -> PermissionLevel {+ self.inner.permission_level()+ }+ fn permission_level_with_args(&self, args: &Value) -> PermissionLevel {+ self.inner.permission_level_with_args(args)+ }+ fn scope(&self) -> ToolScope {+ self.inner.scope()+ }+ fn category(&self) -> ToolCategory {+ self.inner.category()+ }+ fn exposure(&self) -> ToolExposure {+ self.inner.exposure()+ }+ fn family(&self) -> Option<&str> {+ self.inner.family()+ }+ fn is_concurrency_safe(&self, args: &Value) -> bool {+ self.inner.is_concurrency_safe(args)+ }+ fn external_effect(&self) -> bool {+ self.inner.external_effect()+ }+ fn external_effect_with_args(&self, args: &Value) -> bool {+ self.inner.external_effect_with_args(args)+ }+ fn max_result_size_chars(&self) -> Option<usize> {+ self.inner.max_result_size_chars()+ }+ fn timeout_policy(&self, args: &Value) -> ToolTimeout {+ self.inner.timeout_policy(args)+ }+ fn host_extension(&self) -> Option<&(dyn Any + Send + Sync)> {+ self.inner.host_extension()+ }+ fn host_call_extension(&self, args: &Value) -> Option<Box<dyn Any + Send + Sync>> {+ self.inner.host_call_extension(args)+ }+ fn spec(&self) -> ToolSpec {+ self.inner.spec()+ }+ fn display_label(&self, args: &Value) -> Option<String> {+ self.inner.display_label(args)+ }+ fn display_detail(&self, args: &Value) -> Option<String> {+ self.inner.display_detail(args)+ }+ fn return_direct(&self) -> bool {+ self.inner.return_direct()+ }+}++#[cfg(test)]+#[path = "decorate_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/mcp/ui/decorate_tests.rs b/crates/openhuman-core/src/mcp/ui/decorate_tests.rsnew file mode 100644index 0000000000..a1fb282777--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/decorate_tests.rs@@ -0,0 +1,122 @@+use super::*;+use serde_json::json;++struct Fixed(ToolResult);++#[async_trait]+impl Tool for Fixed {+ fn name(&self) -> &str {+ "mcp_shop_order"+ }+ fn description(&self) -> &str {+ "order"+ }+ fn parameters_schema(&self) -> Value {+ json!({"type": "object"})+ }+ fn exposure(&self) -> ToolExposure {+ ToolExposure::Deferred+ }+ async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {+ Ok(self.0.clone())+ }+}++fn no_lookup() -> MetaLookup {+ MetaLookup::Configured(Arc::new(McpServerRegistry::default()))+}++fn envelope(extra: Value) -> Value {+ let mut base = json!({+ "kind": "mcp_result",+ "server": "shop",+ "tool": "order",+ "structured_content": null,+ "meta": null,+ "resources": [],+ "outcome": {"kind": "mcp_call", "server": "shop", "tool": "order", "ok": true}+ });+ base.as_object_mut()+ .unwrap()+ .extend(extra.as_object().unwrap().clone());+ base+}++fn result_with(metadata: Value, text: &str) -> ToolResult {+ let mut result = ToolResult::success(text);+ result.metadata = Some(metadata);+ result+}++#[tokio::test]+async fn widget_tool_emits_mcp_ui_and_keeps_text() {+ let tool = UiAwareTool::new(+ Box::new(Fixed(result_with(+ envelope(json!({"meta": {"ui": {"resourceUri": "ui://shop/cart"}}})),+ "Order placed",+ ))),+ no_lookup(),+ ToolInput::Direct,+ );+ assert_eq!(tool.exposure(), ToolExposure::Deferred);+ let result = tool.execute(json!({"item": "dosa"})).await.unwrap();+ assert_eq!(result.text(), "Order placed");+ let metadata = result.metadata.expect("presentation");+ assert_eq!(metadata["kind"], "mcp_ui");+ assert_eq!(metadata["resource_uri"], "ui://shop/cart");+ assert_eq!(metadata["tool_input"], json!({"item": "dosa"}));+ assert_eq!(metadata["server_id"], "shop");+}++#[tokio::test]+async fn envelope_without_ui_or_links_is_dropped() {+ let tool = UiAwareTool::new(+ Box::new(Fixed(result_with(envelope(json!({})), "Nothing to show"))),+ no_lookup(),+ ToolInput::Direct,+ );+ let result = tool.execute(json!({})).await.unwrap();+ assert!(result.metadata.is_none());+}++#[tokio::test]+async fn link_in_structured_content_is_surfaced() {+ let tool = UiAwareTool::new(+ Box::new(Fixed(result_with(+ envelope(json!({"structured_content": {"pay": "phonepe://pay?o=1"}})),+ "ok",+ ))),+ no_lookup(),+ ToolInput::Nested("arguments"),+ );+ let metadata = tool.execute(json!({})).await.unwrap().metadata.unwrap();+ assert_eq!(metadata["links"][0]["url"], "phonepe://pay?o=1");+ assert_eq!(metadata["links"][0]["kind"], "handoff");+}++#[test]+fn other_metadata_is_left_alone() {+ let mut result = result_with(json!({"kind": "web_search", "hits": []}), "x");+ decorate_result(None, &json!({}), &mut result);+ assert_eq!(result.metadata.unwrap()["kind"], "web_search");+}++#[test]+fn malformed_envelope_is_removed() {+ let mut result = result_with(+ json!({"kind": "mcp_result", "resources": [{"text": "<html>"}]}),+ "x",+ );+ decorate_result(None, &json!({}), &mut result);+ assert!(result.metadata.is_none());+}++#[test]+fn scrub_strings_rewrites_nested_values() {+ let mut value = json!({"a": ["tok-SECRET"], "b": {"c": "SECRET"}, "n": 1});+ scrub_strings(&mut value, &|text| text.replace("SECRET", "[redacted]"));+ assert_eq!(+ value,+ json!({"a": ["tok-[redacted]"], "b": {"c": "[redacted]"}, "n": 1})+ );+}diff --git a/crates/openhuman-core/src/mcp/ui/links.rs b/crates/openhuman-core/src/mcp/ui/links.rsnew file mode 100644index 0000000000..49904c7d3e--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/links.rs@@ -0,0 +1,142 @@+//! Links a tool result offers: payment pages, deep links, sign-in URLs.+//!+//! Found in the structured content and the text, classified, and capped. A+//! scheme that could run script or reach this process is dropped outright.++use std::sync::LazyLock;++use regex::Regex;+use serde_json::Value;++use super::types::{UiLink, UiLinkKind};++/// The most links one result surfaces.+pub const MAX_LINKS: usize = 5;++const MAX_URL_LEN: usize = 2048;+const MAX_WALK_DEPTH: usize = 8;+const MAX_WALK_STRINGS: usize = 512;++const BLOCKED_SCHEMES: &[&str] = &[+ "javascript",+ "data",+ "vbscript",+ "file",+ "blob",+ "about",+ "tauri",+ "ipc",+ "asset",+ "ohwidget",+ "filesystem",+ "chrome",+ "chrome-extension",+ "view-source",+ "ws",+ "wss",+ "ftp",+ "openhuman",+];++static URL_RE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r#"(?i)\b([a-z][a-z0-9+.\-]{1,31})://[^\s"'<>\x60{}|\\^\[\]]+"#)+ .expect("link pattern compiles")+});++/// How a link is treated, by scheme. `None` for a blocked or malformed one.+#[must_use]+pub fn classify(url: &str) -> Option<UiLinkKind> {+ let (scheme, rest) = url.split_once(':')?;+ let scheme = scheme.to_ascii_lowercase();+ if scheme.is_empty()+ || !scheme+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))+ || !scheme.starts_with(|c: char| c.is_ascii_alphabetic())+ {+ return None;+ }+ if BLOCKED_SCHEMES.contains(&scheme.as_str()) || rest.trim().is_empty() {+ return None;+ }+ if url.chars().any(char::is_control) || url.len() > MAX_URL_LEN {+ return None;+ }+ match scheme.as_str() {+ "http" | "https" => {+ let parsed = url::Url::parse(url).ok()?;+ parsed.host_str().filter(|host| !host.is_empty())?;+ Some(UiLinkKind::External)+ }+ _ => Some(UiLinkKind::Handoff),+ }+}++/// Every allowed link in `structured` and `text`, deduplicated, at most+/// [`MAX_LINKS`], structured content first.+#[must_use]+pub fn extract_links(structured: Option<&Value>, text: &str) -> Vec<UiLink> {+ let mut out: Vec<UiLink> = Vec::new();+ let mut strings = Vec::new();+ if let Some(value) = structured {+ collect_strings(value, 0, &mut strings);+ }+ strings.push(text);+ for haystack in strings {+ for found in URL_RE.find_iter(haystack) {+ if out.len() >= MAX_LINKS {+ return out;+ }+ let url = trim_trailing(found.as_str());+ let Some(kind) = classify(url) else {+ tracing::trace!("[mcp_ui] dropped a blocked link");+ continue;+ };+ if out.iter().any(|link| link.url == url) {+ continue;+ }+ out.push(UiLink {+ url: url.to_string(),+ kind,+ });+ }+ }+ out+}++fn collect_strings<'a>(value: &'a Value, depth: usize, out: &mut Vec<&'a str>) {+ if depth > MAX_WALK_DEPTH || out.len() >= MAX_WALK_STRINGS {+ return;+ }+ match value {+ Value::String(text) => out.push(text),+ Value::Array(items) => items+ .iter()+ .for_each(|item| collect_strings(item, depth + 1, out)),+ Value::Object(map) => map+ .values()+ .for_each(|item| collect_strings(item, depth + 1, out)),+ _ => {}+ }+}++fn trim_trailing(url: &str) -> &str {+ let mut end = url.len();+ loop {+ let trimmed = &url[..end];+ let Some(last) = trimmed.chars().last() else {+ return trimmed;+ };+ let unbalanced_paren =+ last == ')' && trimmed.matches('(').count() < trimmed.matches(')').count();+ if matches!(last, '.' | ',' | ';' | ':' | '!' | '?' | '*') || unbalanced_paren {+ end -= last.len_utf8();+ } else {+ return trimmed;+ }+ }+}++#[cfg(test)]+#[path = "links_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/mcp/ui/links_tests.rs b/crates/openhuman-core/src/mcp/ui/links_tests.rsnew file mode 100644index 0000000000..797386d891--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/links_tests.rs@@ -0,0 +1,82 @@+use super::*;+use serde_json::json;++fn urls(links: &[UiLink]) -> Vec<&str> {+ links.iter().map(|link| link.url.as_str()).collect()+}++#[test]+fn keeps_https_and_handoff_schemes() {+ let text =+ "Pay at https://pay.example.com/o/1 or phonepe://pay?id=1 or upi://pay?pa=a@b&am=10.";+ let links = extract_links(None, text);+ assert_eq!(+ urls(&links),+ vec![+ "https://pay.example.com/o/1",+ "phonepe://pay?id=1",+ "upi://pay?pa=a@b&am=10"+ ]+ );+ assert_eq!(links[0].kind, UiLinkKind::External);+ assert_eq!(links[1].kind, UiLinkKind::Handoff);+ assert_eq!(links[2].kind, UiLinkKind::Handoff);+}++#[test]+fn drops_dangerous_schemes() {+ let text = "javascript://x%0Aalert(1) data://text/html,hi file:///etc/passwd tauri://localhost ohwidget://x blob://y";+ assert!(extract_links(None, text).is_empty());+}++#[test]+fn classify_table() {+ assert_eq!(classify("https://a.com"), Some(UiLinkKind::External));+ assert_eq!(classify("http://a.com/x"), Some(UiLinkKind::External));+ assert_eq!(classify("tez://upi/pay"), Some(UiLinkKind::Handoff));+ assert_eq!(classify("JAVASCRIPT:alert(1)"), None);+ assert_eq!(classify("data:text/html,x"), None);+ assert_eq!(classify("https://"), None);+ assert_eq!(classify("nonsense"), None);+ assert_eq!(classify("1http://a.com"), None);+}++#[test]+fn structured_content_comes_first_and_dedupes() {+ let structured = json!({+ "order": {"a_payment_url": "https://pay.example.com/o/1", "b_deep": ["phonepe://pay?id=1"]}+ });+ let links = extract_links(+ Some(&structured),+ "See https://pay.example.com/o/1 and https://other.example.com.",+ );+ assert_eq!(+ urls(&links),+ vec![+ "https://pay.example.com/o/1",+ "phonepe://pay?id=1",+ "https://other.example.com"+ ]+ );+}++#[test]+fn caps_at_max_links() {+ let text = (0..10)+ .map(|i| format!("https://e{i}.example.com"))+ .collect::<Vec<_>>()+ .join(" ");+ assert_eq!(extract_links(None, &text).len(), MAX_LINKS);+}++#[test]+fn trims_markdown_punctuation_and_unbalanced_parens() {+ let links = extract_links(+ None,+ "[pay](https://pay.example.com/x) (see https://a.example.com/p_(1)).",+ );+ assert_eq!(+ urls(&links),+ vec!["https://pay.example.com/x", "https://a.example.com/p_(1)"]+ );+}diff --git a/crates/openhuman-core/src/mcp/ui/mod.rs b/crates/openhuman-core/src/mcp/ui/mod.rsnew file mode 100644index 0000000000..aa7807505a--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/mod.rs@@ -0,0 +1,40 @@+//! Tool-provided UI in the chat: MCP Apps widgets, OpenAI Apps SDK widgets,+//! skill views, and the links a tool result offers.+//!+//! - [`resolve`] reads one call's descriptor `_meta` and result into a+//! [`types::McpUiPresentation`], the metadata the chat surface renders.+//! - [`decorate`] applies that to every MCP tool path.+//! - [`ops`] / `schemas` serve a widget its document and run the tool calls+//! it asks for (`mcp_ui` namespace), through [`port::UiServerPort`].+//! - [`tools`] is `show_ui`, the host tool a skill renders HTML with.+//!+//! Widget HTML stays in [`cache`], in memory; events and transcripts carry+//! only the bounded presentation.++pub mod cache;+pub mod decorate;+pub mod links;+pub mod ops;+pub mod port;+pub mod resolve;+mod schemas;+pub mod tools;+pub mod types;++pub use decorate::{decorate_result, UiAwareTool};+pub use schemas::{+ all_controller_schemas as all_mcp_ui_controller_schemas,+ all_registered_controllers as all_mcp_ui_registered_controllers,+};+pub use tools::ShowUiTool;++/// The `initialize` capabilities this host advertises: MCP Apps support.+#[must_use]+pub fn client_capabilities() -> serde_json::Value {+ let mut extensions = serde_json::Map::new();+ extensions.insert(+ types::MCP_APPS_EXTENSION.to_string(),+ serde_json::json!({ "mimeTypes": [types::MCP_APP_MIME] }),+ );+ serde_json::json!({ "extensions": extensions })+}diff --git a/crates/openhuman-core/src/mcp/ui/ops.rs b/crates/openhuman-core/src/mcp/ui/ops.rsnew file mode 100644index 0000000000..2b5b5ce9b5--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/ops.rs@@ -0,0 +1,209 @@+//! The `mcp_ui` operations: serving a widget its document and running the+//! tool calls a widget asks for.+//!+//! A widget is untrusted page content. Everything it reaches goes through+//! here, under the same scan and policy the agent's own calls get, and a call+//! that can change something waits for the user unless the tool declares+//! itself read-only.++use std::time::Instant;++use serde_json::{json, Value};++use crate::core::bus::BUS;+use crate::core::events::DomainEvent;+use crate::core::Outcome;+use crate::security::{SecurityPolicy, ToolOperation};++use super::cache;+use super::port::UiServerPort;+use super::resolve::{is_ui_uri, resource_from_contents};+use super::types::{UiResource, UiToolDescriptor};++fn require(value: Option<String>, field: &str) -> Result<String, String> {+ value+ .as_deref()+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_string)+ .ok_or_else(|| format!("{field} must not be empty"))+}++fn encode(resource: &UiResource) -> Result<Value, String> {+ serde_json::to_value(resource).map_err(|error| format!("serialization error: {error}"))+}++/// The document a widget frame loads: an inline one by `inline_id`, or the+/// `ui://` resource `uri` on `server_id`.+///+/// # Errors+///+/// When the id is unknown or expired, the URI is not `ui://`, the server is+/// not available, or the document is not acceptable HTML.+pub async fn resource_read(+ port: &dyn UiServerPort,+ server_id: Option<String>,+ uri: Option<String>,+ inline_id: Option<String>,+) -> Result<Outcome<Value>, String> {+ if let Some(id) = inline_id.filter(|id| !id.trim().is_empty()) {+ let entry = cache::get_inline(id.trim())+ .ok_or_else(|| "this widget is no longer available".to_string())?;+ if let (Some(owner), Some(asked)) = (entry.server_id.as_deref(), server_id.as_deref()) {+ if owner != asked.trim() {+ return Err("this widget belongs to another server".to_string());+ }+ }+ tracing::debug!(inline_id = %id, "[mcp_ui] served an inline widget document");+ return Ok(Outcome::new(+ encode(&entry.resource)?,+ vec![format!("resource_read inline_id={id}")],+ ));+ }++ let server_id = require(server_id, "server_id")?;+ let uri = require(uri, "uri")?;+ if !is_ui_uri(&uri) {+ return Err("only ui:// resources can be shown".to_string());+ }+ if !port.is_available(&server_id).await {+ return Err(format!("MCP server `{server_id}` is not connected"));+ }+ if let Some(resource) = cache::get_read(&server_id, &uri) {+ tracing::debug!(server_id, uri, "[mcp_ui] widget document served from cache");+ return Ok(Outcome::new(+ encode(&resource)?,+ vec![format!("resource_read server_id={server_id} cached")],+ ));+ }+ let contents = port.read_resource(&server_id, &uri).await?;+ let resource = resource_from_contents(&contents, &uri)?;+ tracing::debug!(+ server_id,+ uri,+ bytes = resource.html.len(),+ connect = resource.csp.connect_domains.len(),+ "[mcp_ui] read a widget document"+ );+ cache::put_read(&server_id, &uri, resource.clone());+ Ok(Outcome::new(+ encode(&resource)?,+ vec![format!("resource_read server_id={server_id}")],+ ))+}++/// Whether a widget may call this tool: absent `_meta.ui.visibility` means+/// both the model and the app may; otherwise it must name `"app"`.+#[must_use]+pub fn visible_to_app(descriptor: &UiToolDescriptor) -> bool {+ match descriptor+ .meta+ .as_ref()+ .and_then(|meta| meta.pointer("/ui/visibility"))+ {+ None | Some(Value::Null) => true,+ Some(Value::Array(items)) => items.iter().any(|item| item.as_str() == Some("app")),+ Some(_) => false,+ }+}++/// Whether the tool declares it changes nothing.+#[must_use]+pub fn is_read_only(descriptor: &UiToolDescriptor) -> bool {+ descriptor+ .annotations+ .as_ref()+ .and_then(|annotations| annotations.get("readOnlyHint"))+ .and_then(Value::as_bool)+ .unwrap_or(false)+}++/// A tool call a widget asked for.+///+/// Answers `requires_confirmation: true` without calling when the tool is+/// not read-only and the user has not confirmed it.+///+/// # Errors+///+/// When the server is not available, the tool is not offered, hidden from+/// apps, or blocked by policy.+pub async fn tool_call(+ port: &dyn UiServerPort,+ security: &SecurityPolicy,+ server_id: Option<String>,+ tool_name: Option<String>,+ arguments: Option<Value>,+ confirmed: bool,+) -> Result<Outcome<Value>, String> {+ let server_id = require(server_id, "server_id")?;+ let tool_name = require(tool_name, "tool_name")?;+ let arguments = match arguments {+ None | Some(Value::Null) => json!({}),+ Some(value @ Value::Object(_)) => value,+ Some(_) => return Err("arguments must be an object".to_string()),+ };+ if !port.is_available(&server_id).await {+ return Err(format!("MCP server `{server_id}` is not connected"));+ }+ let descriptor = port+ .tool_descriptor(&server_id, &tool_name)+ .await+ .ok_or_else(|| format!("`{tool_name}` is not offered by this server"))?;+ if !visible_to_app(&descriptor) {+ tracing::debug!(+ server_id,+ tool_name,+ "[mcp_ui] widget asked for a model-only tool"+ );+ return Err(format!("`{tool_name}` cannot be called from a widget"));+ }+ let read_only = is_read_only(&descriptor);+ if !read_only && !confirmed {+ tracing::debug!(+ server_id,+ tool_name,+ "[mcp_ui] widget tool call needs confirmation"+ );+ return Ok(Outcome::new(+ json!({"requires_confirmation": true, "read_only": false}),+ vec![format!(+ "tool_call server_id={server_id} tool={tool_name} awaiting confirmation"+ )],+ ));+ }+ let operation = if read_only {+ ToolOperation::Read+ } else {+ ToolOperation::Act+ };+ security.enforce_tool_operation(operation, &format!("mcp_ui:{server_id}/{tool_name}"))?;++ let start = Instant::now();+ let result = port.call_tool(&server_id, &tool_name, arguments).await;+ let elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);+ BUS.publish(DomainEvent::McpClientToolExecuted {+ server_id: server_id.clone(),+ tool_name: tool_name.clone(),+ success: result.is_ok(),+ elapsed_ms,+ });+ tracing::debug!(+ server_id,+ tool_name,+ elapsed_ms,+ ok = result.is_ok(),+ "[mcp_ui] widget tool call"+ );+ let raw = result?;+ let is_error = raw.get("isError").and_then(Value::as_bool).unwrap_or(false);+ Ok(Outcome::new(+ json!({"requires_confirmation": false, "read_only": read_only, "result": raw, "is_error": is_error}),+ vec![format!(+ "tool_call server_id={server_id} tool={tool_name} elapsed_ms={elapsed_ms}"+ )],+ ))+}++#[cfg(test)]+#[path = "ops_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/mcp/ui/ops_tests.rs b/crates/openhuman-core/src/mcp/ui/ops_tests.rsnew file mode 100644index 0000000000..1f512ec363--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/ops_tests.rs@@ -0,0 +1,254 @@+use super::*;+use std::sync::atomic::{AtomicUsize, Ordering};++use async_trait::async_trait;+use serde_json::json;++use crate::mcp::ui::cache::{put_inline, InlineEntry};+use crate::mcp::ui::types::UiCsp;+use crate::security::AutonomyLevel;++#[derive(Default)]+struct FakePort {+ descriptor: Option<UiToolDescriptor>,+ contents: Vec<Value>,+ calls: AtomicUsize,+ reads: AtomicUsize,+}++#[async_trait]+impl UiServerPort for FakePort {+ async fn is_available(&self, server_id: &str) -> bool {+ server_id == "srv"+ }+ async fn tool_descriptor(&self, _server_id: &str, tool: &str) -> Option<UiToolDescriptor> {+ (tool == "known").then(|| self.descriptor.clone().unwrap_or_default())+ }+ async fn read_resource(&self, _server_id: &str, _uri: &str) -> Result<Vec<Value>, String> {+ self.reads.fetch_add(1, Ordering::SeqCst);+ Ok(self.contents.clone())+ }+ async fn call_tool(&self, _s: &str, _t: &str, arguments: Value) -> Result<Value, String> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ Ok(json!({"content": [], "structuredContent": arguments}))+ }+}++fn read_only() -> UiToolDescriptor {+ UiToolDescriptor {+ meta: None,+ annotations: Some(json!({"readOnlyHint": true})),+ }+}++#[tokio::test]+async fn resource_read_rejects_non_ui_and_unconnected() {+ let port = FakePort::default();+ let err = resource_read(&port, Some("srv".into()), Some("https://x/y".into()), None)+ .await+ .unwrap_err();+ assert!(err.contains("ui://"));+ let err = resource_read(&port, Some("other".into()), Some("ui://x".into()), None)+ .await+ .unwrap_err();+ assert!(err.contains("not connected"));+}++#[tokio::test]+async fn resource_read_rejects_oversize_and_caches() {+ let port = FakePort {+ contents: vec![+ json!({"uri": "ui://big", "mimeType": "text/html", "text": "x".repeat(crate::mcp::ui::resolve::MAX_RESOURCE_BYTES + 1)}),+ ],+ ..FakePort::default()+ };+ assert!(+ resource_read(&port, Some("srv".into()), Some("ui://big".into()), None)+ .await+ .is_err()+ );++ let port = FakePort {+ contents: vec![json!({"uri": "ui://ok-cache", "mimeType": "text/html", "text": "<p/>"})],+ ..FakePort::default()+ };+ for _ in 0..2 {+ let out = resource_read(+ &port,+ Some("srv".into()),+ Some("ui://ok-cache".into()),+ None,+ )+ .await+ .unwrap();+ assert_eq!(out.value["html"], "<p/>");+ }+ assert_eq!(port.reads.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn inline_read_checks_owner() {+ let id = put_inline(InlineEntry {+ server_id: Some("srv".into()),+ resource: UiResource {+ html: "<i/>".into(),+ mime_type: "text/html".into(),+ csp: UiCsp::default(),+ permissions: None,+ prefers_border: false,+ },+ });+ let port = FakePort::default();+ let out = resource_read(&port, Some("srv".into()), None, Some(id.clone()))+ .await+ .unwrap();+ assert_eq!(out.value["html"], "<i/>");+ assert!(resource_read(&port, Some("other".into()), None, Some(id))+ .await+ .is_err());+ assert!(resource_read(&port, None, None, Some("missing".into()))+ .await+ .is_err());+}++#[tokio::test]+async fn tool_call_requires_confirmation_unless_read_only() {+ let port = FakePort::default();+ let policy = SecurityPolicy::default();+ let out = tool_call(+ &port,+ &policy,+ Some("srv".into()),+ Some("known".into()),+ None,+ false,+ )+ .await+ .unwrap();+ assert_eq!(out.value["requires_confirmation"], true);+ assert_eq!(port.calls.load(Ordering::SeqCst), 0);++ let out = tool_call(+ &port,+ &policy,+ Some("srv".into()),+ Some("known".into()),+ Some(json!({"a": 1})),+ true,+ )+ .await+ .unwrap();+ assert_eq!(out.value["requires_confirmation"], false);+ assert_eq!(out.value["result"]["structuredContent"], json!({"a": 1}));+ assert_eq!(port.calls.load(Ordering::SeqCst), 1);++ let port = FakePort {+ descriptor: Some(read_only()),+ ..FakePort::default()+ };+ let out = tool_call(+ &port,+ &policy,+ Some("srv".into()),+ Some("known".into()),+ None,+ false,+ )+ .await+ .unwrap();+ assert_eq!(out.value["read_only"], true);+ assert_eq!(port.calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn tool_call_rejects_unknown_hidden_and_cross_server() {+ let policy = SecurityPolicy::default();+ let port = FakePort::default();+ assert!(tool_call(+ &port,+ &policy,+ Some("other".into()),+ Some("known".into()),+ None,+ true+ )+ .await+ .is_err());+ assert!(tool_call(+ &port,+ &policy,+ Some("srv".into()),+ Some("unknown".into()),+ None,+ true+ )+ .await+ .is_err());+ assert!(tool_call(+ &port,+ &policy,+ Some("srv".into()),+ Some("known".into()),+ Some(json!([1])),+ true+ )+ .await+ .is_err());++ let hidden = FakePort {+ descriptor: Some(UiToolDescriptor {+ meta: Some(json!({"ui": {"visibility": ["model"]}})),+ annotations: Some(json!({"readOnlyHint": true})),+ }),+ ..FakePort::default()+ };+ let err = tool_call(+ &hidden,+ &policy,+ Some("srv".into()),+ Some("known".into()),+ None,+ true,+ )+ .await+ .unwrap_err();+ assert!(err.contains("widget"));+ assert_eq!(hidden.calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn tool_call_honours_policy_denial() {+ let port = FakePort::default();+ let policy = SecurityPolicy {+ autonomy: AutonomyLevel::ReadOnly,+ ..SecurityPolicy::default()+ };+ let err = tool_call(+ &port,+ &policy,+ Some("srv".into()),+ Some("known".into()),+ None,+ true,+ )+ .await+ .unwrap_err();+ assert!(err.contains("read-only"));+ assert_eq!(port.calls.load(Ordering::SeqCst), 0);+}++#[test]+fn visibility_table() {+ let with = |meta| UiToolDescriptor {+ meta: Some(meta),+ annotations: None,+ };+ assert!(visible_to_app(&UiToolDescriptor::default()));+ assert!(visible_to_app(&with(+ json!({"ui": {"visibility": ["model", "app"]}})+ )));+ assert!(!visible_to_app(&with(+ json!({"ui": {"visibility": ["model"]}})+ )));+ assert!(!visible_to_app(&with(json!({"ui": {"visibility": "app"}}))));+}diff --git a/crates/openhuman-core/src/mcp/ui/port.rs b/crates/openhuman-core/src/mcp/ui/port.rsnew file mode 100644index 0000000000..b670625ae8--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/port.rs@@ -0,0 +1,152 @@+//! The server operations widget RPCs need, behind a seam.+//!+//! [`HostUiPort`] answers them from this workspace's MCP host: installed+//! servers through the live connection map, configured servers through the+//! static set. Tests substitute their own.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::Value;++use crate::config::Config;+use crate::mcp::host;+use crate::mcp::registry::connections;++use super::types::UiToolDescriptor;++/// What a widget RPC asks of an MCP server.+#[async_trait]+pub trait UiServerPort: Send + Sync {+ /// Whether `server_id` is connected (installed) or configured (static).+ async fn is_available(&self, server_id: &str) -> bool;++ /// The live, scan-clean descriptor of `tool`, or `None` when the server+ /// does not offer it now.+ async fn tool_descriptor(&self, server_id: &str, tool: &str) -> Option<UiToolDescriptor>;++ /// A `resources/read` reply's `contents`.+ async fn read_resource(&self, server_id: &str, uri: &str) -> Result<Vec<Value>, String>;++ /// A `tools/call` reply, as the server sent it.+ async fn call_tool(+ &self,+ server_id: &str,+ tool: &str,+ arguments: Value,+ ) -> Result<Value, String>;+}++/// [`UiServerPort`] over `config`'s MCP host.+pub struct HostUiPort {+ config: Arc<Config>,+}++impl HostUiPort {+ #[must_use]+ pub fn new(config: Arc<Config>) -> Self {+ Self { config }+ }++ fn is_static(&self, server_id: &str) -> bool {+ host::static_registry(&self.config).get(server_id).is_some()+ }+}++#[async_trait]+impl UiServerPort for HostUiPort {+ async fn is_available(&self, server_id: &str) -> bool {+ connections::is_connected_for_config(&self.config, server_id).await+ || self.is_static(server_id)+ }++ async fn tool_descriptor(&self, server_id: &str, tool: &str) -> Option<UiToolDescriptor> {+ if let Some(live) = connections::server_tools_for_config(&self.config, server_id).await {+ let safe = crate::mcp::registry::tools_safe_for_agent(server_id, live);+ safe.iter().find(|candidate| candidate.name == tool)?;+ let service = host::for_config(&self.config).ok()?;+ let meta = service+ .dynamic()+ .connections()+ .tool_meta(server_id, tool)+ .await;+ return Some(UiToolDescriptor {+ meta,+ annotations: None,+ });+ }+ let registry = host::static_registry(&self.config);+ registry.get(server_id)?;+ let listed = registry+ .list_tools(server_id)+ .await+ .map_err(|error| {+ tracing::debug!(server_id, %error, "[mcp_ui] could not list tools");+ })+ .ok()?;+ let safe = crate::mcp::registry::tools_safe_for_agent(+ server_id,+ listed+ .into_iter()+ .map(|remote| {+ let description = remote.display_description();+ tinymcp_bus::McpTool {+ name: remote.name,+ description,+ input_schema: remote.input_schema,+ }+ })+ .collect(),+ );+ safe.iter().find(|candidate| candidate.name == tool)?;+ Some(UiToolDescriptor {+ meta: registry.tool_meta(server_id, tool),+ annotations: None,+ })+ }++ async fn read_resource(&self, server_id: &str, uri: &str) -> Result<Vec<Value>, String> {+ let contents = if connections::is_connected_for_config(&self.config, server_id).await {+ host::for_config(&self.config)+ .map_err(|error| error.to_string())?+ .dynamic()+ .connections()+ .read_resource(server_id, uri)+ .await+ } else {+ host::static_registry(&self.config)+ .read_resource(server_id, uri)+ .await+ }+ .map_err(|error| {+ tracing::debug!(server_id, %error, "[mcp_ui] resources/read failed");+ error.to_string()+ })?;+ contents+ .iter()+ .map(|entry| serde_json::to_value(entry).map_err(|error| error.to_string()))+ .collect()+ }++ async fn call_tool(+ &self,+ server_id: &str,+ tool: &str,+ arguments: Value,+ ) -> Result<Value, String> {+ if connections::is_connected_for_config(&self.config, server_id).await {+ let service = host::for_config(&self.config).map_err(|error| error.to_string())?;+ return service+ .dynamic()+ .tool_call(server_id, tool, arguments)+ .await+ .map(|outcome| outcome.result)+ .map_err(|error| error.to_string());+ }+ host::static_registry(&self.config)+ .call_tool(server_id, tool, arguments)+ .await+ .map(|result| result.raw_result)+ .map_err(|error| error.to_string())+ }+}diff --git a/crates/openhuman-core/src/mcp/ui/resolve.rs b/crates/openhuman-core/src/mcp/ui/resolve.rsnew file mode 100644index 0000000000..01bde19c7a--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/resolve.rs@@ -0,0 +1,399 @@+//! Turning one tool call into what the chat surface shows for it.+//!+//! Pure over the call's JSON: the tool descriptor's `_meta`, the result's+//! structured content, `_meta` and embedded resources, and its text. The one+//! side effect is caching an embedded widget document so the frame can load+//! it by id.++use base64::Engine as _;+use serde_json::Value;++use super::cache::{self, InlineEntry};+use super::links::extract_links;+use super::types::{+ McpUiPresentation, UiCallView, UiCsp, UiFlavor, UiResource, MCP_RESULT_KIND, MCP_UI_KIND,+};++/// The largest widget document served to a frame.+pub const MAX_RESOURCE_BYTES: usize = 2 * 1024 * 1024;+/// The largest structured content forwarded with a presentation.+pub const MAX_STRUCTURED_BYTES: usize = 64 * 1024;+const MAX_META_BYTES: usize = 16 * 1024;+const MAX_INPUT_BYTES: usize = 16 * 1024;+const MAX_CSP_DOMAINS: usize = 32;++/// Where a frame's document comes from.+#[derive(Debug, Clone, PartialEq)]+pub enum UiSource {+ /// A `ui://` resource on the tool's server.+ Uri { uri: String, flavor: UiFlavor },+ /// A document the result embedded.+ Embedded { resource: Value },+}++/// Whether `uri` is a widget resource URI.+#[must_use]+pub fn is_ui_uri(uri: &str) -> bool {+ uri.len() > "ui://".len()+ && uri+ .get(..5)+ .is_some_and(|scheme| scheme.eq_ignore_ascii_case("ui://"))+}++fn is_html_mime(mime: &str) -> bool {+ let lowered = mime.trim().to_ascii_lowercase();+ lowered.starts_with("text/html")+}++fn meta_str<'a>(meta: Option<&'a Value>, path: &[&str]) -> Option<&'a str> {+ let mut cursor = meta?;+ for key in path {+ cursor = cursor.get(*key)?;+ }+ cursor.as_str()+}++/// The resource a tool's UI loads from, by precedence: `_meta.ui.resourceUri`,+/// the legacy `_meta["ui/resourceUri"]`, the Apps SDK+/// `_meta["openai/outputTemplate"]`, then an embedded `ui://` HTML resource.+#[must_use]+pub fn select_source(view: &UiCallView) -> Option<UiSource> {+ let metas = [view.tool_meta.as_ref(), view.result_meta.as_ref()];+ let candidates: [(&[&str], UiFlavor); 3] = [+ (&["ui", "resourceUri"], UiFlavor::McpApps),+ (&["ui/resourceUri"], UiFlavor::McpApps),+ (&["openai/outputTemplate"], UiFlavor::AppsSdk),+ ];+ for (path, flavor) in candidates {+ for meta in metas {+ if let Some(uri) = meta_str(meta, path).map(str::trim) {+ if is_ui_uri(uri) {+ return Some(UiSource::Uri {+ uri: uri.to_string(),+ flavor,+ });+ }+ tracing::debug!(tool = %view.tool, "[mcp_ui] ignored a non-ui:// resource URI");+ }+ }+ }+ view.resources+ .iter()+ .find(|resource| {+ let uri = resource.get("uri").and_then(Value::as_str).unwrap_or("");+ let mime = resource+ .get("mimeType")+ .and_then(Value::as_str)+ .unwrap_or("");+ is_ui_uri(uri) && is_html_mime(mime)+ })+ .map(|resource| UiSource::Embedded {+ resource: resource.clone(),+ })+}++fn bounded(value: Option<&Value>, limit: usize) -> Option<Value> {+ let value = value.filter(|value| !value.is_null())?;+ let size = serde_json::to_vec(value).map(|bytes| bytes.len()).ok()?;+ if size > limit {+ tracing::debug!(size, limit, "[mcp_ui] dropped an oversized field");+ return None;+ }+ Some(value.clone())+}++/// The presentation for one call, or `None` when it offered neither a widget+/// nor a link.+#[must_use]+pub fn presentation_from_view(view: &UiCallView) -> Option<McpUiPresentation> {+ let links = extract_links(view.structured_content.as_ref(), &view.text);+ let source = select_source(view);+ let (resource_uri, inline_id, flavor) = match source {+ Some(UiSource::Uri { uri, flavor }) => {+ if let Some(embedded) = view+ .resources+ .iter()+ .find(|resource| resource.get("uri").and_then(Value::as_str) == Some(uri.as_str()))+ {+ if let Ok(resource) = resource_from_contents(std::slice::from_ref(embedded), &uri) {+ cache::put_read(&view.server_id, &uri, resource);+ }+ }+ (Some(uri), None, flavor)+ }+ Some(UiSource::Embedded { resource }) => {+ let uri = resource+ .get("uri")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ match resource_from_contents(std::slice::from_ref(&resource), &uri) {+ Ok(document) => {+ let id = cache::put_inline(InlineEntry {+ server_id: Some(view.server_id.clone()),+ resource: document,+ });+ (None, Some(id), UiFlavor::McpApps)+ }+ Err(error) => {+ tracing::debug!(tool = %view.tool, %error, "[mcp_ui] embedded widget rejected");+ (None, None, UiFlavor::McpApps)+ }+ }+ }+ None => (None, None, UiFlavor::McpApps),+ };+ if resource_uri.is_none() && inline_id.is_none() && links.is_empty() {+ return None;+ }+ tracing::debug!(+ server_id = %view.server_id,+ tool = %view.tool,+ frame = resource_uri.is_some() || inline_id.is_some(),+ links = links.len(),+ "[mcp_ui] tool call offered UI"+ );+ Some(McpUiPresentation {+ kind: MCP_UI_KIND.to_string(),+ flavor,+ server_id: Some(view.server_id.clone()),+ tool: view.tool.clone(),+ resource_uri,+ inline_id,+ title: None,+ tool_input: bounded(Some(&view.tool_input), MAX_INPUT_BYTES).unwrap_or(Value::Null),+ structured_content: bounded(view.structured_content.as_ref(), MAX_STRUCTURED_BYTES),+ result_meta: bounded(view.result_meta.as_ref(), MAX_META_BYTES),+ links,+ })+}++fn normalize_resource_entry(entry: &Value) -> Value {+ match entry.get("type").and_then(Value::as_str) {+ Some("resource") => entry.get("resource").cloned().unwrap_or(Value::Null),+ _ => entry.clone(),+ }+}++fn resources_from_content(content: Option<&Value>) -> Vec<Value> {+ content+ .and_then(Value::as_array)+ .map(|blocks| {+ blocks+ .iter()+ .filter(|block| block.get("type").and_then(Value::as_str) == Some("resource"))+ .map(normalize_resource_entry)+ .collect()+ })+ .unwrap_or_default()+}++fn text_from_content(content: Option<&Value>) -> String {+ content+ .and_then(Value::as_array)+ .map(|blocks| {+ blocks+ .iter()+ .filter(|block| block.get("type").and_then(Value::as_str) == Some("text"))+ .filter_map(|block| block.get("text").and_then(Value::as_str))+ .collect::<Vec<_>>()+ .join("\n")+ })+ .unwrap_or_default()+}++/// A view over a server's raw `tools/call` reply.+#[must_use]+pub fn view_from_raw_result(+ server_id: &str,+ tool: &str,+ tool_meta: Option<Value>,+ tool_input: Value,+ raw: &Value,+) -> UiCallView {+ UiCallView {+ server_id: server_id.to_string(),+ tool: tool.to_string(),+ tool_meta,+ tool_input,+ structured_content: raw.get("structuredContent").cloned(),+ result_meta: raw.get("_meta").cloned(),+ resources: resources_from_content(raw.get("content")),+ text: text_from_content(raw.get("content")),+ }+}++/// A view over the `mcp_result` envelope a tool result's metadata carries.+///+/// `None` when `metadata` is not that envelope.+#[must_use]+pub fn view_from_envelope(+ metadata: &Value,+ tool_meta: Option<Value>,+ tool_input: Value,+ text: &str,+) -> Option<UiCallView> {+ if metadata.get("kind").and_then(Value::as_str) != Some(MCP_RESULT_KIND) {+ return None;+ }+ let server_id = metadata.get("server").and_then(Value::as_str)?;+ let tool = metadata.get("tool").and_then(Value::as_str)?;+ let resources = metadata+ .get("resources")+ .and_then(Value::as_array)+ .map(|entries| entries.iter().map(normalize_resource_entry).collect())+ .unwrap_or_default();+ Some(UiCallView {+ server_id: server_id.to_string(),+ tool: tool.to_string(),+ tool_meta,+ tool_input,+ structured_content: metadata+ .get("structured_content")+ .filter(|value| !value.is_null())+ .cloned(),+ result_meta: metadata+ .get("meta")+ .filter(|value| !value.is_null())+ .cloned(),+ resources,+ text: text.to_string(),+ })+}++/// The widget document for `uri` among a `resources/read` reply's contents.+///+/// # Errors+///+/// When no entry matches, the entry is not HTML, has no text, or is larger+/// than [`MAX_RESOURCE_BYTES`].+pub fn resource_from_contents(contents: &[Value], uri: &str) -> Result<UiResource, String> {+ let entry = contents+ .iter()+ .find(|entry| entry.get("uri").and_then(Value::as_str) == Some(uri))+ .or_else(|| (contents.len() == 1).then(|| &contents[0]))+ .ok_or_else(|| "the server returned no document for this URI".to_string())?;+ let mime_type = entry+ .get("mimeType")+ .and_then(Value::as_str)+ .unwrap_or("")+ .trim()+ .to_string();+ if !is_html_mime(&mime_type) {+ return Err(format!("unsupported widget type `{mime_type}`"));+ }+ let html = match (+ entry.get("text").and_then(Value::as_str),+ entry.get("blob").and_then(Value::as_str),+ ) {+ (Some(text), _) => {+ if text.len() > MAX_RESOURCE_BYTES {+ return Err("the widget document is too large".to_string());+ }+ text.to_string()+ }+ (None, Some(blob)) => {+ if blob.len() > MAX_RESOURCE_BYTES * 4 / 3 + 4 {+ return Err("the widget document is too large".to_string());+ }+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(blob.trim())+ .map_err(|_| "the widget document is not valid base64".to_string())?;+ String::from_utf8(bytes).map_err(|_| "the widget document is not UTF-8".to_string())?+ }+ (None, None) => return Err("the widget document is empty".to_string()),+ };+ if html.len() > MAX_RESOURCE_BYTES {+ return Err("the widget document is too large".to_string());+ }+ let meta = entry.get("_meta");+ Ok(UiResource {+ html,+ mime_type,+ csp: csp_from_meta(meta),+ permissions: meta+ .and_then(|meta| meta.pointer("/ui/permissions"))+ .filter(|value| value.is_object())+ .cloned(),+ prefers_border: meta+ .and_then(|meta| {+ meta.pointer("/ui/prefersBorder")+ .or_else(|| meta.get("openai/widgetPrefersBorder"))+ })+ .and_then(Value::as_bool)+ .unwrap_or(false),+ })+}++fn csp_from_meta(meta: Option<&Value>) -> UiCsp {+ let Some(meta) = meta else {+ return UiCsp::default();+ };+ let (connect, resource) = if let Some(csp) = meta.pointer("/ui/csp") {+ (csp.get("connectDomains"), csp.get("resourceDomains"))+ } else if let Some(csp) = meta.get("openai/widgetCSP") {+ (csp.get("connect_domains"), csp.get("resource_domains"))+ } else {+ (None, None)+ };+ UiCsp {+ connect_domains: https_origins(connect),+ resource_domains: https_origins(resource),+ }+}++/// Each declared origin that is `https`, reduced to `https://host[:port]`;+/// a leading `*.` wildcard label is kept.+#[must_use]+pub fn https_origins(value: Option<&Value>) -> Vec<String> {+ let mut out: Vec<String> = Vec::new();+ let Some(items) = value.and_then(Value::as_array) else {+ return out;+ };+ for item in items.iter().filter_map(Value::as_str) {+ if out.len() >= MAX_CSP_DOMAINS {+ break;+ }+ if let Some(origin) = https_origin(item) {+ if !out.contains(&origin) {+ out.push(origin);+ }+ }+ }+ out+}++fn https_origin(raw: &str) -> Option<String> {+ let raw = raw.trim();+ let rest = raw+ .get(..8)+ .filter(|prefix| prefix.eq_ignore_ascii_case("https://"))+ .map(|_| &raw[8..])?;+ let authority = rest.split(['/', '?', '#']).next()?.to_ascii_lowercase();+ let (host, port) = match authority.rsplit_once(':') {+ Some((host, port)) if !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => {+ (host.to_string(), Some(port.to_string()))+ }+ Some(_) => return None,+ None => (authority.clone(), None),+ };+ let bare = host.strip_prefix("*.").unwrap_or(&host);+ let labels_ok = !bare.is_empty()+ && bare.contains('.')+ && bare.split('.').all(|label| {+ !label.is_empty()+ && label.len() <= 63+ && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')+ });+ if !labels_ok {+ return None;+ }+ Some(match port {+ Some(port) => format!("https://{host}:{port}"),+ None => format!("https://{host}"),+ })+}++#[cfg(test)]+#[path = "resolve_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/mcp/ui/resolve_tests.rs b/crates/openhuman-core/src/mcp/ui/resolve_tests.rsnew file mode 100644index 0000000000..1abe336f1b--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/resolve_tests.rs@@ -0,0 +1,196 @@+use super::*;+use serde_json::json;++fn view() -> UiCallView {+ UiCallView {+ server_id: "srv".into(),+ tool: "order".into(),+ tool_input: json!({"item": "dosa"}),+ ..UiCallView::default()+ }+}++#[test]+fn resource_uri_precedence() {+ let mut v = view();+ v.tool_meta = Some(json!({+ "openai/outputTemplate": "ui://widget/sdk.html",+ "ui/resourceUri": "ui://widget/legacy.html",+ "ui": {"resourceUri": "ui://widget/app.html"}+ }));+ assert_eq!(+ select_source(&v),+ Some(UiSource::Uri {+ uri: "ui://widget/app.html".into(),+ flavor: UiFlavor::McpApps+ })+ );++ v.tool_meta = Some(json!({+ "openai/outputTemplate": "ui://widget/sdk.html",+ "ui/resourceUri": "ui://widget/legacy.html"+ }));+ assert_eq!(+ select_source(&v),+ Some(UiSource::Uri {+ uri: "ui://widget/legacy.html".into(),+ flavor: UiFlavor::McpApps+ })+ );++ v.tool_meta = Some(json!({"openai/outputTemplate": "ui://widget/sdk.html"}));+ assert_eq!(+ select_source(&v),+ Some(UiSource::Uri {+ uri: "ui://widget/sdk.html".into(),+ flavor: UiFlavor::AppsSdk+ })+ );+}++#[test]+fn only_ui_scheme_is_accepted() {+ let mut v = view();+ v.tool_meta = Some(json!({"ui": {"resourceUri": "https://evil.example.com/w.html"}}));+ assert_eq!(select_source(&v), None);+ v.tool_meta = Some(json!({"ui": {"resourceUri": "file:///etc/passwd"}}));+ assert_eq!(select_source(&v), None);+ assert!(!is_ui_uri("ui://"));+ assert!(is_ui_uri("UI://x"));+ assert!(!is_ui_uri("é://xx"));+}++#[test]+fn embedded_html_resource_is_cached_inline() {+ let mut v = view();+ v.resources = vec![+ json!({"uri": "ui://w/plain", "mimeType": "text/plain", "text": "x"}),+ json!({"uri": "https://x/y", "mimeType": "text/html", "text": "<p>no</p>"}),+ json!({"uri": "ui://w/card", "mimeType": "text/html;profile=mcp-app", "text": "<p>hi</p>"}),+ ];+ let presentation = presentation_from_view(&v).expect("presentation");+ assert_eq!(presentation.kind, MCP_UI_KIND);+ assert!(presentation.resource_uri.is_none());+ let id = presentation.inline_id.expect("inline id");+ let entry = cache::get_inline(&id).expect("cached");+ assert_eq!(entry.resource.html, "<p>hi</p>");+ assert_eq!(entry.server_id.as_deref(), Some("srv"));+}++#[test]+fn no_ui_and_no_links_yields_nothing() {+ let mut v = view();+ v.text = "Your order is placed.".into();+ assert!(presentation_from_view(&v).is_none());+}++#[test]+fn links_only_presentation() {+ let mut v = view();+ v.text = "Pay here: upi://pay?pa=shop@bank&am=120".into();+ let presentation = presentation_from_view(&v).expect("presentation");+ assert!(!presentation.has_frame());+ assert_eq!(presentation.links.len(), 1);+ assert_eq!(presentation.tool_input, json!({"item": "dosa"}));+}++#[test]+fn oversized_structured_content_is_dropped_but_links_kept() {+ let mut v = view();+ let big = "x".repeat(MAX_STRUCTURED_BYTES + 10);+ v.structured_content = Some(json!({"blob": big, "pay": "https://pay.example.com/1"}));+ let presentation = presentation_from_view(&v).expect("presentation");+ assert!(presentation.structured_content.is_none());+ assert_eq!(presentation.links[0].url, "https://pay.example.com/1");+}++#[test]+fn raw_result_view_reads_content_blocks() {+ let raw = json!({+ "content": [+ {"type": "text", "text": "done"},+ {"type": "resource", "resource": {"uri": "ui://a", "mimeType": "text/html", "text": "<b/>"}}+ ],+ "structuredContent": {"id": 1},+ "_meta": {"k": "v"}+ });+ let v = view_from_raw_result("srv", "t", None, json!({}), &raw);+ assert_eq!(v.text, "done");+ assert_eq!(v.resources.len(), 1);+ assert_eq!(v.structured_content, Some(json!({"id": 1})));+ assert_eq!(v.result_meta, Some(json!({"k": "v"})));+}++#[test]+fn envelope_view_requires_mcp_result_kind() {+ assert!(view_from_envelope(&json!({"kind": "mcp_call"}), None, json!({}), "").is_none());+ let envelope = json!({+ "kind": "mcp_result",+ "server": "srv",+ "tool": "t",+ "structured_content": {"a": 1},+ "meta": null,+ "resources": [{"uri": "ui://x", "mimeType": "text/html", "text": "<i/>"}]+ });+ let v = view_from_envelope(&envelope, None, json!({}), "txt").expect("view");+ assert_eq!(v.server_id, "srv");+ assert!(v.result_meta.is_none());+ assert_eq!(v.resources.len(), 1);+ assert_eq!(v.text, "txt");+}++#[test]+fn resource_contents_validation() {+ let ok = json!({+ "uri": "ui://a",+ "mimeType": "text/html;profile=mcp-app",+ "text": "<html></html>",+ "_meta": {"ui": {+ "csp": {"connectDomains": ["https://api.example.com/x", "http://insecure.example.com", "javascript:alert(1)"],+ "resourceDomains": ["https://*.cdn.example.com", "https://cdn.example.com:8443"]},+ "prefersBorder": true,+ "permissions": {"clipboardWrite": {}}+ }}+ });+ let resource = resource_from_contents(&[ok], "ui://a").expect("resource");+ assert_eq!(+ resource.csp.connect_domains,+ vec!["https://api.example.com"]+ );+ assert_eq!(+ resource.csp.resource_domains,+ vec!["https://*.cdn.example.com", "https://cdn.example.com:8443"]+ );+ assert!(resource.prefers_border);+ assert!(resource.permissions.is_some());++ let not_html = json!({"uri": "ui://a", "mimeType": "application/javascript", "text": "x"});+ assert!(resource_from_contents(&[not_html], "ui://a").is_err());++ let huge = json!({"uri": "ui://a", "mimeType": "text/html", "text": "x".repeat(MAX_RESOURCE_BYTES + 1)});+ assert!(resource_from_contents(&[huge], "ui://a").is_err());++ let blob = json!({"uri": "ui://a", "mimeType": "text/html+skybridge", "blob": "PGI+aGk8L2I+",+ "_meta": {"openai/widgetCSP": {"connect_domains": ["https://api.example.com"]},+ "openai/widgetPrefersBorder": true}});+ let resource = resource_from_contents(&[blob], "ui://a").expect("blob");+ assert_eq!(resource.html, "<b>hi</b>");+ assert_eq!(+ resource.csp.connect_domains,+ vec!["https://api.example.com"]+ );+ assert!(resource.prefers_border);+}++#[test]+fn https_origin_rejects_odd_hosts() {+ let origins = https_origins(Some(&json!([+ "https://localhost",+ "https://a..b.com",+ "https://ok.example.com",+ "https://ok.example.com",+ "https://x.example.com:abc",+ "https://[email protected]"+ ])));+ assert_eq!(origins, vec!["https://ok.example.com"]);+}diff --git a/crates/openhuman-core/src/mcp/ui/schemas.rs b/crates/openhuman-core/src/mcp/ui/schemas.rsnew file mode 100644index 0000000000..826874fde1--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/schemas.rs@@ -0,0 +1,127 @@+//! `mcp_ui` controller schemas and handlers.++use std::sync::Arc;++use serde_json::{Map, Value};++use crate::config::rpc as config_rpc;+use crate::core::all::{ControllerFuture, RegisteredController};+use crate::core::{ControllerSchema, FieldSchema, TypeSchema};+use crate::security::SecurityPolicy;+use crate::util::read_optional;++use super::ops;+use super::port::HostUiPort;++pub fn all_controller_schemas() -> Vec<ControllerSchema> {+ vec![schemas("resource_read"), schemas("tool_call")]+}++pub fn all_registered_controllers() -> Vec<RegisteredController> {+ vec![+ RegisteredController {+ schema: schemas("resource_read"),+ handler: handle_resource_read,+ },+ RegisteredController {+ schema: schemas("tool_call"),+ handler: handle_tool_call,+ },+ ]+}++fn field(name: &'static str, ty: TypeSchema, comment: &'static str, required: bool) -> FieldSchema {+ FieldSchema {+ name,+ ty,+ comment,+ required,+ }+}++fn optional(ty: TypeSchema) -> TypeSchema {+ TypeSchema::Option(Box::new(ty))+}++pub fn schemas(function: &str) -> ControllerSchema {+ match function {+ "resource_read" => ControllerSchema {+ namespace: "mcp_ui",+ function: "resource_read",+ description: "Read the HTML document a tool's widget renders: a ui:// resource on a connected MCP server, or an inline document by id.",+ inputs: vec![+ field("server_id", optional(TypeSchema::String), "Server the widget belongs to.", false),+ field("uri", optional(TypeSchema::String), "The ui:// resource URI.", false),+ field("inline_id", optional(TypeSchema::String), "An inline document id from a tool result.", false),+ ],+ outputs: vec![+ field("html", TypeSchema::String, "The widget document.", true),+ field("mime_type", TypeSchema::String, "The document's MIME type.", true),+ field("csp", TypeSchema::Json, "Declared https origins: connect_domains, resource_domains.", true),+ field("permissions", optional(TypeSchema::Json), "Declared permissions.", false),+ field("prefers_border", TypeSchema::Bool, "Whether the widget asks for a border.", true),+ ],+ },+ "tool_call" => ControllerSchema {+ namespace: "mcp_ui",+ function: "tool_call",+ description: "Call a tool on behalf of a widget, under the agent's tool policy. Tools that are not read-only need confirmed=true.",+ inputs: vec![+ field("server_id", TypeSchema::String, "Server the widget belongs to.", true),+ field("tool_name", TypeSchema::String, "Tool to call.", true),+ field("arguments", optional(TypeSchema::Json), "Arguments object.", false),+ field("confirmed", optional(TypeSchema::Bool), "The user approved this call.", false),+ ],+ outputs: vec![+ field("requires_confirmation", TypeSchema::Bool, "True when the call waits for the user.", true),+ field("read_only", TypeSchema::Bool, "Whether the tool declares itself read-only.", true),+ field("result", optional(TypeSchema::Json), "The raw tools/call result.", false),+ field("is_error", optional(TypeSchema::Bool), "True when the tool reported an error.", false),+ ],+ },+ _ => ControllerSchema {+ namespace: "mcp_ui",+ function: "unknown",+ description: "Unknown mcp_ui controller function.",+ inputs: vec![],+ outputs: vec![field("error", TypeSchema::String, "Lookup error details.", true)],+ },+ }+}++fn handle_resource_read(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let server_id = read_optional::<String>(¶ms, "server_id")?;+ let uri = read_optional::<String>(¶ms, "uri")?;+ let inline_id = read_optional::<String>(¶ms, "inline_id")?;+ let config = config_rpc::load_config_with_timeout().await?;+ let port = HostUiPort::new(Arc::new(config));+ let outcome = ops::resource_read(&port, server_id, uri, inline_id).await?;+ Ok(outcome.value)+ })+}++fn handle_tool_call(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let server_id = read_optional::<String>(¶ms, "server_id")?;+ let tool_name = read_optional::<String>(¶ms, "tool_name")?;+ let arguments = params.get("arguments").cloned();+ let confirmed = read_optional::<bool>(¶ms, "confirmed")?.unwrap_or(false);+ let config = config_rpc::load_config_with_timeout().await?;+ let security = crate::security::live_policy::current().unwrap_or_else(|| {+ Arc::new(SecurityPolicy::from_config(+ &config.autonomy,+ &config.workspace_dir,+ &config.action_dir,+ ))+ });+ let port = HostUiPort::new(Arc::new(config));+ let outcome =+ ops::tool_call(&port, &security, server_id, tool_name, arguments, confirmed).await?;+ Ok(outcome.value)+ })+}++#[cfg(test)]+#[path = "schemas_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/mcp/ui/schemas_tests.rs b/crates/openhuman-core/src/mcp/ui/schemas_tests.rsnew file mode 100644index 0000000000..81b66f686c--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/schemas_tests.rs@@ -0,0 +1,23 @@+use super::*;++#[test]+fn every_registered_controller_is_in_the_mcp_ui_namespace() {+ let controllers = all_registered_controllers();+ assert_eq!(controllers.len(), all_controller_schemas().len());+ for controller in controllers {+ assert_eq!(controller.schema.namespace, "mcp_ui");+ assert_ne!(controller.schema.function, "unknown");+ }+}++#[test]+fn tool_call_requires_server_and_tool() {+ let schema = schemas("tool_call");+ let required: Vec<_> = schema+ .inputs+ .iter()+ .filter(|field| field.required)+ .map(|field| field.name)+ .collect();+ assert_eq!(required, vec!["server_id", "tool_name"]);+}diff --git a/crates/openhuman-core/src/mcp/ui/tools.rs b/crates/openhuman-core/src/mcp/ui/tools.rsnew file mode 100644index 0000000000..c5b904d21c--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/tools.rs@@ -0,0 +1,207 @@+//! `show_ui`: lets a skill render its own HTML in the chat, in the same+//! sandboxed frame MCP widgets use.+//!+//! The document comes inline or from an `.html` file confined to the action+//! directory, the workspace, or the user's skill bundles. The frame it runs in+//! cannot call tools; it can only ask the host to open a link or prefill the+//! composer.++use std::path::{Component, Path, PathBuf};++use async_trait::async_trait;+use serde_json::{json, Value};+use tinytools::{PermissionLevel, Tool, ToolExposure, ToolResult};++use super::cache::{self, InlineEntry};+use super::links::extract_links;+use super::resolve::{MAX_RESOURCE_BYTES, MAX_STRUCTURED_BYTES};+use super::types::{McpUiPresentation, UiCsp, UiFlavor, UiResource, MCP_APP_MIME, MCP_UI_KIND};++/// The tool's registered name.+pub const SHOW_UI_TOOL: &str = "show_ui";++const MAX_TITLE_CHARS: usize = 80;++/// The `show_ui` tool.+pub struct ShowUiTool {+ roots: Vec<PathBuf>,+}++impl ShowUiTool {+ /// A tool reading files under `roots` only.+ #[must_use]+ pub fn new(roots: Vec<PathBuf>) -> Self {+ Self { roots }+ }++ /// The tool for `config`: the action directory, the workspace and the+ /// user's skill bundles.+ #[must_use]+ pub fn for_config(config: &crate::config::Config) -> Self {+ let mut roots = vec![config.action_dir.clone(), config.workspace_dir.clone()];+ if let Some(home) = dirs::home_dir() {+ roots.push(home.join(".openhuman").join("skills"));+ }+ Self::new(roots)+ }+}++/// `path` resolved inside one of `roots`, refusing traversal, symlink escapes+/// and anything but `.html` / `.htm`.+///+/// # Errors+///+/// When the path is malformed, outside every root, or not an HTML file.+pub fn confine_path(roots: &[PathBuf], path: &str) -> Result<PathBuf, String> {+ let requested = Path::new(path.trim());+ if path.trim().is_empty() || path.contains('\0') {+ return Err("path must not be empty".to_string());+ }+ if requested+ .components()+ .any(|component| matches!(component, Component::ParentDir))+ {+ return Err("path must not contain `..`".to_string());+ }+ let extension = requested+ .extension()+ .and_then(|ext| ext.to_str())+ .map(str::to_ascii_lowercase);+ if !matches!(extension.as_deref(), Some("html" | "htm")) {+ return Err("only .html files can be shown".to_string());+ }+ for root in roots {+ let Ok(canonical_root) = root.canonicalize() else {+ continue;+ };+ let candidate = if requested.is_absolute() {+ requested.to_path_buf()+ } else {+ canonical_root.join(requested)+ };+ let Ok(resolved) = candidate.canonicalize() else {+ continue;+ };+ if resolved.starts_with(&canonical_root) && resolved.is_file() {+ return Ok(resolved);+ }+ }+ Err("the file is not inside the workspace or a skill bundle".to_string())+}++fn clean_title(raw: Option<&str>) -> Option<String> {+ let title: String = raw?+ .chars()+ .filter(|c| !c.is_control())+ .take(MAX_TITLE_CHARS)+ .collect();+ let title = title.trim().to_string();+ (!title.is_empty()).then_some(title)+}++#[async_trait]+impl Tool for ShowUiTool {+ fn name(&self) -> &str {+ SHOW_UI_TOOL+ }++ fn description(&self) -> &str {+ "Show an interactive HTML view inline in the chat, in a sandbox. Pass `html`, or `path` to an .html file in the workspace or a skill bundle, plus an optional `title` and a `data` object the page receives as its tool result. The page cannot call tools or reach the network; use it for visual output a skill produces."+ }++ fn parameters_schema(&self) -> Value {+ json!({+ "type": "object",+ "properties": {+ "html": {"type": "string", "description": "A complete HTML document."},+ "path": {"type": "string", "description": "An .html file in the workspace or a skill bundle."},+ "title": {"type": "string", "description": "A short label for the view."},+ "data": {"type": "object", "description": "Data handed to the page."}+ }+ })+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::ReadOnly+ }++ fn exposure(&self) -> ToolExposure {+ ToolExposure::Deferred+ }++ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {+ let html_arg = args.get("html").and_then(Value::as_str);+ let path_arg = args.get("path").and_then(Value::as_str);+ let html = match (html_arg, path_arg) {+ (Some(html), None) => html.to_string(),+ (None, Some(path)) => {+ let resolved = match confine_path(&self.roots, path) {+ Ok(resolved) => resolved,+ Err(error) => return Ok(ToolResult::error(format!("show_ui: {error}"))),+ };+ let size = tokio::fs::metadata(&resolved).await?.len();+ if size > MAX_RESOURCE_BYTES as u64 {+ return Ok(ToolResult::error("show_ui: the file is too large to show"));+ }+ tokio::fs::read_to_string(&resolved).await?+ }+ _ => {+ return Ok(ToolResult::error(+ "show_ui: pass exactly one of `html` or `path`",+ ))+ }+ };+ if html.trim().is_empty() {+ return Ok(ToolResult::error("show_ui: the document is empty"));+ }+ if html.len() > MAX_RESOURCE_BYTES {+ return Ok(ToolResult::error(+ "show_ui: the document is too large to show",+ ));+ }+ let data = args+ .get("data")+ .filter(|value| value.is_object())+ .filter(|value| {+ serde_json::to_vec(value)+ .map(|bytes| bytes.len() <= MAX_STRUCTURED_BYTES)+ .unwrap_or(false)+ })+ .cloned();+ let title = clean_title(args.get("title").and_then(Value::as_str));+ let inline_id = cache::put_inline(InlineEntry {+ server_id: None,+ resource: UiResource {+ html,+ mime_type: MCP_APP_MIME.to_string(),+ csp: UiCsp::default(),+ permissions: None,+ prefers_border: true,+ },+ });+ let presentation = McpUiPresentation {+ kind: MCP_UI_KIND.to_string(),+ flavor: UiFlavor::HostInline,+ server_id: None,+ tool: SHOW_UI_TOOL.to_string(),+ resource_uri: None,+ inline_id: Some(inline_id),+ title: title.clone(),+ tool_input: data.clone().unwrap_or(Value::Null),+ structured_content: data.clone(),+ result_meta: None,+ links: extract_links(data.as_ref(), ""),+ };+ tracing::debug!(title = ?title, "[mcp_ui] show_ui rendered a host view");+ let mut result = ToolResult::success(match &title {+ Some(title) => format!("Shown \"{title}\" inline in the chat."),+ None => "Shown the view inline in the chat.".to_string(),+ });+ result.metadata = Some(presentation.to_metadata());+ Ok(result)+ }+}++#[cfg(test)]+#[path = "tools_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/mcp/ui/tools_tests.rs b/crates/openhuman-core/src/mcp/ui/tools_tests.rsnew file mode 100644index 0000000000..309ba12bed--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/tools_tests.rs@@ -0,0 +1,86 @@+use super::*;++fn tempdir() -> tempfile::TempDir {+ tempfile::tempdir().expect("tempdir")+}++#[test]+fn confine_path_rules() {+ let root = tempdir();+ let outside = tempdir();+ std::fs::write(root.path().join("view.html"), "<p>hi</p>").unwrap();+ std::fs::write(root.path().join("notes.txt"), "x").unwrap();+ std::fs::write(outside.path().join("secret.html"), "x").unwrap();+ let roots = vec![root.path().to_path_buf()];++ assert!(confine_path(&roots, "view.html").is_ok());+ assert!(confine_path(&roots, "notes.txt").is_err());+ assert!(confine_path(&roots, "../secret.html").is_err());+ assert!(confine_path(&roots, outside.path().join("secret.html").to_str().unwrap()).is_err());+ assert!(confine_path(&roots, "missing.html").is_err());+ assert!(confine_path(&roots, "").is_err());+}++#[cfg(unix)]+#[test]+fn confine_path_refuses_symlink_escape() {+ let root = tempdir();+ let outside = tempdir();+ std::fs::write(outside.path().join("secret.html"), "x").unwrap();+ std::os::unix::fs::symlink(+ outside.path().join("secret.html"),+ root.path().join("link.html"),+ )+ .unwrap();+ assert!(confine_path(&[root.path().to_path_buf()], "link.html").is_err());+}++#[tokio::test]+async fn inline_html_produces_host_inline_presentation() {+ let tool = ShowUiTool::new(vec![]);+ let result = tool+ .execute(+ serde_json::json!({"html": "<p>chart</p>", "title": "Sales\nchart", "data": {"n": 1}}),+ )+ .await+ .unwrap();+ assert!(!result.is_error);+ let metadata = result.metadata.unwrap();+ assert_eq!(metadata["kind"], "mcp_ui");+ assert_eq!(metadata["flavor"], "host_inline");+ assert_eq!(metadata["title"], "Saleschart");+ assert!(metadata.get("server_id").is_none());+ let id = metadata["inline_id"].as_str().unwrap();+ let entry = cache::get_inline(id).unwrap();+ assert_eq!(entry.resource.html, "<p>chart</p>");+ assert!(entry.server_id.is_none());+}++#[tokio::test]+async fn requires_exactly_one_source() {+ let tool = ShowUiTool::new(vec![]);+ let both = tool+ .execute(serde_json::json!({"html": "<p/>", "path": "a.html"}))+ .await+ .unwrap();+ assert!(both.is_error);+ let neither = tool.execute(serde_json::json!({})).await.unwrap();+ assert!(neither.is_error);+}++#[tokio::test]+async fn path_source_is_read_from_root() {+ let root = tempdir();+ std::fs::write(root.path().join("v.html"), "<b>ok</b>").unwrap();+ let tool = ShowUiTool::new(vec![root.path().to_path_buf()]);+ let result = tool+ .execute(serde_json::json!({"path": "v.html"}))+ .await+ .unwrap();+ assert!(!result.is_error);+ let id = result.metadata.unwrap()["inline_id"]+ .as_str()+ .unwrap()+ .to_string();+ assert_eq!(cache::get_inline(&id).unwrap().resource.html, "<b>ok</b>");+}diff --git a/crates/openhuman-core/src/mcp/ui/types.rs b/crates/openhuman-core/src/mcp/ui/types.rsnew file mode 100644index 0000000000..259928774d--- /dev/null+++ b/crates/openhuman-core/src/mcp/ui/types.rs@@ -0,0 +1,137 @@+//! Wire types for tool-provided UI: the presentation a tool result carries to+//! the chat surface, and the payloads of the `mcp_ui` RPC namespace.++use serde::{Deserialize, Serialize};+use serde_json::Value;++/// The `kind` a presentation carries in a tool result's metadata.+pub const MCP_UI_KIND: &str = "mcp_ui";++/// The `kind` of the result envelope `tinymcp` attaches to a tool result.+pub const MCP_RESULT_KIND: &str = "mcp_result";++/// The MIME type an MCP Apps resource declares.+pub const MCP_APP_MIME: &str = "text/html;profile=mcp-app";++/// The client capability extension that advertises MCP Apps support.+pub const MCP_APPS_EXTENSION: &str = "io.modelcontextprotocol/ui";++/// Which widget protocol the frame speaks to the page.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum UiFlavor {+ /// MCP Apps (`ui/*` JSON-RPC over `postMessage`).+ McpApps,+ /// OpenAI Apps SDK (`window.openai`), bridged onto the same channel.+ AppsSdk,+ /// HTML supplied by the host itself (`show_ui`); no tool calls.+ HostInline,+}++/// How a link found in a tool result may be opened.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum UiLinkKind {+ /// `http(s)`: opened in the system browser.+ External,+ /// Any other allowed scheme (`upi://`, `phonepe://`, ...): handed to a+ /// phone by QR code, never opened on this machine.+ Handoff,+}++/// A link a tool result offered, shown as an action under the call.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct UiLink {+ pub url: String,+ pub kind: UiLinkKind,+}++/// What the chat surface renders for one tool call that offered UI.+///+/// Carried as the tool result's metadata. Never carries the widget's HTML:+/// the frame reads that through `openhuman.mcp_ui_resource_read`.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct McpUiPresentation {+ /// Always [`MCP_UI_KIND`].+ pub kind: String,+ pub flavor: UiFlavor,+ /// The server the tool belongs to; `None` for host-supplied UI.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub server_id: Option<String>,+ pub tool: String,+ /// The `ui://` resource the frame loads.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub resource_uri: Option<String>,+ /// An in-memory inline resource the frame loads instead.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub inline_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ #[serde(default)]+ pub tool_input: Value,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub structured_content: Option<Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub result_meta: Option<Value>,+ #[serde(default)]+ pub links: Vec<UiLink>,+}++impl McpUiPresentation {+ /// Whether the presentation has a frame to show.+ #[must_use]+ pub fn has_frame(&self) -> bool {+ self.resource_uri.is_some() || self.inline_id.is_some()+ }++ /// The presentation as tool-result metadata.+ #[must_use]+ pub fn to_metadata(&self) -> Value {+ serde_json::to_value(self).unwrap_or(Value::Null)+ }+}++/// One tool call, reduced to what UI resolution reads.+#[derive(Debug, Clone, Default)]+pub struct UiCallView {+ pub server_id: String,+ pub tool: String,+ /// The tool descriptor's `_meta`.+ pub tool_meta: Option<Value>,+ pub tool_input: Value,+ pub structured_content: Option<Value>,+ /// The result's `_meta`.+ pub result_meta: Option<Value>,+ /// Embedded resources, as `{uri, mimeType, text?, _meta?}` objects.+ pub resources: Vec<Value>,+ /// The result's text, as the model saw it.+ pub text: String,+}++/// A widget document, ready for the frame.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct UiResource {+ pub html: String,+ pub mime_type: String,+ pub csp: UiCsp,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub permissions: Option<Value>,+ #[serde(default)]+ pub prefers_border: bool,+}++/// The origins a widget may reach, already reduced to `https` only.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct UiCsp {+ #[serde(default)]+ pub connect_domains: Vec<String>,+ #[serde(default)]+ pub resource_domains: Vec<String>,+}++/// What a widget-initiated tool call needs to know about its target tool.+#[derive(Debug, Clone, Default, PartialEq)]+pub struct UiToolDescriptor {+ pub meta: Option<Value>,+ pub annotations: Option<Value>,+}