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): take the tool UI rules from tinymcp::ui
oxoxDev94deacc34b7a
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex c77060f71c..4cd13cd374 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -237,6 +237,9 @@ tinymcp = { path = "../../vendor/tinymcp/crates/tinymcp", default-features = fal# Server tools as `tinytools::Tool`s over the persistent tool cache. Needs# the root `[patch]` that redirects tinymcp's git tinytools to ours."tools",+ # Tool UI rules: widget templates, documents, link classification, and the+ # widget tool-call policy, behind the `mcp_ui` host glue.+ "ui",] }tinymcp-bus = { path = "../../vendor/tinymcp/crates/tinymcp-bus", features = ["schemars"] }# The transport-free channel vocabulary: inbound envelopes, outbound intents,diff --git a/crates/openhuman-core/src/mcp/ui/discovery.rs b/crates/openhuman-core/src/mcp/ui/discovery.rsindex 97eb880073..0009380b10 100644--- a/crates/openhuman-core/src/mcp/ui/discovery.rs+++ b/crates/openhuman-core/src/mcp/ui/discovery.rs@@ -13,20 +13,8 @@ use crate::mcp::host::{self, McpHost};use super::resolve::is_ui_uri;-const TEMPLATE_KEYS: &[&[&str]] = &[- &["ui", "resourceUri"],- &["ui/resourceUri"],- &["openai/outputTemplate"],-];--fn template_uri(meta: &Value) -> Option<&str> {- TEMPLATE_KEYS.iter().find_map(|path| {- let mut cursor = meta;- for key in *path {- cursor = cursor.get(*key)?;- }- cursor.as_str().filter(|uri| is_ui_uri(uri))- })+fn template_uri(meta: &Value) -> Option<String> {+ tinymcp::ui::template_from_meta(meta).map(|(uri, _)| uri)}fn meta_keys(meta: &Value) -> Vec<String> {diff --git a/crates/openhuman-core/src/mcp/ui/discovery_tests.rs b/crates/openhuman-core/src/mcp/ui/discovery_tests.rsindex ac63dfbc18..6c3412d170 100644--- a/crates/openhuman-core/src/mcp/ui/discovery_tests.rs+++ b/crates/openhuman-core/src/mcp/ui/discovery_tests.rs@@ -1,22 +1,6 @@use super::*;use serde_json::json;-#[test]-fn template_uri_precedence_and_scheme() {- assert_eq!(- template_uri(&json!({"ui": {"resourceUri": "ui://a"}, "openai/outputTemplate": "ui://b"})),- Some("ui://a")- );- assert_eq!(- template_uri(&json!({"openai/outputTemplate": "ui://b"})),- Some("ui://b")- );- assert_eq!(- template_uri(&json!({"ui": {"resourceUri": "https://x"}})),- None- );-}-#[test]fn meta_keys_include_ui_members() {let keys = meta_keys(&json!({"ui": {"resourceUri": "ui://a", "visibility": ["app"]}, "x": 1}));diff --git a/crates/openhuman-core/src/mcp/ui/links.rs b/crates/openhuman-core/src/mcp/ui/links.rsdeleted file mode 100644index 2cfd9b78ff..0000000000--- a/crates/openhuman-core/src/mcp/ui/links.rs+++ /dev/null@@ -1,163 +0,0 @@-//! 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 IMAGE_EXTENSIONS: &[&str] = &[- "jpg", "jpeg", "png", "gif", "webp", "avif", "svg", "bmp", "ico", "heic", "heif", "tif", "tiff",-];-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 kind == UiLinkKind::External && is_image_url(url) {- continue;- }- if out.iter().any(|link| link.url == url) {- continue;- }- out.push(UiLink {- url: url.to_string(),- kind,- });- }- }- out-}--/// Whether an `http(s)` URL points at an image asset rather than a page.-#[must_use]-pub fn is_image_url(url: &str) -> bool {- let Ok(parsed) = url::Url::parse(url) else {- return false;- };- let path = parsed.path().to_ascii_lowercase();- if path.contains("/image/upload/") {- return true;- }- path.rsplit_once('.')- .is_some_and(|(_, ext)| !ext.contains('/') && IMAGE_EXTENSIONS.contains(&ext))-}--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.rsdeleted file mode 100644index 6f45078cd9..0000000000--- a/crates/openhuman-core/src/mcp/ui/links_tests.rs+++ /dev/null@@ -1,111 +0,0 @@-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)"]- );-}--#[test]-fn drops_image_assets() {- let structured = json!({- "a_image": "https://media-assets.swiggy.com/swiggy/image/upload/fl_lossy,f_auto,q_auto/NI_CATALOG/IMAGES/CIW/2026/6/4/x_1",- "b_photo": "https://cdn.example.com/products/bar_1.JPG",- "c_page": "https://www.swiggy.com/instamart/item/123",- });- let text = "Logo https://cdn.example.com/logo.svg?v=2 and pay at upi://[email protected]";- let links = extract_links(Some(&structured), text);- assert_eq!(- urls(&links),- vec![- "https://www.swiggy.com/instamart/item/123",- "upi://[email protected]"- ]- );-}--#[test]-fn image_url_table() {- assert!(is_image_url(- "https://res.cloudinary.com/demo/image/upload/sample"- ));- assert!(is_image_url("https://cdn.example.com/a/b.webp"));- assert!(!is_image_url("https://example.com/pngs/list"));- assert!(!is_image_url("https://example.com/checkout"));- assert!(!is_image_url("not a url"));-}diff --git a/crates/openhuman-core/src/mcp/ui/mod.rs b/crates/openhuman-core/src/mcp/ui/mod.rsindex 014ebbd809..9064d9d18c 100644--- a/crates/openhuman-core/src/mcp/ui/mod.rs+++ b/crates/openhuman-core/src/mcp/ui/mod.rs@@ -1,8 +1,9 @@//! 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.+//! - [`resolve`] applies `tinymcp::ui`'s rules to one call's descriptor+//! `_meta` and result, giving a [`types::McpUiPresentation`], the metadata+//! the chat surface renders, and caches any document the result carried.//! - [`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`].@@ -14,7 +15,6 @@pub mod cache;pub mod decorate;pub mod discovery;-pub mod links;pub mod ops;pub mod port;pub mod resolve;@@ -29,13 +29,28 @@ pub use schemas::{};pub use tools::ShowUiTool;+/// `show_ui`, boxed for the tool list.+#[must_use]+pub fn show_ui_tool(config: &crate::config::Config) -> Box<dyn tinytools::Tool> {+ Box::new(ShowUiTool::for_config(config))+}++/// `mcp_call_tool` over a configured-server registry, presenting the UI of+/// the remote tool it calls.+#[must_use]+pub fn ui_aware_call(+ call: Box<dyn tinytools::Tool>,+ registry: &std::sync::Arc<crate::mcp::config_servers::McpServerRegistry>,+) -> Box<dyn tinytools::Tool> {+ Box::new(UiAwareTool::new(+ call,+ decorate::MetaLookup::Configured(std::sync::Arc::clone(registry)),+ decorate::ToolInput::Nested("arguments"),+ ))+}+/// 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 })+ tinymcp::ui::client_capabilities()}diff --git a/crates/openhuman-core/src/mcp/ui/ops.rs b/crates/openhuman-core/src/mcp/ui/ops.rsindex 2b5b5ce9b5..7419790cb2 100644--- a/crates/openhuman-core/src/mcp/ui/ops.rs+++ b/crates/openhuman-core/src/mcp/ui/ops.rs@@ -18,7 +18,7 @@ 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};+use super::types::UiResource;fn require(value: Option<String>, field: &str) -> Result<String, String> {value@@ -92,32 +92,6 @@ pub async fn resource_read())}-/// 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@@ -149,7 +123,7 @@ pub async fn tool_call(.tool_descriptor(&server_id, &tool_name).await.ok_or_else(|| format!("`{tool_name}` is not offered by this server"))?;- if !visible_to_app(&descriptor) {+ if !tinymcp::ui::visible_to_app(descriptor.meta.as_ref()) {tracing::debug!(server_id,tool_name,@@ -157,7 +131,7 @@ pub async fn tool_call();return Err(format!("`{tool_name}` cannot be called from a widget"));}- let read_only = is_read_only(&descriptor);+ let read_only = tinymcp::ui::is_read_only(descriptor.annotations.as_ref());if !read_only && !confirmed {tracing::debug!(server_id,diff --git a/crates/openhuman-core/src/mcp/ui/ops_tests.rs b/crates/openhuman-core/src/mcp/ui/ops_tests.rsindex 1f512ec363..8fe3fc5efb 100644--- a/crates/openhuman-core/src/mcp/ui/ops_tests.rs+++ b/crates/openhuman-core/src/mcp/ui/ops_tests.rs@@ -5,7 +5,7 @@ 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::mcp::ui::types::{UiCsp, UiToolDescriptor};use crate::security::AutonomyLevel;#[derive(Default)]@@ -236,19 +236,3 @@ async fn tool_call_honours_policy_denial() {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/resolve.rs b/crates/openhuman-core/src/mcp/ui/resolve.rsindex 01bde19c7a..0b139edc24 100644--- a/crates/openhuman-core/src/mcp/ui/resolve.rs+++ b/crates/openhuman-core/src/mcp/ui/resolve.rs@@ -1,397 +1,32 @@//! 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.+//! The rules are `tinymcp::ui`'s. This host keeps any widget document the+//! result carried, 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,+pub use tinymcp::ui::{+ https_origins, is_ui_uri, resource_from_contents, view_from_envelope, view_from_raw_result,+ MAX_STRUCTURED_BYTES, MAX_WIDGET_BYTES as MAX_RESOURCE_BYTES,};-/// 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())-}+use super::cache::{self, InlineEntry};+use super::types::{McpUiPresentation, UiCallView};/// The presentation for one call, or `None` when it offered neither a widget-/// nor a link.+/// nor a link. A document the result embedded is cached for the frame.#[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}"),- })+ let resolved = tinymcp::ui::resolve_presentation(view)?;+ let mut presentation = resolved.presentation;+ if let Some((uri, document)) = resolved.prefetched {+ cache::put_read(&view.server_id, &uri, document);+ }+ if let Some(document) = resolved.inline_document {+ presentation.inline_id = Some(cache::put_inline(InlineEntry {+ server_id: Some(view.server_id.clone()),+ resource: document,+ }));+ }+ Some(presentation)}#[cfg(test)]diff --git a/crates/openhuman-core/src/mcp/ui/resolve_tests.rs b/crates/openhuman-core/src/mcp/ui/resolve_tests.rsindex 1abe336f1b..270bd0297b 100644--- a/crates/openhuman-core/src/mcp/ui/resolve_tests.rs+++ b/crates/openhuman-core/src/mcp/ui/resolve_tests.rs@@ -1,6 +1,8 @@use super::*;use serde_json::json;+use crate::mcp::ui::types::MCP_UI_KIND;+fn view() -> UiCallView {UiCallView {server_id: "srv".into(),@@ -10,62 +12,10 @@ fn view() -> UiCallView {}}-#[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");@@ -78,119 +28,25 @@ fn embedded_html_resource_is_cached_inline() {}#[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() {+fn embedded_template_document_is_cached_for_reads() {let mut v = view();- v.text = "Pay here: upi://pay?pa=shop@bank&am=120".into();+ v.server_id = "srv-prefetch".into();+ v.tool_meta = Some(json!({"ui": {"resourceUri": "ui://w/prefetched"}}));+ v.resources =+ vec![json!({"uri": "ui://w/prefetched", "mimeType": "text/html", "text": "<p>card</p>"})];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"]+ presentation.resource_uri.as_deref(),+ Some("ui://w/prefetched"));- assert!(resource.prefers_border);+ assert!(presentation.inline_id.is_none());+ let cached = cache::get_read("srv-prefetch", "ui://w/prefetched").expect("cached");+ assert_eq!(cached.html, "<p>card</p>");}#[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"]);+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());}diff --git a/crates/openhuman-core/src/mcp/ui/tools.rs b/crates/openhuman-core/src/mcp/ui/tools.rsindex c5b904d21c..cf2a4d67ce 100644--- a/crates/openhuman-core/src/mcp/ui/tools.rs+++ b/crates/openhuman-core/src/mcp/ui/tools.rs@@ -13,9 +13,9 @@ 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};+use tinymcp::ui::extract_links;/// The tool's registered name.pub const SHOW_UI_TOOL: &str = "show_ui";diff --git a/crates/openhuman-core/src/mcp/ui/types.rs b/crates/openhuman-core/src/mcp/ui/types.rsindex 259928774d..a299728ab3 100644--- a/crates/openhuman-core/src/mcp/ui/types.rs+++ b/crates/openhuman-core/src/mcp/ui/types.rs@@ -1,133 +1,13 @@-//! 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.+//! Types for tool-provided UI. The presentation vocabulary is `tinymcp`'s;+//! what is defined here is this host's own.-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>,-}+pub use tinymcp::ui::{+ McpUiPresentation, UiCallView, UiCsp, UiFlavor, UiLink, UiLinkKind, UiResource,+ MCP_APPS_EXTENSION, MCP_APP_MIME, MCP_UI_KIND,+};+pub use tinymcp::MCP_RESULT_KIND;/// What a widget-initiated tool call needs to know about its target tool.#[derive(Debug, Clone, Default, PartialEq)]