lean_ctx/tools/registered/
ctx_shape.rs1use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput};
7use crate::tool_defs::tool_def;
8
9pub struct CtxShapeTool;
20
21const MIN_SHAPE_BYTES: usize = 2_000;
26const MAX_SHAPE_BYTES: usize = 8 * 1024 * 1024;
29
30impl McpTool for CtxShapeTool {
31 fn name(&self) -> &'static str {
32 "ctx_shape"
33 }
34
35 fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
39 true
40 }
41
42 fn tool_def(&self) -> Tool {
43 tool_def(
44 "ctx_shape",
45 "Internal host hook: shape a native tool's output after it ran. Not for agents.",
46 json!({
47 "type": "object",
48 "properties": {
49 "tool": { "type": "string", "description": "Native tool name, e.g. Bash" },
50 "command": { "type": "string", "description": "Exact command line (Bash)" },
51 "exit_code": { "type": "integer", "description": "The command's exit code, when known" },
52 "output": { "type": "string", "description": "The native tool's output as the model would read it" }
53 },
54 "required": ["tool", "output"]
55 }),
56 )
57 }
58
59 fn handle(
60 &self,
61 args: &Map<String, Value>,
62 _ctx: &ToolContext,
63 ) -> Result<ToolOutput, ErrorData> {
64 let tool = args
65 .get("tool")
66 .and_then(Value::as_str)
67 .ok_or_else(|| ErrorData::invalid_params("tool is required", None))?;
68 let output = args
69 .get("output")
70 .and_then(Value::as_str)
71 .ok_or_else(|| ErrorData::invalid_params("output is required", None))?;
72 let command = args.get("command").and_then(Value::as_str);
73 let exit_code = args
74 .get("exit_code")
75 .and_then(Value::as_i64)
76 .and_then(|c| i32::try_from(c).ok());
77
78 let shaped = shape(tool, command, exit_code, output);
79 let original_tokens = crate::core::tokens::count_tokens(output);
80 let shaped_tokens = crate::core::tokens::count_tokens(&shaped);
81 Ok(ToolOutput {
82 text: shaped,
83 original_tokens,
84 saved_tokens: original_tokens.saturating_sub(shaped_tokens),
85 mode: Some("shape".to_string()),
86 path: None,
87 changed: false,
88 shell_outcome: None,
89 content_blocks: None,
90 })
91 }
92}
93
94fn shape(tool: &str, command: Option<&str>, exit_code: Option<i32>, output: &str) -> String {
96 if output.len() < MIN_SHAPE_BYTES || output.len() > MAX_SHAPE_BYTES {
97 return output.to_string();
98 }
99 let redacted = super::ctx_shell_background::redact_shell_output_secrets(output);
100 let shaped = match (tool, command) {
101 ("Bash", Some(cmd)) if !cmd.trim().is_empty() => {
102 crate::proxy::compress::shape_command_output(cmd, &redacted, exit_code)
103 }
104 _ => crate::proxy::compress::compress_tool_result(&redacted, Some(tool)),
105 };
106 if shaped.len() >= redacted.len() {
108 redacted
109 } else {
110 shaped
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 #[test]
119 fn outside_the_size_window_output_is_returned_verbatim() {
120 assert_eq!(shape("Bash", Some("ls"), Some(0), "a\nb\n"), "a\nb\n");
121 let huge = "x\n".repeat(MAX_SHAPE_BYTES / 2 + 1);
122 assert_eq!(shape("Bash", Some("cat big"), Some(0), &huge), huge);
123 }
124
125 #[test]
129 fn successful_build_output_is_folded_and_recoverable() {
130 use std::fmt::Write as _;
131 let _data = crate::core::data_dir::isolated_data_dir();
134 let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
137 let mut noisy = String::new();
138 for i in 0..400 {
139 let _ = writeln!(noisy, " Compiling crate-{i} v0.1.{i} (/tmp/x)");
140 }
141 noisy
142 .push_str(" Finished `dev` profile [unoptimized + debuginfo] target(s) in 42.17s\n");
143 let shaped = shape("Bash", Some("cargo build"), Some(0), &noisy);
144 assert!(
145 shaped.len() < noisy.len(),
146 "verbose cargo output must shrink"
147 );
148 assert!(
149 shaped.contains("Finished"),
150 "the build verdict must survive: {shaped}"
151 );
152 assert!(
153 shaped.contains("full original"),
154 "a lossy shrink must carry its recovery handle: {shaped}"
155 );
156
157 let mut opaque = String::new();
158 for i in 0..300 {
159 let _ = writeln!(opaque, "{i:x}{}", i * 7919);
160 }
161 assert!(shape("Grep", None, None, &opaque).len() <= opaque.len());
162 }
163}