use crate::execution::ToolExecution;
use rmcp::ErrorData as McpError;
use serde::Serialize;
use serde_json::json;
pub(crate) fn build_tool_response<T: Serialize>(
execution: ToolExecution<T>,
include_version: bool,
) -> Result<serde_json::Value, McpError> {
let mut response = serde_json::Map::new();
if include_version {
response.insert("version".to_string(), json!("2024-11-05"));
}
let data = serde_json::to_value(&execution.data)
.map_err(|e| McpError::internal_error(format!("Failed to serialize result: {e}"), None))?;
response.insert("data".to_string(), data);
response.insert("execution_ms".to_string(), json!(execution.execution_ms));
if execution.used_index {
response.insert("used_index".to_string(), json!(true));
}
if execution.used_graph {
response.insert("used_graph".to_string(), json!(true));
}
if let Some(metadata) = execution.graph_metadata {
let metadata_value = serde_json::to_value(&metadata).map_err(|e| {
McpError::internal_error(format!("Failed to serialize graph_metadata: {e}"), None)
})?;
response.insert("graph_metadata".to_string(), metadata_value);
}
if let Some(token) = execution.next_page_token {
response.insert("next_page_token".to_string(), json!(token));
}
if let Some(total) = execution.total {
response.insert("total".to_string(), json!(total));
}
if let Some(truncated) = execution.truncated {
response.insert("truncated".to_string(), json!(truncated));
}
if let Some(scanned) = execution.candidates_scanned {
response.insert("candidates_scanned".to_string(), json!(scanned));
}
if !execution.workspace_path.is_empty() {
response.insert(
"workspace_path".to_string(),
json!(execution.workspace_path),
);
}
Ok(serde_json::Value::Object(response))
}