lean_ctx/tools/registered/
ctx_edit.rs1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6 McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str, require_resolved_path,
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 "Search-and-replace edit with race-condition guards — for simple text replacement in a single file.\n\
21 old_string must be unique unless replace_all=true. create=true writes new files.\n\
22 backup creates .bak. MD5/size/mtime pre-guards prevent race conditions.\n\
23 ANTIPATTERN: Do NOT loop on failures — verify file content and adjust old_string, or use native Edit with prior Read.\n\
24 For LSP-aware refactoring (rename, move, inline), use ctx_refactor.",
25 json!({
26 "type": "object",
27 "properties": {
28 "path": { "type": "string", "description": "File path to edit" },
29 "old_string": { "type": "string", "description": "Text to replace (unique unless replace_all=true)" },
30 "new_string": { "type": "string", "description": "Replacement text" },
31 "replace_all": { "type": "boolean", "description": "Replace all occurrences (default false)", "default": false },
32 "create": { "type": "boolean", "description": "Create file", "default": false }
33 },
34 "required": ["path", "new_string"]
35 }),
36 )
37 }
38
39 fn handle(
40 &self,
41 args: &Map<String, Value>,
42 ctx: &ToolContext,
43 ) -> Result<ToolOutput, ErrorData> {
44 let path = require_resolved_path(ctx, args, "path")?;
45
46 let old_string = get_str(args, "old_string").unwrap_or_default();
47 let new_string = get_str(args, "new_string")
48 .ok_or_else(|| ErrorData::invalid_params("new_string is required", None))?;
49 let replace_all = get_bool(args, "replace_all").unwrap_or(false);
50 let create = get_bool(args, "create").unwrap_or(false);
51 let expected_md5 = get_str(args, "expected_md5");
52 let expected_size = get_int(args, "expected_size").and_then(|v| u64::try_from(v).ok());
53 let expected_mtime_ms =
54 get_int(args, "expected_mtime_ms").and_then(|v| u64::try_from(v).ok());
55 let backup = get_bool(args, "backup").unwrap_or(false);
56 let backup_path = get_str(args, "backup_path")
57 .map(|p| ctx.resolved_paths.get("backup_path").cloned().unwrap_or(p));
58 let evidence = get_bool(args, "evidence").unwrap_or(true);
59 let diff_max_lines = get_int(args, "diff_max_lines")
60 .and_then(|v| usize::try_from(v.max(0)).ok())
61 .unwrap_or(200);
62 let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
63
64 let edit_params = crate::tools::ctx_edit::EditParams {
65 path: path.clone(),
66 old_string,
67 new_string,
68 replace_all,
69 create,
70 expected_md5,
71 expected_size,
72 expected_mtime_ms,
73 backup,
74 backup_path,
75 evidence,
76 diff_max_lines,
77 allow_lossy_utf8,
78 };
79
80 tokio::task::block_in_place(|| {
81 let cache_lock = ctx
82 .cache
83 .as_ref()
84 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
85 let rt = tokio::runtime::Handle::current();
86
87 let file_lock = crate::core::path_locks::per_file_lock(&path);
94 let _file_guard = {
95 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
96 loop {
97 if let Ok(guard) = file_lock.try_lock() {
98 break guard;
99 }
100 if std::time::Instant::now() >= deadline {
101 return Err(ErrorData::internal_error(
102 format!(
103 "per-file edit lock contention for {path} — another edit to the same file is in progress, retry in a moment"
104 ),
105 None,
106 ));
107 }
108 std::thread::sleep(std::time::Duration::from_millis(20));
109 }
110 };
111
112 let last_mode = match rt.block_on(tokio::time::timeout(
115 std::time::Duration::from_secs(5),
116 cache_lock.read(),
117 )) {
118 Ok(cache) => cache
119 .get(&path)
120 .map(|e| e.last_mode.clone())
121 .unwrap_or_default(),
122 Err(_) => String::new(),
123 };
124
125 let (output, effect) = crate::tools::ctx_edit::run_io(&edit_params, &last_mode);
127
128 crate::tools::ctx_edit::record_outcome(&edit_params, &last_mode, &output, &effect);
131
132 if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
134 match rt.block_on(tokio::time::timeout(
135 std::time::Duration::from_secs(5),
136 cache_lock.write(),
137 )) {
138 Ok(mut cache) => {
139 crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
140 }
141 Err(_) => {
142 tracing::warn!(
143 "ctx_edit: cache write-lock timeout (5s) applying post-edit cache effect for {path}"
144 );
145 }
146 }
147 }
148
149 if let Some(session_lock) = ctx.session.as_ref() {
150 let guard = rt.block_on(tokio::time::timeout(
151 std::time::Duration::from_secs(5),
152 session_lock.write(),
153 ));
154 if let Ok(mut session) = guard {
155 session.mark_modified(&path);
156 }
157 }
158
159 Ok(ToolOutput {
160 text: output,
161 original_tokens: 0,
162 saved_tokens: 0,
163 mode: None,
164 path: Some(path),
165 changed: false,
166 shell_outcome: None,
167 })
168 })
169 }
170}