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
merge: sync main into feat/7202-mcp-apps-in-chat
oxoxDev7777fe7ec509
diff --cc Cargo.lockindex 0ceb099e12,96d20e3891..6d4834a77a--- a/Cargo.lock+++ b/Cargo.lock@@@ -143,7 -143,7 +143,7 @@@ version = "1.1.5source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"dependencies = [-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -154,7 -154,7 +154,7 @@@ checksum = "291e6a250ff86cd4a820112fb88dependencies = ["anstyle","once_cell_polyfill",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -713,7 -713,7 +713,7 @@@ dependencies ="cap-primitives","cap-std","io-lifetimes 3.0.1",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -730,7 -730,7 +730,7 @@@ dependencies ="maybe-owned","rustix 1.1.5","rustix-linux-procfs",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2","winx",]@@@ -1580,7 -1571,7 +1580,7 @@@ dependencies ="libc","option-ext","redox_users",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -1771,7 -1762,7 +1771,7 @@@ source = "registry+https://github.com/rchecksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -3589,7 -3580,7 +3589,7 @@@ version = "0.50.3source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -4794,7 -4784,7 +4794,7 @@@ dependencies ="once_cell","socket2","tracing",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -5324,7 -5314,7 +5324,7 @@@ dependencies ="errno","libc","linux-raw-sys 0.12.1",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -5392,7 -5382,7 +5392,7 @@@ dependencies ="security-framework 3.7.0","security-framework-sys","webpki-root-certs",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -5981,7 -5971,7 +5981,7 @@@ source = "registry+https://github.com/rchecksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"dependencies = ["libc",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -6278,10 -6268,10 +6278,10 @@@ source = "registry+https://github.com/rchecksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",-- "getrandom 0.3.4",++ "getrandom 0.4.3","once_cell","rustix 1.1.5",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -6294,7 -6284,7 +6294,7 @@@ dependencies ="parking_lot","rustix 1.1.5","signal-hook",-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]@@@ -7073,39 -7095,9 +7105,35 @@@ dependencies ="url",]+[[package]]+name = "tinymcp"- version = "0.9.0"++version = "0.14.3"+dependencies = [- "anyhow",- "async-trait",- "axum",+ "base64 0.23.1",+ "dirs 7.0.0",+ "futures-util",+ "libc",+ "parking_lot",+ "regex",+ "reqwest 0.12.28",+ "rusqlite",+ "serde",+ "serde_json",+ "sha2 0.11.0",+ "thiserror 2.0.20",+ "tinymcp-bus",+ "tinytools",+ "tinytools-std",+ "tokio",- "tokio-stream",+ "tracing",+ "url",+ "urlencoding",+ "uuid",+]+[[package]]name = "tinymcp-bus"- version = "0.9.0"+ version = "0.14.3"dependencies = ["schemars","serde",@@@ -8588,7 -8580,7 +8616,7 @@@ version = "0.1.11source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [-- "windows-sys 0.60.2",++ "windows-sys 0.61.2",][[package]]diff --cc crates/openhuman-app/Cargo.lockindex 1afd59e497,6e76f03b35..91a12e3023--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@@ -1592,15 -1525,9 +1534,9 @@@ source = "registry+https://github.com/rchecksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",]- [[package]]- name = "event-listener"- version = "2.5.3"- source = "registry+https://github.com/rust-lang/crates.io-index"- checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"-[[package]]name = "event-listener"version = "5.4.2"@@@ -5197,6 -4996,19 +5007,19 @@@ dependencies ="semver",]+ [[package]]+ name = "rustix"+ version = "0.38.44"+ source = "registry+https://github.com/rust-lang/crates.io-index"+ checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"+ dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.4.15",- "windows-sys 0.52.0",++ "windows-sys 0.59.0",+ ]+[[package]]name = "rustix"version = "1.1.5"@@@ -5206,8 -5018,8 +5029,8 @@@ dependencies ="bitflags 2.13.2","errno","libc",- "linux-raw-sys",+ "linux-raw-sys 0.12.1",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@@ -6661,8 -6450,8 +6461,8 @@@ dependencies ="fastrand","getrandom 0.4.3","once_cell",- "rustix",+ "rustix 1.1.5",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@@ -7370,39 -7097,9 +7108,35 @@@ dependencies ="url",]+[[package]]+name = "tinymcp"- version = "0.9.0"++version = "0.14.3"+dependencies = [- "anyhow",- "async-trait",- "axum",+ "base64 0.23.1",+ "dirs 7.0.0",+ "futures-util",+ "libc",+ "parking_lot",+ "regex",+ "reqwest 0.12.28",+ "rusqlite",+ "serde",+ "serde_json",+ "sha2 0.11.0",+ "thiserror 2.0.20",+ "tinymcp-bus",+ "tinytools",+ "tinytools-std",+ "tokio",- "tokio-stream",+ "tracing",+ "url",+ "urlencoding",+ "uuid",+]+[[package]]name = "tinymcp-bus"- version = "0.9.0"+ version = "0.14.3"dependencies = ["schemars 1.2.2","serde",@@@ -8713,7 -8383,7 +8420,7 @@@ version = "0.1.11source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [-- "windows-sys 0.48.0",++ "windows-sys 0.61.2",][[package]]diff --cc crates/openhuman-core/Cargo.tomlindex 4cd13cd374,008cc3c9a7..847674b4be--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@@ -205,42 -205,6 +205,9 @@@ tinyconnectors-bus = { path = "../../ve- # tinymcp — the Model Context Protocol client, extracted out of this tree- # (https://github.com/tinyhumansai/tinymcp). Owns both transports, the static- # config-declared server set, the dynamic registry with its store, supervisor- # and OAuth, and the write-audit log. What stays here is the host half: the RPC- # surface, the agent-facing tools, and the prompt-injection scan over remote- # tool definitions, which is host policy.- #- # `tinymcp-bus` is the wire contract — payload types and member names, with no- # transport and no runtime. The `schemars` feature is on because this crate- # generates a settings schema for the desktop application from those types- # rather than from a hand-kept copy.- #- # `tinymcp` v0.9.0 publishes contract 1.13, including module-owned server- # protocol operations and HTTP session admission. The native registry entry- # pins the same release and its verified platform digests. This host is moving- # its server transport adapter to those bus operations; client adapter callers- # remain a separate cutover slice.- #- # Correcting what this comment used to promise: dropping the path dependency does- # NOT take reqwest/rusqlite with it. Measured in the kernel profile, `rusqlite` has- # six parents and `reqwest` ten, so `scripts/dep-sim.py --cut tinymcp` projects the- # entire shed at -1 package / -1 name / 0 native builds — the `tinymcp` package and- # nothing beneath it. The boundary buys compilation isolation, not a dependency shed.- #- # After cloning: `git submodule update --init vendor/tinymcp`.- # `default-features = false` drops the TinyBus adapter: this build calls the- # library directly and has no use for a bus inside it.- tinymcp = { path = "../../vendor/tinymcp/crates/tinymcp", default-features = false, features = [- "rustls-tls",- # 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: pure tool-UI rules only (`tinymcp::ui`). The MCP runtime itself runs++# as a module behind `tinymcp-bus`.++tinymcp = { path = "../../vendor/tinymcp/crates/tinymcp", default-features = false, features = ["ui"] }tinymcp-bus = { path = "../../vendor/tinymcp/crates/tinymcp-bus", features = ["schemars"] }# The transport-free channel vocabulary: inbound envelopes, outbound intents,# the config schema, controller metadata and relay frames. UNCONDITIONAL — `DomainEvent` embedsdiff --cc crates/openhuman-core/src/mcp/host.rsindex e2abcefccb,306bce8e36..d5facebded--- a/crates/openhuman-core/src/mcp/host.rs+++ b/crates/openhuman-core/src/mcp/host.rs@@@ -449,16 -48,10 +48,11 @@@ pub fn client_config(config: &Config) -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();+ client.client_identity.capabilities = tinymcp::ui::client_capabilities();-client.registry_auth = config.mcp_client.registry_auth.clone();- // The documentation server is deliberately not seeded as an MCP server:- // `gitbooks_search` / `gitbooks_get_page` are hard-coded deferred tools- // (`tools::implementations::network::gitbooks`). Seeding it here made every- // first turn dial the endpoint for `tools/list` and register the generic- // MCP bridge tools for nothing.-+ // GitBooks uses dedicated deferred tools and is not part of the configured+ // server set, so first-turn tool assembly never dials it for a catalog.client}diff --cc crates/openhuman-core/src/mcp/mod.rsindex 4f9ef7f0ed,bc1236ad57..74ad96b90a--- a/crates/openhuman-core/src/mcp/mod.rs+++ b/crates/openhuman-core/src/mcp/mod.rs@@@ -194,32 -195,9 +208,11 @@@ pub mod auditpub mod host;pub mod registry;pub mod server;+#[cfg(feature = "mcp")]+pub mod ui;- /// The Streamable HTTP transport, from the wire contract's implementation.- ///- /// Re-exported under the path this module used to define it at. The bespoke- /// documentation tool and the observability classifier both name these, and- /// neither is gated — so this is not either, exactly as before the extraction.+ /// MCP wire-contract response types used by host adapters.pub mod http_client {- pub use tinymcp::transport::http::{McpHttpClient, McpHttpClientBuilder};- /// The transport's error, re-exported so a caller can inspect a failure- /// structurally rather than by its rendered text.- ///- /// The variant that motivates it is [`McpError::Unauthorized`], whose- /// `resource_metadata` is what separates a server that wants OAuth from one- /// that wants a static credential — the difference between offering a sign-in- /// path and asking for a token. That field is deliberately absent from the- /// message, so a caller wanting it must have the type.- ///- /// Note this crate's own `core::observability` classifier does **not** use- /// it: it reads rendered text, because it classifies failures that have- /// already crossed an RPC boundary and arrive as strings. This re-export is- /// for an in-process consumer, which holds the real error and should not be- /// reduced to matching on wording that upstream is free to reword.- pub use tinymcp::Error as McpError;- pub use tinymcp::{redact_endpoint, render_tool_result};pub use tinymcp_bus::{AuthorizationServerMetadata, McpAuthChallenge, McpAuthorizationContext,McpInitializeResult, McpRemoteTool, McpServerToolResult, McpSseEvent,diff --cc crates/openhuman-core/src/mcp/registry/action_tool.rsindex d66ce0d1e9,6e9d30347a..c2e2544fe5--- a/crates/openhuman-core/src/mcp/registry/action_tool.rs+++ b/crates/openhuman-core/src/mcp/registry/action_tool.rs@@@ -191,6 -118,72 +118,74 @@@ impl Tool for InstalledServerTool}}+ impl InstalledServerTool {+ async fn execute_inner(&self, arguments: Value) -> anyhow::Result<ToolResult> {++ let tool_input = arguments.clone();+ let client = match McpConfiguredClient::for_config(&self.config) {+ Ok(client) => client,+ Err(_) => return Ok(ToolResult::error("MCP module is unavailable")),+ };+ let client_config = host::client_config(&self.config);+ let arguments: serde_json::Map<String, Value> = match client+ .call(+ &client_config,+ tinymcp_bus::names::methods::NORMALIZE_TOOL_ARGUMENTS,+ (Some(arguments),),+ )+ .await+ {+ Ok(arguments) => arguments,+ Err(_) => return Ok(ToolResult::error("invalid arguments for MCP tool")),+ };++ let outcome: tinymcp_bus::ToolCallOutcome = match client+ .call(+ &client_config,+ tinymcp_bus::names::methods::TOOL_CALL,+ (+ self.presentation.server_id.as_str(),+ self.presentation.remote_name.as_str(),+ Value::Object(arguments),+ ),+ )+ .await+ {+ Ok(outcome) => outcome,+ Err(_) => return Ok(ToolResult::error("MCP tool call failed")),+ };+ let rendered: String = match client+ .call::<String>(+ &client_config,+ tinymcp_bus::names::methods::RENDER_TOOL_OUTPUT,+ (tinymcp_bus::RenderToolOutputRequest {+ result: outcome.rendered.clone(),+ format: tinymcp_bus::ToolOutputFormat::Llm,+ prefer_markdown: true,+ },),+ )+ .await+ {+ Ok(rendered) => rendered,+ Err(_) => return Ok(ToolResult::error("MCP tool output is unavailable")),+ };+ let mut result = ToolResult {+ content: vec![ToolContent::Text { text: rendered }],+ is_error: outcome.rendered.is_error,+ ..ToolResult::default()+ };+ result.metadata = Some(+ tinymcp_bus::McpResultEnvelope::new(+ &self.presentation.server_id,+ &self.presentation.remote_name,+ &outcome.rendered,+ )+ .to_metadata(),+ );++ crate::mcp::ui::decorate_result(None, &tool_input, &mut result);+ Ok(result)+ }+ }+#[cfg(test)]#[path = "action_tool_tests.rs"]mod tests;diff --cc crates/openhuman-core/src/mcp/registry/tools.rsindex 02a13ab227,031d653175..c8e12f338d--- a/crates/openhuman-core/src/mcp/registry/tools.rs+++ b/crates/openhuman-core/src/mcp/registry/tools.rs@@@ -259,37 -258,17 +258,30 @@@ impl Tool for McpRegistryToolCallTool// Tolerant at execution, unchanged in the schema: an object that// arrived JSON-encoded in a string is decoded, and anything that// cannot hold one is refused here, naming what arrived.- let arguments = normalize_tool_arguments(args.get("arguments").cloned())- .map(Value::Object)- .map_err(|error| anyhow::anyhow!("mcp_registry_tool_call: {error}"))?;+ let client = crate::mcp::module_client::McpConfiguredClient::for_config(&self.config)+ .map_err(|_| anyhow::anyhow!("mcp_registry_tool_call: MCP module is unavailable"))?;+ let normalized: serde_json::Map<String, Value> = client- .normalize_tool_arguments(args.get("arguments").cloned())++ .normalize_tool_arguments(args.get("arguments").cloned().unwrap_or(Value::Null))+ .await+ .map_err(|_| anyhow::anyhow!("mcp_registry_tool_call: invalid tool arguments"))?;- emit!(- ops::mcp_clients_tool_call(&self.config, sid, tool_name, Value::Object(normalized),)- .await,- "mcp_registry_tool_call"++ let arguments = Value::Object(normalized);+ let outcome = ops::mcp_clients_tool_call(+ &self.config,+ sid.clone(),+ tool_name.clone(),+ arguments.clone(),)+ .await+ .map_err(|e| anyhow::anyhow!("mcp_registry_tool_call: {e}"))?;+ let mut result = ToolResult::success(serde_json::to_string(&outcome.value)?);- let raw = outcome.value.get("result").filter(|raw| raw.is_object());- if let Some(raw) = raw {- let tool_meta = match crate::mcp::host::for_config(&self.config) {- Ok(service) => {- service- .dynamic()- .connections()- .tool_meta(&sid, &tool_name)- .await- }- Err(_) => None,- };++ if let Some(raw) = outcome.value.get("result").filter(|raw| raw.is_object()) {+ let view = crate::mcp::ui::resolve::view_from_raw_result(- &sid, &tool_name, tool_meta, arguments, raw,++ &sid, &tool_name, None, arguments, raw,+ );+ result.metadata = crate::mcp::ui::resolve::presentation_from_view(&view)+ .map(|presentation| presentation.to_metadata());+ }+ Ok(result)}}diff --cc crates/openhuman-core/src/mcp/ui/decorate.rsindex b102d2dc4f,0000000000..c120830f00mode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/ui/decorate.rs+++ b/crates/openhuman-core/src/mcp/ui/decorate.rs@@@ -1,251 -1,0 +1,252 @@@+//! 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 crate::mcp::module_client::McpConfiguredClient;++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>),++ /// No descriptor `_meta` is available; only the result's own metadata is++ /// read.++ Absent,++ /// Configured servers: the module's live listing.++ Configured(Arc<Config>),+}++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),++ Self::Absent => None,++ Self::Configured(config) => configured_tool_meta(config, server, tool).await,+ }+ }+}+++async fn configured_tool_meta(config: &Config, server: &str, tool: &str) -> Option<Value> {++ let client = McpConfiguredClient::for_config(config).ok()?;++ let client_config = host::client_config(config);++ let listed: Vec<tinymcp_bus::McpRemoteTool> = client++ .call(++ &client_config,++ tinymcp_bus::names::methods::STATIC_LIST_TOOLS,++ (server,),++ )++ .await++ .ok()?;++ listed++ .into_iter()++ .find(|remote| remote.name == tool)++ .and_then(|remote| remote.meta)++}+++/// 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 --cc crates/openhuman-core/src/mcp/ui/decorate_tests.rsindex 1f2c007196,0000000000..71a56c3199mode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/ui/decorate_tests.rs+++ b/crates/openhuman-core/src/mcp/ui/decorate_tests.rs@@@ -1,206 -1,0 +1,196 @@@+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()))++ MetaLookup::Absent+}++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})- );- }-+#[tokio::test]+async fn wrapper_forwards_every_inner_tool_property() {+ let tool = UiAwareTool::new(+ Box::new(Fixed(ToolResult::success("plain"))),+ no_lookup(),+ ToolInput::Direct,+ );+ let args = json!({});+ assert_eq!(tool.name(), "mcp_shop_order");+ assert_eq!(tool.description(), "order");+ assert_eq!(tool.parameters_schema(), json!({"type": "object"}));+ let inner = Fixed(ToolResult::success("plain"));+ assert_eq!(tool.permission_level(), inner.permission_level());+ assert_eq!(+ tool.permission_level_with_args(&args),+ inner.permission_level_with_args(&args)+ );+ assert_eq!(tool.scope(), inner.scope());+ assert_eq!(tool.category(), inner.category());+ assert_eq!(tool.family(), inner.family());+ assert_eq!(tool.policy(), inner.policy());+ assert_eq!(+ tool.injected_arguments().len(),+ inner.injected_arguments().len()+ );+ assert_eq!(tool.supports_markdown(), inner.supports_markdown());+ assert_eq!(+ tool.is_concurrency_safe(&args),+ inner.is_concurrency_safe(&args)+ );+ assert_eq!(tool.external_effect(), inner.external_effect());+ assert_eq!(+ tool.external_effect_with_args(&args),+ inner.external_effect_with_args(&args)+ );+ assert_eq!(tool.max_result_size_chars(), inner.max_result_size_chars());+ assert_eq!(tool.timeout_policy(&args), inner.timeout_policy(&args));+ assert_eq!(+ tool.host_extension().is_some(),+ inner.host_extension().is_some()+ );+ assert_eq!(+ tool.host_call_extension(&args).is_some(),+ inner.host_call_extension(&args).is_some()+ );+ assert_eq!(tool.spec().name, inner.spec().name);+ assert_eq!(tool.display_label(&args), inner.display_label(&args));+ assert_eq!(tool.display_detail(&args), inner.display_detail(&args));+ assert_eq!(tool.return_direct(), inner.return_direct());+}++#[tokio::test]+async fn option_and_context_entry_points_present_the_widget() {+ let build = || {+ UiAwareTool::new(+ Box::new(Fixed(result_with(+ envelope(json!({"meta": {"ui": {"resourceUri": "ui://shop/cart"}}})),+ "Order placed",+ ))),+ no_lookup(),+ ToolInput::Direct,+ )+ };+ let with_options = build()+ .execute_with_options(json!({}), ToolCallOptions::default())+ .await+ .unwrap();+ assert_eq!(with_options.metadata.unwrap()["kind"], "mcp_ui");+ let with_context = build()+ .execute_with_context(json!({}), ToolCallOptions::default(), None)+ .await+ .unwrap();+ assert_eq!(with_context.metadata.unwrap()["kind"], "mcp_ui");+}++#[tokio::test]- async fn installed_lookup_without_a_host_has_no_meta() {++async fn configured_lookup_without_a_module_has_no_meta() {+ let workspace = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.workspace_dir = workspace.path().to_path_buf();- let lookup = MetaLookup::Installed(Arc::new(config));++ let lookup = MetaLookup::Configured(Arc::new(config));+ assert!(lookup.tool_meta("shop", "order").await.is_none());+}diff --cc crates/openhuman-core/src/mcp/ui/discovery.rsindex 4bd53f390f,0000000000..ab15a0313cmode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/ui/discovery.rs+++ b/crates/openhuman-core/src/mcp/ui/discovery.rs@@@ -1,114 -1,0 +1,46 @@@- //! What a server declares for UI, logged when it connects.++//! What a configured server declares for UI, logged when its tools are listed.+//!+//! One line per tool that sends `_meta` (its keys, plus any widget template- //! URI) and one per resource. Only names, keys and `ui://` URIs are logged,++//! URI). Only names, keys and `ui://` URIs are logged,+//! never values that could carry data.+- use std::sync::Arc;-+use serde_json::Value;+- use crate::mcp::host::{self, McpHost};-- use super::resolve::is_ui_uri;-+fn template_uri(meta: &Value) -> Option<String> {+ tinymcp::ui::template_from_meta(meta).map(|(uri, _)| uri)+}++fn meta_keys(meta: &Value) -> Vec<String> {+ let Some(map) = meta.as_object() else {+ return Vec::new();+ };+ let mut keys: Vec<String> = map.keys().cloned().collect();+ if let Some(ui) = map.get("ui").and_then(Value::as_object) {+ keys.extend(ui.keys().map(|key| format!("ui.{key}")));+ }+ keys+}++fn log_tool(server: &str, tool: &str, meta: &Value) {+ tracing::info!(+ server = %server,+ tool = %tool,+ meta_keys = ?meta_keys(meta),+ template = ?template_uri(meta),+ "[mcp-ui] tool _meta"+ );+}+- fn log_resource(server: &str, uri: &str, mime: Option<&str>) {- let shown = if is_ui_uri(uri) {- uri- } else {- "<non-ui resource>"- };- tracing::info!(- server = %server,- uri = %shown,- mime = ?mime,- "[mcp-ui] resource"- );- }-- /// Logs an installed server's declared UI.- pub async fn log_installed_server(host: &McpHost, server_id: &str) {- let connections = host.dynamic().connections();- let tools = connections.tools_for(server_id).await.unwrap_or_default();- let metas = connections.tool_metas(server_id).await.unwrap_or_default();- tracing::info!(- server = %server_id,- tools = tools.len(),- with_meta = metas.len(),- "[mcp-ui] server connected"- );- let mut names: Vec<&String> = metas.keys().collect();- names.sort();- for name in names {- log_tool(server_id, name, &metas[name]);- }- match connections.list_resources(server_id).await {- Ok(resources) => {- for resource in resources {- log_resource(server_id, &resource.uri, resource.mime_type.as_deref());- }- }- Err(error) => {- tracing::info!(server = %server_id, %error, "[mcp-ui] resources/list unavailable")- }- }- }-- /// [`log_installed_server`] in the background, against the process host.- pub fn spawn_log_installed(server_id: String) {- let Some(service) = host::try_service() else {- return;- };- let Ok(handle) = tokio::runtime::Handle::try_current() else {- return;- };- handle.spawn(async move {- log_installed_server(&service, &server_id).await;- });- }-- /// Logs every connected installed server on `host`.- pub async fn log_all_installed(host: Arc<McpHost>) {- for server in host.dynamic().connected_overview().await {- log_installed_server(&host, &server.server_id).await;- }- }-+/// Logs a configured server's declared UI, from the tools it just listed.+pub fn log_configured_server(server: &str, tools: &[tinymcp_bus::McpRemoteTool]) {+ tracing::info!(server = %server, tools = tools.len(), "[mcp-ui] configured server listed");+ for tool in tools {+ if let Some(meta) = tool.meta.as_ref() {+ log_tool(server, &tool.name, meta);+ }+ }+}++#[cfg(test)]+#[path = "discovery_tests.rs"]+mod tests;diff --cc crates/openhuman-core/src/mcp/ui/discovery_tests.rsindex aada7d8316,0000000000..9df9f4f86bmode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/ui/discovery_tests.rs+++ b/crates/openhuman-core/src/mcp/ui/discovery_tests.rs@@@ -1,59 -1,0 +1,42 @@@+use super::*;+use serde_json::json;++#[test]+fn meta_keys_include_ui_members() {+ let keys = meta_keys(&json!({"ui": {"resourceUri": "ui://a", "visibility": ["app"]}, "x": 1}));+ assert!(keys.contains(&"ui".to_string()));+ assert!(keys.contains(&"ui.resourceUri".to_string()));+ assert!(keys.contains(&"x".to_string()));+}++fn remote_tool(value: serde_json::Value) -> tinymcp_bus::McpRemoteTool {+ serde_json::from_value(value).expect("remote tool")+}++#[test]+fn meta_keys_of_a_non_object_are_empty() {+ assert!(meta_keys(&json!("text")).is_empty());+ assert!(meta_keys(&json!(null)).is_empty());+}++#[test]- fn logging_a_tool_and_resources_does_not_expose_values() {++fn logging_a_tool_does_not_expose_values() {+ log_tool(+ "shop",+ "order",+ &json!({"ui": {"resourceUri": "ui://shop/cart"}}),+ );- log_resource("shop", "ui://shop/cart", Some("text/html"));- log_resource("shop", "file:///secret", None);+}++#[test]+fn configured_server_logs_every_tool_with_meta() {+ let tools = vec![+ remote_tool(json!({+ "name": "order",+ "inputSchema": {"type": "object"},+ "_meta": {"ui": {"resourceUri": "ui://shop/cart"}}+ })),+ remote_tool(json!({"name": "plain", "inputSchema": {"type": "object"}})),+ ];+ log_configured_server("shop", &tools);+}-- #[tokio::test]- async fn installed_server_with_no_connection_logs_nothing_to_list() {- let workspace = tempfile::tempdir().unwrap();- let mut config = crate::config::Config::default();- config.workspace_dir = workspace.path().to_path_buf();- let host = host::for_config(&config).expect("host");- log_installed_server(&host, "missing").await;- log_all_installed(Arc::clone(&host)).await;- }-- #[tokio::test]- async fn spawning_a_log_without_a_runtime_host_is_a_no_op() {- spawn_log_installed("missing".to_string());- }diff --cc crates/openhuman-core/src/mcp/ui/mod.rsindex 0157fa4e96,0000000000..d8e23ecef9mode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/ui/mod.rs+++ b/crates/openhuman-core/src/mcp/ui/mod.rs@@@ -1,50 -1,0 +1,50 @@@+//! Tool-provided UI in the chat: MCP Apps widgets, OpenAI Apps SDK widgets,+//! skill views, and the links a tool result offers.+//!+//! - [`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`].+//! - [`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 discovery;+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;++/// `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.++/// `mcp_call_tool` over the configured servers, 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>,++ config: &std::sync::Arc<crate::config::Config>,+) -> Box<dyn tinytools::Tool> {+ Box::new(UiAwareTool::new(+ call,- decorate::MetaLookup::Configured(std::sync::Arc::clone(registry)),++ decorate::MetaLookup::Configured(std::sync::Arc::clone(config)),+ decorate::ToolInput::Nested("arguments"),+ ))+}diff --cc crates/openhuman-core/src/mcp/ui/port.rsindex 9bc516d09c,0000000000..736dbbfb36mode 100644,000000..100644--- a/crates/openhuman-core/src/mcp/ui/port.rs+++ b/crates/openhuman-core/src/mcp/ui/port.rs@@@ -1,157 -1,0 +1,188 @@@+//! 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.++//! [`HostUiPort`] answers them through this workspace's TinyMCP module:++//! installed servers by their connection, configured servers by the static++//! set. The module contract has no `resources/read`, so a widget document is++//! only available when the tool result embedded it. Tests substitute their++//! own port.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::Value;- use tinymcp::McpRemoteToolExt;++use crate::config::Config;+use crate::mcp::host;- use crate::mcp::registry::connections;++use crate::mcp::module_client::McpConfiguredClient;++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.++/// [`UiServerPort`] over `config`'s TinyMCP module.+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()++ fn client(&self) -> Option<Arc<McpConfiguredClient>> {++ McpConfiguredClient::for_config(&self.config).ok()++ }++++ async fn is_static(&self, server_id: &str) -> bool {++ let Some(client) = self.client() else {++ return false;++ };++ let listed: Result<Vec<String>, _> = client++ .call(++ &host::client_config(&self.config),++ tinymcp_bus::names::methods::STATIC_LIST,++ (),++ )++ .await;++ listed.is_ok_and(|servers| servers.iter().any(|name| name == server_id))++ }++++ async fn is_installed_connected(&self, server_id: &str) -> bool {++ let Some(client) = self.client() else {++ return false;++ };++ let statuses: Result<Vec<tinymcp_bus::ConnStatus>, _> = client++ .call(++ &host::client_config(&self.config),++ tinymcp_bus::names::methods::STATUS,++ (),++ )++ .await;++ statuses.is_ok_and(|statuses| {++ statuses.iter().any(|status| {++ status.server_id == server_id++ && status.status == tinymcp_bus::ServerStatus::Connected++ })++ })+ }+}++#[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)++ self.is_installed_connected(server_id).await || self.is_static(server_id).await+ }++ 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 client = self.client()?;++ let client_config = host::client_config(&self.config);++ if self.is_installed_connected(server_id).await {++ let live: Vec<tinymcp_bus::McpTool> = client++ .call(++ &client_config,++ tinymcp_bus::names::methods::LIST_TOOLS,++ (server_id,),++ )++ .await++ .ok()?;+ 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,++ meta: None,+ annotations: None,+ });+ }- let registry = host::static_registry(&self.config);- registry.get(server_id)?;- let listed = registry- .list_tools(server_id)++ let listed: Vec<tinymcp_bus::McpRemoteTool> = client++ .call(++ &client_config,++ tinymcp_bus::names::methods::STATIC_LIST_TOOLS,++ (server_id,),++ )+ .await+ .map_err(|error| {- tracing::debug!(server_id, %error, "[mcp_ui] could not list tools");++ tracing::debug!(server_id, ?error, "[mcp_ui] could not list tools");+ })+ .ok()?;++ let listed = client++ .scrub_static_tools(&client_config, server_id, listed)++ .await++ .ok()?;++ let meta = listed++ .iter()++ .find(|remote| remote.name == tool)++ .and_then(|remote| remote.meta.clone());+ 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,- }++ .map(|remote| tinymcp_bus::McpTool {++ description: remote.description.or(remote.title),++ name: remote.name,++ input_schema: remote.input_schema,+ })+ .collect(),+ );+ safe.iter().find(|candidate| candidate.name == tool)?;+ Some(UiToolDescriptor {- meta: registry.tool_meta(server_id, tool),++ meta,+ 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()++ tracing::debug!(++ server_id,++ uri,++ "[mcp_ui] resources/read is not part of the TinyMCP module contract"++ );++ Err("this server's widget document is not embedded in its tool result".to_string())+ }++ 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)++ let client = self.client().ok_or("MCP module is unavailable")?;++ let client_config = host::client_config(&self.config);++ let member = if self.is_installed_connected(server_id).await {++ tinymcp_bus::names::methods::TOOL_CALL++ } else {++ tinymcp_bus::names::methods::STATIC_CALL_TOOL++ };++ let outcome: tinymcp_bus::ToolCallOutcome = client++ .call_confidential(&client_config, member, (server_id, tool, arguments))+ .await- .map(|result| result.raw_result)- .map_err(|error| error.to_string())++ .map_err(|error| {++ tracing::debug!(server_id, tool, ?error, "[mcp_ui] widget tool call failed");++ "MCP tool call failed".to_string()++ })?;++ Ok(outcome.result)+ }+}++#[cfg(test)]+#[path = "port_tests.rs"]+mod tests;diff --cc crates/openhuman-core/src/tools/impl/network/mcp_server_tools.rsindex d31d591495,7caeff57b5..2ff12f2fa8--- a/crates/openhuman-core/src/tools/impl/network/mcp_server_tools.rs+++ b/crates/openhuman-core/src/tools/impl/network/mcp_server_tools.rs@@@ -206,53 -98,77 +98,84 @@@ impl Tool for ModuleConfiguredMcpServerasync fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {self.security.enforce_tool_operation(ToolOperation::Act, self.name())- .map_err(|err| anyhow::anyhow!(err))?;- let server = self.inner.server_id();- let tool = self.inner.remote_name();- let config =- crate::config::ops::reload_config_from_paths(&self.config_path, &self.workspace_dir)- .await- .map_err(|error| anyhow::anyhow!("could not reload MCP configuration: {error}"))?;- let current_registry = crate::mcp::host::static_registry(&config);- let Some(current_definition) = current_registry.get(server) else {- anyhow::bail!("MCP server is no longer configured: {server}");- };- let Some(captured_definition) = self.registry.get(server) else {- anyhow::bail!("MCP server is no longer configured: {server}");- };- if current_definition.fingerprint() != captured_definition.fingerprint() {- anyhow::bail!(- "MCP server configuration changed; rebuild tools before calling {server}"- );+ .map_err(|error| anyhow::anyhow!(error))?;+ let current = crate::config::ops::reload_config_from_paths(+ &self.config.config_path,+ &self.config.workspace_dir,+ )+ .await+ .map_err(|_| anyhow::anyhow!("could not reload MCP configuration"))?;+ let current_server = current+ .mcp_client+ .servers+ .iter()+ .find(|server| server.server.name == self.presentation.server_id)+ .map(|server| &server.server)+ .ok_or_else(|| anyhow::anyhow!("MCP server is no longer configured"))?;+ if current_server != &self.server {+ anyhow::bail!("MCP server configuration changed; rebuild tools before calling");}- let live = current_registry.list_tools(server).await?;++ let client = crate::mcp::module_client::McpConfiguredClient::for_config(&self.config)+ .map_err(|_| anyhow::anyhow!("TinyMCP module is unavailable"))?;+ let client_config = crate::mcp::host::client_config(&self.config);+ let live: Vec<tinymcp_bus::McpRemoteTool> = client+ .call(+ &client_config,+ tinymcp_bus::names::methods::STATIC_LIST_TOOLS,+ (self.presentation.server_id.as_str(),),+ )+ .await+ .map_err(|_| anyhow::anyhow!("MCP tool is unavailable"))?;+ let live = client+ .scrub_static_tools(&client_config, &self.presentation.server_id, live)+ .await+ .map_err(|_| anyhow::anyhow!("MCP tool metadata is unavailable"))?;++ let tool_meta = live++ .iter()++ .find(|tool| tool.name == self.presentation.remote_name)++ .and_then(|tool| tool.meta.clone());let safe = crate::mcp::registry::tools_safe_for_agent(- server,+ &self.presentation.server_id,live.into_iter()- .map(|remote| {- let description = remote.display_description();- tinymcp_bus::McpTool {- name: remote.name,- description,- input_schema: remote.input_schema,- }+ .map(|tool| tinymcp_bus::McpTool {+ name: tool.name,+ description: tool.description.or(tool.title),+ input_schema: tool.input_schema,}).collect(),);- if !safe.iter().any(|candidate| candidate.name == tool) {- anyhow::bail!("MCP tool is no longer available or safe: {server}/{tool}");+ if !safe+ .iter()+ .any(|tool| tool.name == self.presentation.remote_name)+ {+ anyhow::bail!("MCP tool is no longer available or safe");}- let mut result = self- .inner- .execute(args.clone())+ let arguments = client+ .normalize_tool_arguments(args).await- .map_err(|error| anyhow::anyhow!(self.scrubber.scrub_error(&error)))?;- if let Some(metadata) = result.metadata.as_mut() {- crate::mcp::ui::decorate::scrub_strings(metadata, &|text| self.scrubber.scrub(text));- }- let tool_meta = current_registry.tool_meta(server, tool);- crate::mcp::ui::decorate_result(tool_meta.as_ref(), &args, &mut result);- Ok(self.scrubber.scrub_result(result))+ .map_err(|error| anyhow::anyhow!(super::mcp::input_module_error_message(error)))?;++ let tool_input = Value::Object(arguments.clone());+ let call: tinymcp_bus::ClassifiedStaticToolCall = client+ .call_confidential(+ &client_config,+ tinymcp_bus::names::methods::STATIC_CALL_TOOL_CLASSIFIED,+ (+ self.presentation.server_id.as_str(),+ self.presentation.remote_name.as_str(),+ Value::Object(arguments),+ ),+ )+ .await+ .map_err(|_| anyhow::anyhow!("MCP tool call failed"))?;- Ok(super::mcp::classified_result(++ let mut result = super::mcp::classified_result(+ call,+ &self.presentation.server_id,+ &self.presentation.remote_name,+ false,- ))++ );++ crate::mcp::ui::decorate_result(tool_meta.as_ref(), &tool_input, &mut result);++ Ok(result)}}diff --cc crates/openhuman-core/src/tools/ops.rsindex f0c5798a2e,2aadced35c..3384811f0e--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@@ -375,45 -377,14 +377,17 @@@ pub fn all_tools_with_runtime// `mcp::registry` domain gated above. Both are compiled out by the `mcp`// feature; see the static-vs-dynamic note in AGENTS.md.#[cfg(feature = "mcp")]- {- tools.push(crate::mcp::ui::show_ui_tool(root_config));- let mcp_registry = {- // Built from the converted configuration, which is the one place- // the two vocabularies meet. A registry that cannot be built is- // logged and treated as empty: a malformed proxy or TLS setting- // must not take the whole tool surface down with it.- let base = crate::mcp::host::static_registry(root_config);- Arc::new(base)- };- log::debug!(- "[tools::ops][mcp_client] static servers={}",- mcp_registry.list().len()- );- if !mcp_registry.is_empty() {- tools.push(Box::new(McpListServersTool::new(Arc::clone(&mcp_registry))));- tools.push(Box::new(McpListToolsTool::new(Arc::clone(&mcp_registry))));- let call = Box::new(mcp_call_tool(Arc::clone(&mcp_registry), security.clone()));- tools.push(crate::mcp::ui::ui_aware_call(call, &mcp_registry));- tracing::debug!(- count = mcp_registry.list().len(),- "[mcp_client] registered generic MCP bridge tools"- );- // And every cached server tool as its own `mcp_<server>_<tool>`,- // deferred unless the server asks for direct exposure. Names- // already taken keep their owner.- let reserved: std::collections::HashSet<String> =- tools.iter().map(|tool| tool.name().to_string()).collect();- tools.extend(- crate::tools::implementations::network::configured_server_tools(- root_config,- &mcp_registry,- security,- &reserved,- ),- );- } else {- tracing::debug!("[mcp_client] no MCP servers registered — bridge tools skipped");- }++ tools.push(crate::mcp::ui::show_ui_tool(root_config));++ #[cfg(feature = "mcp")]+ if root_config.mcp_client.enabled && !root_config.mcp_client.servers.is_empty() {+ // Catalog retrieval runs in the async turn prelude. This synchronous+ // baseline contributes only the generic bridge; per-tool executors+ // are projected from the module-prepared snapshot there.+ let mcp_config = Arc::new(root_config.clone());+ tools.push(Box::new(McpListServersTool::new(Arc::clone(&mcp_config))));+ tools.push(Box::new(McpListToolsTool::new(Arc::clone(&mcp_config))));- tools.push(Box::new(mcp_call_tool(mcp_config, security.clone())));++ let call = Box::new(mcp_call_tool(Arc::clone(&mcp_config), security.clone()));++ tools.push(crate::mcp::ui::ui_aware_call(call, &mcp_config));}tools.extend(crate::search::build_search_tools(root_config));