Skip to main content

lean_ctx/tools/registered/
ctx_shape.rs

1// SPDX-License-Identifier: Apache-2.0
2use 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
9/// Shapes the output of a host-native tool *after* it ran (concept K2,
10/// "shape, don't redirect"): a host mod (Claude Code `tool.call`) forwards the
11/// native Bash stdout here instead of denying the call and forcing a round
12/// trip to `ctx_shell`. The text it rewrites gets lean-ctx's secret redaction,
13/// and the result flows through the same dispatch pipeline as every `ctx_*`
14/// output (sensitivity floor, policy-pack redaction, input filters).
15///
16/// Host-only surface: a host extension calls it directly (`$.mcp.call`); it is
17/// never advertised and refused through `ctx_call` — see
18/// `dynamic_tools::INTERNAL_HOST_TOOLS`.
19pub struct CtxShapeTool;
20
21/// Below this many **bytes** the shaping gain cannot pay for the call. Bytes,
22/// not chars: the Claude Code mod measures JavaScript string length (UTF-16
23/// units), and a text is never fewer bytes than UTF-16 units — so anything the
24/// mod sends clears this floor instead of slipping back unredacted.
25const MIN_SHAPE_BYTES: usize = 2_000;
26/// Above this the input is returned unchanged: bounds memory and CPU for a
27/// single call (native outputs that large are persisted by the host anyway).
28const MAX_SHAPE_BYTES: usize = 8 * 1024 * 1024;
29
30impl McpTool for CtxShapeTool {
31    fn name(&self) -> &'static str {
32        "ctx_shape"
33    }
34
35    /// The body replaces a native tool's output verbatim, so the pipeline must
36    /// hand it back without hints, nudges or checkpoints — after its redaction,
37    /// sensitivity and filter passes, which machine-readable calls keep.
38    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
94/// Pure shaping decision, separated from MCP plumbing for testing.
95fn 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    // Never hand back more than the host already has.
107    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    /// A successful `cargo build` (real shape: progress lines + `Finished`)
126    /// must shrink on the success path and stay recoverable — never larger
127    /// than the input.
128    #[test]
129    fn successful_build_output_is_folded_and_recoverable() {
130        use std::fmt::Write as _;
131        // The tee path is derived from the data dir and re-checked at write time:
132        // hold an isolated data dir so a parallel test cannot move it in between.
133        let _data = crate::core::data_dir::isolated_data_dir();
134        // The recovery tee is Community-only: hold the policy test lock with no
135        // policy, so a parallel test's scoped policy cannot suppress the handle.
136        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}