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 through `ctx_call` (`$.mcp.call`
17/// in Claude Code 2.1.296+ only reaches listed tools, #2089); it is never
18/// advertised, and every gate refusal on it is an error so the host keeps the
19/// native output — see `dynamic_tools::INTERNAL_HOST_TOOLS`.
20pub struct CtxShapeTool;
21
22/// Below this many **bytes** the shaping gain cannot pay for the call. Bytes,
23/// not chars: the Claude Code mod measures JavaScript string length (UTF-16
24/// units), and a text is never fewer bytes than UTF-16 units — so anything the
25/// mod sends clears this floor instead of slipping back unredacted.
26const MIN_SHAPE_BYTES: usize = 2_000;
27/// Above this the input is returned unchanged: bounds memory and CPU for a
28/// single call (native outputs that large are persisted by the host anyway).
29const MAX_SHAPE_BYTES: usize = 8 * 1024 * 1024;
30
31impl McpTool for CtxShapeTool {
32    fn name(&self) -> &'static str {
33        "ctx_shape"
34    }
35
36    /// The body replaces a native tool's output verbatim, so the pipeline must
37    /// hand it back without hints, nudges or checkpoints — after its redaction,
38    /// sensitivity and filter passes, which machine-readable calls keep.
39    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
95/// Pure shaping decision, separated from MCP plumbing for testing.
96fn 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    // Never hand back more than the host already has.
108    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    /// A successful `cargo build` (real shape: progress lines + `Finished`)
127    /// must shrink on the success path and stay recoverable — never larger
128    /// than the input.
129    #[test]
130    fn successful_build_output_is_folded_and_recoverable() {
131        use std::fmt::Write as _;
132        // The tee path is derived from the data dir and re-checked at write time:
133        // hold an isolated data dir so a parallel test cannot move it in between.
134        let _data = crate::core::data_dir::isolated_data_dir();
135        // The recovery tee is Community-only: hold the policy test lock with no
136        // policy, so a parallel test's scoped policy cannot suppress the handle.
137        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}