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
134 if written {
135 let after = std::fs::read(&path).unwrap_or_default();
136 observe_mcp_edit(ctx, &path, "ctx_edit", &before, &after);
137 }
138
139 crate::tools::ctx_edit::record_outcome(&edit_params, &last_mode, &output, &effect);
142
143 if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
145 crate::tools::ctx_read::dedup_hook::on_write(&path);
146 match crate::server::bounded_lock::write(cache_lock, "ctx_edit cache write") {
147 Some(mut cache) => {
148 crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
149 }
150 None => {
151 tracing::warn!(
152 "ctx_edit: cache write-lock timeout applying post-edit effect for {path}"
153 );
154 }
155 }
156 }
157
158 if !written {
162 return Err(tool_execution_error(output));
163 }
164
165 if let Some(session_lock) = ctx.session.as_ref() {
166 if let Some(mut session) =
167 crate::server::bounded_lock::write(session_lock, "ctx_edit session write")
168 {
169 session.mark_modified(&path);
170 }
171 }
172
173 Ok(ToolOutput {
174 text: output,
175 original_tokens: 0,
176 saved_tokens: 0,
177 mode: None,
178 path: Some(path),
179 changed: false,
180 shell_outcome: None,
181 content_blocks: None,
182 })
183 }
184 }
185}
186
187pub(crate) fn observe_mcp_edit(
188 ctx: &ToolContext,
189 path: &str,
190 tool: &str,
191 before: &[u8],
192 after: &[u8],
193) {
194 let config = crate::core::config::Config::load();
195 if !config.provenance.enabled || !config.provenance.capture_mcp_edits || before == after {
196 return;
197 }
198
199 let root = ctx.project_root.as_str();
200 if root.is_empty() {
201 return;
202 }
203
204 let before_text = String::from_utf8_lossy(before);
205 let after_text = String::from_utf8_lossy(after);
206 let (lines_added, lines_removed) = TextDiff::from_lines(&before_text, &after_text)
207 .iter_all_changes()
208 .fold((0_u64, 0_u64), |(added, removed), change| {
209 match change.tag() {
210 ChangeTag::Insert => (added.saturating_add(1), removed),
211 ChangeTag::Delete => (added, removed.saturating_add(1)),
212 ChangeTag::Equal => (added, removed),
213 }
214 });
215 let tracked_path = Path::new(path)
216 .strip_prefix(root)
217 .ok()
218 .filter(|relative| !relative.as_os_str().is_empty())
219 .map(|relative| relative.to_string_lossy().into_owned())
220 .unwrap_or_else(|| path.to_owned());
221 let session_id = ctx
222 .session
223 .as_ref()
224 .and_then(|session| {
225 crate::server::bounded_lock::read(session, "provenance session read")
226 .map(|session| session.id.clone())
227 })
228 .unwrap_or_else(|| "mcp".to_owned());
229 let agent_id = ctx
230 .agent_id
231 .as_ref()
232 .and_then(|agent_id| {
233 crate::server::bounded_lock::read(agent_id, "provenance agent read")
234 .and_then(|agent_id| (*agent_id).clone())
235 })
236 .unwrap_or_else(|| "mcp".to_owned());
237
238 let _ = crate::core::provenance::ProvenanceTracker::new(root).and_then(|tracker| {
239 tracker.observe_edit(
240 tracked_path,
241 tool,
242 sha256_hex(before),
243 sha256_hex(after),
244 lines_added,
245 lines_removed,
246 session_id,
247 agent_id,
248 )
249 });
250}
251
252fn sha256_hex(data: &[u8]) -> String {
253 use sha2::{Digest, Sha256};
254 let hash = Sha256::digest(data);
255 let mut hex = String::with_capacity(64);
256 for b in &hash {
257 use std::fmt::Write;
258 let _ = write!(hex, "{b:02x}");
259 }
260 hex
261}