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