lean_ctx/tools/registered/
ctx_edit.rs1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4use similar::{ChangeTag, TextDiff};
5use std::path::Path;
6
7use crate::server::tool_trait::{
8 McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str, require_resolved_path,
9};
10use crate::tool_defs::tool_def;
11
12pub struct CtxEditTool;
13
14impl McpTool for CtxEditTool {
15 fn name(&self) -> &'static str {
16 "ctx_edit"
17 }
18
19 fn tool_def(&self) -> Tool {
20 tool_def(
21 "ctx_edit",
22 "Search-and-replace edit with race-condition guards — for simple text replacement in a single file.\n\
23 For editing code you've read, prefer ctx_patch (hash-anchored): it never makes you reproduce old text byte-for-byte. Read with ctx_read(mode=\"anchored\") first.\n\
24 old_string must be unique unless replace_all=true. create=true writes new files.\n\
25 backup creates .bak. MD5/size/mtime pre-guards prevent race conditions.\n\
26 ANTIPATTERN: Do NOT loop on failures — switch to ctx_patch (anchored), or verify file content and adjust old_string.\n\
27 For LSP-aware refactoring (rename, move, inline), use ctx_refactor.",
28 json!({
29 "type": "object",
30 "properties": {
31 "path": { "type": "string", "description": "File path to edit" },
32 "old_string": { "type": "string", "description": "Text to replace (unique unless replace_all=true)" },
33 "new_string": { "type": "string", "description": "Replacement text" },
34 "replace_all": { "type": "boolean", "description": "Replace all occurrences (default false)", "default": false },
35 "create": { "type": "boolean", "description": "Create file", "default": false }
36 },
37 "required": ["path", "new_string"]
38 }),
39 )
40 }
41
42 fn handle(
43 &self,
44 args: &Map<String, Value>,
45 ctx: &ToolContext,
46 ) -> Result<ToolOutput, ErrorData> {
47 let path = require_resolved_path(ctx, args, "path")?;
48
49 let old_string = get_str(args, "old_string").unwrap_or_default();
50 let new_string = get_str(args, "new_string")
51 .ok_or_else(|| ErrorData::invalid_params("new_string is required", None))?;
52 let replace_all = get_bool(args, "replace_all").unwrap_or(false);
53 let create = get_bool(args, "create").unwrap_or(false);
54 let expected_md5 = get_str(args, "expected_md5");
55 let expected_size = get_int(args, "expected_size").and_then(|v| u64::try_from(v).ok());
56 let expected_mtime_ms =
57 get_int(args, "expected_mtime_ms").and_then(|v| u64::try_from(v).ok());
58 let backup = get_bool(args, "backup").unwrap_or(false);
59 let backup_path = get_str(args, "backup_path")
60 .map(|p| ctx.resolved_paths.get("backup_path").cloned().unwrap_or(p));
61 let evidence = get_bool(args, "evidence").unwrap_or(true);
62 let diff_max_lines = get_int(args, "diff_max_lines")
63 .and_then(|v| usize::try_from(v.max(0)).ok())
64 .unwrap_or(200);
65 let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
66
67 let edit_params = crate::tools::ctx_edit::EditParams {
68 path: path.clone(),
69 old_string,
70 new_string,
71 replace_all,
72 create,
73 expected_md5,
74 expected_size,
75 expected_mtime_ms,
76 backup,
77 backup_path,
78 evidence,
79 diff_max_lines,
80 allow_lossy_utf8,
81 };
82
83 {
84 let cache_lock = ctx
85 .cache
86 .as_ref()
87 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
88
89 let file_lock = crate::core::path_locks::per_file_lock(&path);
96 let _file_guard = {
97 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
98 loop {
99 if let Ok(guard) = file_lock.try_lock() {
100 break guard;
101 }
102 if std::time::Instant::now() >= deadline {
103 return Err(ErrorData::internal_error(
104 format!(
105 "per-file edit lock contention for {path} — another edit to the same file is in progress, retry in a moment"
106 ),
107 None,
108 ));
109 }
110 std::thread::sleep(std::time::Duration::from_millis(20));
111 }
112 };
113
114 let last_mode =
117 match crate::server::bounded_lock::read(cache_lock, "ctx_edit cache read") {
118 Some(cache) => cache
119 .get(&path)
120 .map(|e| e.last_mode.clone())
121 .unwrap_or_default(),
122 None => String::new(),
123 };
124
125 let before = std::fs::read(&path).unwrap_or_default();
127 let (output, effect) = crate::tools::ctx_edit::run_io(&edit_params, &last_mode);
128
129 if matches!(effect, crate::tools::ctx_edit::CacheEffect::Invalidate) {
130 let after = std::fs::read(&path).unwrap_or_default();
131 observe_mcp_edit(ctx, &path, "ctx_edit", &before, &after);
132 }
133
134 crate::tools::ctx_edit::record_outcome(&edit_params, &last_mode, &output, &effect);
137
138 if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
140 crate::tools::ctx_read::dedup_hook::on_write(&path);
141 match crate::server::bounded_lock::write(cache_lock, "ctx_edit cache write") {
142 Some(mut cache) => {
143 crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
144 }
145 None => {
146 tracing::warn!(
147 "ctx_edit: cache write-lock timeout applying post-edit effect for {path}"
148 );
149 }
150 }
151 }
152
153 if let Some(session_lock) = ctx.session.as_ref() {
154 if let Some(mut session) =
155 crate::server::bounded_lock::write(session_lock, "ctx_edit session write")
156 {
157 session.mark_modified(&path);
158 }
159 }
160
161 Ok(ToolOutput {
162 text: output,
163 original_tokens: 0,
164 saved_tokens: 0,
165 mode: None,
166 path: Some(path),
167 changed: false,
168 shell_outcome: None,
169 content_blocks: None,
170 })
171 }
172 }
173}
174
175pub(crate) fn observe_mcp_edit(
176 ctx: &ToolContext,
177 path: &str,
178 tool: &str,
179 before: &[u8],
180 after: &[u8],
181) {
182 let config = crate::core::config::Config::load();
183 if !config.provenance.enabled || !config.provenance.capture_mcp_edits || before == after {
184 return;
185 }
186
187 let root = ctx.project_root.as_str();
188 if root.is_empty() {
189 return;
190 }
191
192 let before_text = String::from_utf8_lossy(before);
193 let after_text = String::from_utf8_lossy(after);
194 let (lines_added, lines_removed) = TextDiff::from_lines(&before_text, &after_text)
195 .iter_all_changes()
196 .fold((0_u64, 0_u64), |(added, removed), change| {
197 match change.tag() {
198 ChangeTag::Insert => (added.saturating_add(1), removed),
199 ChangeTag::Delete => (added, removed.saturating_add(1)),
200 ChangeTag::Equal => (added, removed),
201 }
202 });
203 let tracked_path = Path::new(path)
204 .strip_prefix(root)
205 .ok()
206 .filter(|relative| !relative.as_os_str().is_empty())
207 .map(|relative| relative.to_string_lossy().into_owned())
208 .unwrap_or_else(|| path.to_owned());
209 let session_id = ctx
210 .session
211 .as_ref()
212 .and_then(|session| {
213 crate::server::bounded_lock::read(session, "provenance session read")
214 .map(|session| session.id.clone())
215 })
216 .unwrap_or_else(|| "mcp".to_owned());
217 let agent_id = ctx
218 .agent_id
219 .as_ref()
220 .and_then(|agent_id| {
221 crate::server::bounded_lock::read(agent_id, "provenance agent read")
222 .and_then(|agent_id| (*agent_id).clone())
223 })
224 .unwrap_or_else(|| "mcp".to_owned());
225
226 let _ = crate::core::provenance::ProvenanceTracker::new(root).and_then(|tracker| {
227 tracker.observe_edit(
228 tracked_path,
229 tool,
230 sha256_hex(before),
231 sha256_hex(after),
232 lines_added,
233 lines_removed,
234 session_id,
235 agent_id,
236 )
237 });
238}
239
240fn sha256_hex(data: &[u8]) -> String {
241 use sha2::{Digest, Sha256};
242 let hash = Sha256::digest(data);
243 let mut hex = String::with_capacity(64);
244 for b in &hash {
245 use std::fmt::Write;
246 let _ = write!(hex, "{b:02x}");
247 }
248 hex
249}