use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{Value, json};
use tokio::sync::Mutex;
use trusty_common::stdio_mcp_client::{McpTool, StdioMcpClient};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub const MAX_INPUT_SCHEMA_BYTES: usize = 64 * 1024;
pub fn composed_name(server: &str, tool: &str) -> String {
format!("mcp__{server}__{tool}")
}
pub fn build_schema(server: &str, tool: &McpTool) -> Result<Value, String> {
let params = if tool.input_schema.is_object() {
let bytes = serde_json::to_vec(&tool.input_schema)
.map_err(|e| format!("its inputSchema could not be serialised: {e}"))?;
if bytes.len() > MAX_INPUT_SCHEMA_BYTES {
return Err(format!(
"its inputSchema is {} bytes, over the {MAX_INPUT_SCHEMA_BYTES}-byte cap",
bytes.len()
));
}
tool.input_schema.clone()
} else {
json!({"type": "object", "properties": {}})
};
Ok(json!({
"type": "function",
"function": {
"name": composed_name(server, &tool.name),
"description": format!(
"[{server}] {}",
tool.description.clone().unwrap_or_default()
),
"parameters": params,
}
}))
}
pub fn render_result(result: &Value) -> String {
let frames: Vec<&str> = result
.get("content")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(|item| item.get("text").and_then(Value::as_str))
.collect()
})
.unwrap_or_default();
if frames.is_empty() {
return result.to_string();
}
frames.join("\n")
}
pub fn is_mcp_error(result: &Value) -> bool {
result
.get("isError")
.and_then(Value::as_bool)
.unwrap_or(false)
}
pub struct McpBridgeTool {
name: String,
remote: String,
server: String,
schema: Value,
client: Arc<Mutex<StdioMcpClient>>,
}
impl McpBridgeTool {
pub fn new(
server: &str,
tool: &McpTool,
client: Arc<Mutex<StdioMcpClient>>,
) -> Result<Self, String> {
Ok(Self {
name: composed_name(server, &tool.name),
remote: tool.name.clone(),
server: server.to_string(),
schema: build_schema(server, tool)?,
client,
})
}
pub fn server(&self) -> &str {
&self.server
}
}
#[async_trait]
impl ToolExecutor for McpBridgeTool {
fn name(&self) -> &str {
&self.name
}
fn schema(&self) -> Value {
self.schema.clone()
}
async fn execute(&self, args: Value) -> ToolResult {
let mut client = self.client.lock().await;
match client.call_tool(&self.remote, args).await {
Ok(result) if is_mcp_error(&result) => {
let detail = render_result(&result);
tracing::warn!(
server = %self.server,
tool = %self.remote,
"mcp: tool reported an error",
);
ToolResult::err(format!(
"MCP tool '{}' on server '{}' reported an error: {detail}",
self.remote, self.server
))
}
Ok(result) => ToolResult::ok(render_result(&result)),
Err(e) => {
tracing::warn!(
server = %self.server,
tool = %self.remote,
error = %e,
"mcp: tool call failed",
);
ToolResult::err(format!(
"MCP tool '{}' on server '{}' failed: {e}",
self.remote, self.server
))
}
}
}
}