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