lean_ctx/tools/registered/
ctx_feedback.rs1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_int, get_str};
6use crate::tool_defs::tool_def;
7
8pub struct CtxFeedbackTool;
9
10impl McpTool for CtxFeedbackTool {
11 fn name(&self) -> &'static str {
12 "ctx_feedback"
13 }
14
15 fn tool_def(&self) -> Tool {
16 tool_def(
17 "ctx_feedback",
18 "Record and report LLM token/latency metrics — use to track efficiency and optimize context usage.\n\
19 WORKFLOW: action=record during each LLM call, then action=report for readable summary.\n\
20 Actions: record (log event), report (readable summary), json (machine-readable),\n\
21 reset (clear data), status (storage info).\n\
22 ANTIPATTERN: not for debugging code behavior — this tracks token/latency stats only.\n\
23 record requires llm_input_tokens + llm_output_tokens.",
24 json!({
25 "type": "object",
26 "properties": {
27 "action": {
28 "type": "string",
29 "enum": ["record", "report", "json", "reset", "status"],
30 "description": "record (log event) | report (summary) | json (data) | reset (clear) | status (storage)"
31 },
32 "agent_id": { "type": "string", "description": "Agent ID (default: current agent)" },
33 "intent": { "type": "string", "description": "Intent/task string" },
34 "model": { "type": "string", "description": "Model identifier" },
35 "llm_input_tokens": { "type": "integer", "description": "Required for action=record" },
36 "llm_output_tokens": { "type": "integer", "description": "Required for action=record" },
37 "latency_ms": { "type": "integer", "description": "Latency in ms (for record)" },
38 "note": { "type": "string", "description": "Note (no prompts/PII)" },
39 "limit": { "type": "integer", "description": "Max recent events (default: 500)" }
40 }
41 }),
42 )
43 }
44
45 fn handle(
46 &self,
47 args: &Map<String, Value>,
48 ctx: &ToolContext,
49 ) -> Result<ToolOutput, ErrorData> {
50 let action = get_str(args, "action").unwrap_or_else(|| "report".to_string());
51 let limit = get_int(args, "limit").map_or(500, |n| n.max(1) as usize);
52
53 let result = match action.as_str() {
54 "record" => {
55 let current_agent_id = ctx
56 .agent_id
57 .as_ref()
58 .and_then(|a| tokio::task::block_in_place(|| a.blocking_read()).clone());
59 let agent_id = get_str(args, "agent_id").or(current_agent_id);
60 let agent_id = agent_id.ok_or_else(|| {
61 ErrorData::invalid_params(
62 "agent_id is required (or register an agent via project_root detection first)",
63 None,
64 )
65 })?;
66
67 let (ctx_read_last_mode, ctx_read_modes) = if let Some(ref tc) = ctx.tool_calls {
68 let calls = tokio::task::block_in_place(|| tc.blocking_read());
69 let mut last: Option<String> = None;
70 let mut modes: std::collections::BTreeMap<String, u64> =
71 std::collections::BTreeMap::new();
72 for rec in calls.iter().rev().take(50) {
73 if rec.tool != "ctx_read" {
74 continue;
75 }
76 if let Some(m) = rec.mode.as_ref() {
77 *modes.entry(m.clone()).or_insert(0) += 1;
78 if last.is_none() {
79 last = Some(m.clone());
80 }
81 }
82 }
83 (last, if modes.is_empty() { None } else { Some(modes) })
84 } else {
85 (None, None)
86 };
87
88 let llm_input_tokens = get_int(args, "llm_input_tokens").ok_or_else(|| {
89 ErrorData::invalid_params("llm_input_tokens is required", None)
90 })?;
91 let llm_output_tokens = get_int(args, "llm_output_tokens").ok_or_else(|| {
92 ErrorData::invalid_params("llm_output_tokens is required", None)
93 })?;
94 if llm_input_tokens <= 0 || llm_output_tokens <= 0 {
95 return Err(ErrorData::invalid_params(
96 "llm_input_tokens and llm_output_tokens must be > 0",
97 None,
98 ));
99 }
100
101 let ev = crate::core::llm_feedback::LlmFeedbackEvent {
102 agent_id,
103 intent: get_str(args, "intent"),
104 model: get_str(args, "model"),
105 llm_input_tokens: llm_input_tokens as u64,
106 llm_output_tokens: llm_output_tokens as u64,
107 latency_ms: get_int(args, "latency_ms").map(|n| n.max(0) as u64),
108 note: get_str(args, "note"),
109 ctx_read_last_mode,
110 ctx_read_modes,
111 timestamp: chrono::Local::now().to_rfc3339(),
112 };
113 crate::tools::ctx_feedback::record(&ev)
114 .unwrap_or_else(|e| format!("Error recording feedback: {e}"))
115 }
116 "status" => crate::tools::ctx_feedback::status(),
117 "json" => crate::tools::ctx_feedback::json(limit),
118 "reset" => crate::tools::ctx_feedback::reset(),
119 _ => crate::tools::ctx_feedback::report(limit),
120 };
121
122 Ok(ToolOutput {
123 text: result,
124 original_tokens: 0,
125 saved_tokens: 0,
126 mode: Some(action),
127 path: None,
128 changed: false,
129 shell_outcome: None,
130 content_blocks: None,
131 })
132 }
133}