use rmcp::ErrorData;
use rmcp::model::Tool;
use serde_json::{Map, Value, json};
use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_str};
use lean_ctx::tool_defs::tool_def;
pub struct CtxHeatmapTool;
impl McpTool for CtxHeatmapTool {
fn name(&self) -> &'static str {
"ctx_heatmap"
}
fn tool_def(&self) -> Tool {
tool_def(
"ctx_heatmap",
"File access heatmap — shows most frequently accessed files per session.\n\
action=status (default) for summary, action=detail for per-file access counts.\n\
Identify hot files to optimize context usage.",
json!({
"type": "object",
"properties": {
"action": { "type": "string", "description": "status|detail" },
"path": { "type": "string" }
}
}),
)
}
fn handle(
&self,
args: &Map<String, Value>,
ctx: &ToolContext,
) -> Result<ToolOutput, ErrorData> {
let action = get_str(args, "action").unwrap_or_else(|| "status".to_string());
let path = jailed_path(args, ctx)?;
let result = crate::tools::ctx_heatmap::handle(&action, path.as_deref());
Ok(ToolOutput {
text: result,
original_tokens: 0,
saved_tokens: 0,
mode: Some(action),
path: None,
changed: false,
shell_outcome: None,
content_blocks: None,
})
}
}
fn jailed_path(args: &Map<String, Value>, ctx: &ToolContext) -> Result<Option<String>, ErrorData> {
if get_str(args, "path").is_none() {
return Ok(None);
}
if let Some(err) = ctx.path_error("path") {
return Err(ErrorData::invalid_params(format!("path: {err}"), None));
}
let resolved = ctx
.resolved_path("path")
.ok_or_else(|| ErrorData::invalid_params("path: not resolved by PathJail", None))?;
lean_ctx::core::workspace_authority::confine(resolved, &ctx.project_root, false)
.map(Some)
.map_err(|error| ErrorData::invalid_params(error, None))
}
#[cfg(test)]
mod tests {
use super::*;
fn args(path: &str) -> Map<String, Value> {
let mut map = Map::new();
map.insert("action".into(), json!("cold"));
map.insert("path".into(), json!(path));
map
}
#[test]
fn raw_path_without_a_jail_resolution_is_refused() {
let ctx = ToolContext::default();
assert!(jailed_path(&args("/etc"), &ctx).is_err());
}
#[test]
fn a_jail_refusal_is_returned_not_walked() {
let mut ctx = ToolContext::default();
ctx.path_errors
.insert("path".into(), "path escapes project root".into());
let err = jailed_path(&args("/etc"), &ctx).unwrap_err();
assert!(err.message.contains("escapes project root"), "{err:?}");
}
#[test]
fn the_resolved_path_is_used() {
let dir = tempfile::tempdir().unwrap();
let resolved = dir.path().to_string_lossy().to_string();
let mut ctx = ToolContext::default();
ctx.resolved_paths.insert("path".into(), resolved.clone());
assert_eq!(
jailed_path(&args("raw/other"), &ctx).unwrap().as_deref(),
Some(resolved.as_str())
);
assert_eq!(jailed_path(&Map::new(), &ctx).unwrap(), None);
}
}