Skip to main content

lean_ctx/tools/registered/
ctx_edit.rs

1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{json, Map, Value};
4
5use crate::server::tool_trait::{
6    get_bool, get_int, get_str, require_resolved_path, McpTool, ToolContext, ToolOutput,
7};
8use crate::tool_defs::tool_def;
9
10pub struct CtxEditTool;
11
12impl McpTool for CtxEditTool {
13    fn name(&self) -> &'static str {
14        "ctx_edit"
15    }
16
17    fn tool_def(&self) -> Tool {
18        tool_def(
19            "ctx_edit",
20            "Edit a file via search-and-replace. Works without native Read/Edit tools. Use this when the IDE's Edit tool requires Read but Read is unavailable.",
21            json!({
22                "type": "object",
23                "properties": {
24                    "path": { "type": "string", "description": "Absolute file path" },
25                    "old_string": { "type": "string", "description": "Exact text to find and replace (must be unique unless replace_all=true)" },
26                    "new_string": { "type": "string", "description": "Replacement text" },
27                    "replace_all": { "type": "boolean", "description": "Replace all occurrences (default: false)", "default": false },
28                    "create": { "type": "boolean", "description": "Create a new file with new_string as content (ignores old_string)", "default": false }
29                },
30                "required": ["path", "new_string"]
31            }),
32        )
33    }
34
35    fn handle(
36        &self,
37        args: &Map<String, Value>,
38        ctx: &ToolContext,
39    ) -> Result<ToolOutput, ErrorData> {
40        let path = require_resolved_path(ctx, args, "path")?;
41
42        let old_string = get_str(args, "old_string").unwrap_or_default();
43        let new_string = get_str(args, "new_string")
44            .ok_or_else(|| ErrorData::invalid_params("new_string is required", None))?;
45        let replace_all = get_bool(args, "replace_all").unwrap_or(false);
46        let create = get_bool(args, "create").unwrap_or(false);
47        let expected_md5 = get_str(args, "expected_md5");
48        let expected_size = get_int(args, "expected_size").and_then(|v| u64::try_from(v).ok());
49        let expected_mtime_ms =
50            get_int(args, "expected_mtime_ms").and_then(|v| u64::try_from(v).ok());
51        let backup = get_bool(args, "backup").unwrap_or(false);
52        let backup_path = get_str(args, "backup_path")
53            .map(|p| ctx.resolved_paths.get("backup_path").cloned().unwrap_or(p));
54        let evidence = get_bool(args, "evidence").unwrap_or(true);
55        let diff_max_lines = get_int(args, "diff_max_lines")
56            .and_then(|v| usize::try_from(v.max(0)).ok())
57            .unwrap_or(200);
58        let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
59
60        tokio::task::block_in_place(|| {
61            let cache_lock = ctx
62                .cache
63                .as_ref()
64                .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
65            let mut cache = cache_lock.blocking_write();
66            let output = crate::tools::ctx_edit::handle(
67                &mut cache,
68                &crate::tools::ctx_edit::EditParams {
69                    path: path.clone(),
70                    old_string,
71                    new_string,
72                    replace_all,
73                    create,
74                    expected_md5,
75                    expected_size,
76                    expected_mtime_ms,
77                    backup,
78                    backup_path,
79                    evidence,
80                    diff_max_lines,
81                    allow_lossy_utf8,
82                },
83            );
84            drop(cache);
85
86            if let Some(session_lock) = ctx.session.as_ref() {
87                let mut session = session_lock.blocking_write();
88                session.mark_modified(&path);
89            }
90
91            Ok(ToolOutput {
92                text: output,
93                original_tokens: 0,
94                saved_tokens: 0,
95                mode: None,
96                path: Some(path),
97                changed: false,
98            })
99        })
100    }
101}