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): delegate tool naming and presentation to the module
Steven Enamakel127c634e5e19
diff --git a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rsindex 3f187b7cf4..6524716364 100644--- a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs+++ b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs@@ -185,26 +185,64 @@ impl OpenHumanTurnPrelude {/// not connected.#[cfg(feature = "mcp")]async fn refresh_connected_mcp_tools(&self) {- let servers = match self.runtime_config.as_deref() {+ let config = match self.runtime_config.as_deref() {Some(config) => {- crate::mcp::registry::connections::cached_overview_for_config(config).await+ config+ }+ None => {+ self.mutable+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .connected_mcp_tools+ .clear();+ return;+ }+ };+ let servers = crate::mcp::registry::connections::cached_overview_for_config(config).await;+ let sources = servers+ .into_iter()+ .map(|server| tinymcp_bus::McpToolSourceSpec {+ server_id: server.server_id.clone(),+ label: server.qualified_name.clone(),+ family: server.qualified_name,+ display_name: server.display_name,+ tools: crate::mcp::registry::tools_safe_for_agent(+ &server.server_id,+ server.tools,+ ),+ default_exposure: tinymcp_bus::McpToolExposure::Deferred,+ direct_tools: Vec::new(),+ })+ .collect::<Vec<_>>();+ let prepared = match crate::mcp::module_client::McpConfiguredClient::for_config(config) {+ Ok(client) => {+ client+ .call(+ &crate::mcp::host::client_config(config),+ tinymcp_bus::names::methods::PREPARE_AGENT_TOOLS,+ (tinymcp_bus::PrepareAgentToolsRequest { sources },),+ )+ .await+ .unwrap_or_else(|error| {+ tracing::debug!(?error, "[mcp] module tool presentation unavailable");+ Vec::new()+ })+ }+ Err(error) => {+ tracing::debug!(?error, "[mcp] no module for tool presentation");+ Vec::new()}- None => Vec::new(),};- let count = servers- .iter()- .map(|server| server.tools.len())- .sum::<usize>();+ let count = prepared.len();tracing::debug!(agent = %self.agent_definition_id,- servers = servers.len(),tools = count,"[mcp] refreshed deferred tool catalogue");self.mutable.lock().unwrap_or_else(std::sync::PoisonError::into_inner)- .connected_mcp_tools = servers;+ .connected_mcp_tools = prepared;}/// Construct searchable MCP actions from the workspace's current snapshot.diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rsindex 5f3e73bc4d..f2fdb2a1b3 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -151,7 +151,7 @@ struct OpenHumanTurnPreludeMutable {/// Live MCP tool definitions for this workspace, refreshed before each/// turn so disconnects remove their deferred executors immediately.#[cfg(feature = "mcp")]- connected_mcp_tools: Vec<crate::mcp::registry::types::ConnectedServerOverview>,+ connected_mcp_tools: Vec<tinymcp_bus::McpToolPresentation>,/// `mcp_*` tool names a resumed thread was sent, so a tool recorded under/// its pre-readable hashed name is restored under that name too.#[cfg(feature = "mcp")]diff --git a/crates/openhuman-core/src/mcp/registry/action_tool.rs b/crates/openhuman-core/src/mcp/registry/action_tool.rsindex 24ac6d5510..c931fece68 100644--- a/crates/openhuman-core/src/mcp/registry/action_tool.rs+++ b/crates/openhuman-core/src/mcp/registry/action_tool.rs@@ -1,185 +1,178 @@-//! Agent tools for every action on the user's installed (`mcp.json`) servers.+//! Host adapters for the module-prepared tools on installed MCP servers.//!-//! The tools themselves are `tinymcp::tools::McpServerTool`s: named-//! `mcp_<server>_<tool>`, deferred so `tool_search` finds them, described and-//! schema'd from sanitized remote text. What stays here is this application's-//! policy, applied through [`InstalledServerInvoker`]:-//!-//! - remote definitions pass the prompt-injection scan-//! ([`super::tools_safe_for_agent`]) before they become tools, and again-//! against the live list at call time;-//! - a call reaches only a server that is connected now — the tool list may-//! come from the persistent cache, which is not an authorization;-//! - every call publishes `McpClientToolExecuted`.+//! TinyMCP prepares stable names, descriptions, schemas, exposure and tags.+//! This file applies OpenHuman's prompt-injection policy before preparation+//! and supplies the `tinytools::Tool` adapter that executes through TinyBus.use std::collections::HashSet;use std::sync::Arc;use std::time::Instant;use async_trait::async_trait;-use serde_json::Value;-use tinymcp::tools::{McpServerTool, McpToolInvoker, McpToolSource};-use tinymcp_bus::McpToolResult;-use tinytools::Tool;+use serde_json::{Value, json};+use tinytools::{PermissionLevel, Tool, ToolCategory, ToolContent, ToolExposure, ToolResult};use crate::config::Config;use crate::core::bus::BUS;use crate::core::events::DomainEvent;-use crate::mcp::host;--use super::connections;-use super::types::ConnectedServerOverview;--/// The name an installed server's tool is exposed under.-///-/// `mcp_<server>_<tool>_<digest>`: the server part from its qualified name,-/// plus a short digest of the install and tool so the name never changes-/// when another server with the same slug comes or goes; see-/// `tinymcp::tools::naming`.-#[must_use]-pub fn searchable_name(server_id: &str, qualified_name: &str, tool_name: &str) -> String {- tinymcp::tools::naming::disambiguated_tool_name(server_id, qualified_name, tool_name)-}+use crate::mcp::{host, module_client::McpConfiguredClient};-/// One deferred tool per action of each installed server in `servers`.-///-/// `servers` may come from the persistent tool cache-/// (`McpRegistry::cached_overview`), so tools appear before their server has-/// finished connecting; the invoker refuses a call until it has.+/// Creates deferred host adapters for the module-prepared tools in `tools`.pub fn deferred_connected_tools(config: Arc<Config>,- servers: &[ConnectedServerOverview],+ tools: &[tinymcp_bus::McpToolPresentation],) -> Vec<Box<dyn Tool>> {- server_tools(config, servers)- .into_iter()- .map(|tool| Box::new(tool) as Box<dyn Tool>)- .collect()+ deferred_connected_tools_with_legacy(config, tools, &HashSet::new())}-/// [`deferred_connected_tools`], plus a copy of any tool under the pre-readable-/// hashed name when `recorded` says the conversation was sent that name.+/// Restores previous tool names recorded in a frozen conversation.///-/// A resumed thread replays the tool names it recorded, so a thread started-/// before readable names keeps working without any file on disk changing.+/// A resumed session may contain a legacy hashed name. Its tool declaration+/// remains available under that exact name while the current module-prepared+/// name is also exposed.pub fn deferred_connected_tools_with_legacy(config: Arc<Config>,- servers: &[ConnectedServerOverview],+ tools: &[tinymcp_bus::McpToolPresentation],recorded: &HashSet<String>,) -> Vec<Box<dyn Tool>> {- let tools = server_tools(config, servers);- let aliases: Vec<McpServerTool> = tools- .iter()- .filter_map(|tool| {- let legacy = tool.legacy_name();- (recorded.contains(&legacy) && legacy != tool.name())- .then(|| tool.clone().renamed(legacy))- })- .collect();- if !aliases.is_empty() {- tracing::debug!(- aliases = aliases.len(),- "[mcp] restoring recorded tools under their earlier names"- );+ let mut result = Vec::with_capacity(tools.len() * 2);+ for presentation in tools {+ let tool = InstalledServerTool {+ config: Arc::clone(&config),+ presentation: presentation.clone(),+ name: presentation.name.clone(),+ };+ if recorded.contains(&presentation.legacy_name)+ && presentation.legacy_name != presentation.name+ {+ result.push(Box::new(InstalledServerTool {+ name: presentation.legacy_name.clone(),+ ..tool.clone()+ }) as Box<dyn Tool>);+ }+ result.push(Box::new(tool));}- tools- .into_iter()- .chain(aliases)- .map(|tool| Box::new(tool) as Box<dyn Tool>)- .collect()-}--fn server_tools(config: Arc<Config>, servers: &[ConnectedServerOverview]) -> Vec<McpServerTool> {- let sources: Vec<McpToolSource> = servers- .iter()- .map(|server| {- let mut source = McpToolSource::from_overview(server);- source.tools = super::tools_safe_for_agent(&server.server_id, server.tools.clone());- source- })- .collect();- let invoker: Arc<dyn McpToolInvoker> = Arc::new(InstalledServerInvoker { config });- tinymcp::tools::tools_for(&sources, &invoker)+ result}-/// Calls an installed server's tool under this application's policy.-#[derive(Debug)]-pub struct InstalledServerInvoker {+#[derive(Clone)]+struct InstalledServerTool {config: Arc<Config>,+ presentation: tinymcp_bus::McpToolPresentation,+ name: String,}-impl InstalledServerInvoker {- /// An invoker over `config`'s workspace.- #[must_use]- pub fn new(config: Arc<Config>) -> Self {- Self { config }+#[async_trait]+impl Tool for InstalledServerTool {+ fn name(&self) -> &str {+ &self.name}-}-#[async_trait]-impl McpToolInvoker for InstalledServerInvoker {- async fn invoke(- &self,- server_id: &str,- tool: &str,- arguments: Value,- ) -> tinymcp::Result<McpToolResult> {- let not_connected = || tinymcp::Error::NotConnected {- server: server_id.to_string(),- };- let live = connections::server_tools_for_config(&self.config, server_id)- .await- .ok_or_else(not_connected)?;- let safe = super::tools_safe_for_agent(server_id, live);- if !safe.iter().any(|candidate| candidate.name == tool) {- tracing::debug!(- server_id,- tool,- "[mcp] tool is no longer offered by the live server"- );- return Err(tinymcp::Error::ToolNotAllowed {- server: server_id.to_string(),- tool: tool.to_string(),- });+ fn description(&self) -> &str {+ &self.presentation.description+ }++ fn parameters_schema(&self) -> Value {+ self.presentation.parameters.clone()+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::Execute+ }++ fn external_effect(&self) -> bool {+ true+ }++ fn category(&self) -> ToolCategory {+ ToolCategory::Workflow+ }++ fn exposure(&self) -> ToolExposure {+ if self.presentation.deferred {+ ToolExposure::Deferred+ } else {+ ToolExposure::Direct}+ }++ fn family(&self) -> Option<&str> {+ Some(&self.presentation.family)+ }++ fn tags(&self) -> Vec<String> {+ self.presentation.tags.clone()+ }++ async fn execute(&self, arguments: Value) -> anyhow::Result<ToolResult> {let start = Instant::now();- let result = async {- let client = crate::mcp::module_client::McpConfiguredClient::for_config(&self.config)- .map_err(|error| {- tracing::debug!(?error, server_id, "[mcp] no module for workspace");- not_connected()- })?;- let outcome: tinymcp_bus::ToolCallOutcome = client- .call(- &host::client_config(&self.config),- tinymcp_bus::names::methods::TOOL_CALL,- (server_id, tool, arguments),- )- .await- .map_err(|error| {- tracing::debug!(?error, server_id, tool, "[mcp] module tool call failed");- not_connected()- })?;- Ok::<_, tinymcp::Error>(outcome.rendered)- }- .await;+ let result = self.execute_inner(arguments).await;let elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);BUS.publish(DomainEvent::McpClientToolExecuted {- server_id: server_id.to_string(),- tool_name: tool.to_string(),- success: result.is_ok(),+ server_id: self.presentation.server_id.clone(),+ tool_name: self.presentation.remote_name.clone(),+ success: result.as_ref().is_ok_and(|result| !result.is_error),elapsed_ms,});- tracing::debug!(- server_id,- tool,- elapsed_ms,- ok = result.is_ok(),- "[mcp] installed server tool call"- );result}}+impl InstalledServerTool {+ async fn execute_inner(&self, arguments: Value) -> anyhow::Result<ToolResult> {+ let client = McpConfiguredClient::for_config(&self.config)+ .map_err(|_| anyhow::anyhow!("MCP module is unavailable"))?;+ let client_config = host::client_config(&self.config);+ let arguments: serde_json::Map<String, Value> = client+ .call(+ &client_config,+ tinymcp_bus::names::methods::NORMALIZE_TOOL_ARGUMENTS,+ (Some(arguments),),+ )+ .await+ .map_err(|_| anyhow::anyhow!("invalid arguments for MCP tool"))?;++ let outcome: tinymcp_bus::ToolCallOutcome = 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+ .map_err(|_| anyhow::anyhow!("MCP tool call failed"))?;+ let rendered = 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+ .map_err(|_| anyhow::anyhow!("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(),+ );+ Ok(result)+ }+}+#[cfg(test)]#[path = "action_tool_tests.rs"]mod tests;