patchloom 0.25.0

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! MCP (Model Context Protocol) server for patchloom.
//!
//! Exposes patchloom operations as structured MCP tools that AI agents
//! can call directly, eliminating the shell-command construction tax.
//!
//! Run with: `patchloom mcp-server`
//!
//! ## Module layout
//!
//! - [`validation`] - Resource limits and input validation helpers.
//! - [`registry`]   - Auto-generated tool registry (1:1 Operation mappings).
//! - [`surface`]    - Registry vs custom tool inventory (MCP surface honesty).
//! - [`handlers`]   - Hand-written `#[tool]` handlers (must be listed in `surface`).
//! - [`transport`]  - `ServerHandler` impl and server startup (stdio/HTTP).
//! - [`params`]     - Parameter structs for hand-written MCP tools.
//! - [`ast_tools`]  - AST MCP handler implementations (feature-gated).
//!
//! ## Surface policy
//!
//! **Registry is the default** for 1:1 write `Operation` tools. **Custom
//! handlers are the exception** and must be justified in
//! [`surface::custom_mcp_tools`]. Do not migrate multi-file search/replace,
//! batch tools, full plans, or AST analyze tools into the registry just to
//! shrink the custom count.

use rmcp::handler::server::router::tool::{ToolRoute, ToolRouter};
use rmcp::handler::server::tool::ToolCallContext;
use rmcp::model::{CallToolResult, ContentBlock, ErrorData as McpError, JsonObject, Tool};
use std::path::PathBuf;
use std::sync::Arc;

use crate::containment::PathGuard;
use crate::exit;
use crate::plan::{Operation, Plan};

// ---------------------------------------------------------------------------
// Submodules
// ---------------------------------------------------------------------------

mod handlers;
mod list_files;
mod params;
mod registry;
mod surface;
mod transport;
mod validation;

#[cfg(feature = "ast")]
mod ast_tools;

// Re-export validation helpers for use by sibling modules (params, handlers, registry).
use validation::*;

// Re-export param types so tests can use them via `super::*`.
#[cfg(test)]
use params::*;

// Re-export transport entry points for use by cmd/mod.rs.
#[cfg(feature = "mcp-http")]
pub(crate) use transport::run_mcp_http_server;
pub(crate) use transport::run_mcp_server;

use registry::{MCP_TOOL_REGISTRY, handle_simple_op, inject_strict_into_schema};

// ---------------------------------------------------------------------------
// Path containment (test-only helper)
// ---------------------------------------------------------------------------

/// Validate all paths in a list of operations.
/// Checks both syntactic containment and symlink resolution.
#[cfg(test)]
fn validate_operation_paths(
    operations: &[Operation],
    cwd: &std::path::Path,
) -> Result<(), McpError> {
    let guard = crate::containment::PathGuard::new(
        cwd.to_path_buf(),
        crate::containment::AbsolutePathPolicy::Reject,
    )
    .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
    for op in operations {
        for path in op.declared_paths() {
            guard
                .check_path(&path)
                .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
        }
        // Note: PatchApply paths are now covered by declared_paths() which
        // parses the diff. The block below is retained as defense-in-depth.
        if let Operation::PatchApply { diff, .. } = op {
            let patch_files = crate::ops::patch::parse_patch(diff).map_err(|e| {
                McpError::invalid_params(
                    format!("failed to parse diff for path validation: {e}"),
                    None,
                )
            })?;
            for pf in &patch_files {
                guard
                    .check_path(&pf.path)
                    .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Service
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct PatchloomService {
    tool_router: ToolRouter<Self>,
    /// Path guard: validates and canonicalizes paths relative to cwd.
    path_guard: crate::containment::PathGuard,
    /// Optional path for logging MCP tool calls as JSONL.
    /// Set via `--log <path>` or `PATCHLOOM_MCP_LOG` env var.
    call_log: Option<PathBuf>,
    /// Active tool inventory (`PATCHLOOM_MCP_SURFACE`).
    surface: surface::McpSurface,
}

impl PatchloomService {
    /// Build a service using `PATCHLOOM_MCP_SURFACE` from the environment.
    ///
    /// Unset or `full` registers the full inventory. `core` registers only
    /// [`surface::CORE_MCP_TOOL_NAMES`] (see `docs/plans/mcp-surface-tiers.md`).
    pub fn new(cwd: PathBuf, log_flag: Option<String>) -> anyhow::Result<Self> {
        let surface = surface::McpSurface::from_env().map_err(|e| {
            anyhow::Error::new(crate::exit::InvalidInputError { msg: e.to_string() })
        })?;
        Self::new_with_surface(cwd, log_flag, surface)
    }

    /// Build a service with an explicit surface (tests and hosts that inject config).
    pub(crate) fn new_with_surface(
        cwd: PathBuf,
        log_flag: Option<String>,
        surface: surface::McpSurface,
    ) -> anyhow::Result<Self> {
        // Allow absolute paths inside the workspace: agents often copy
        // server_info.cwd + relative into an absolute path. Outside workspace
        // still fails closed via PathGuard resolution.
        let path_guard = crate::containment::PathGuard::new(
            cwd.clone(),
            crate::containment::AbsolutePathPolicy::AllowIfContained,
        )
        .map_err(|e| {
            anyhow::Error::new(crate::exit::InvalidInputError {
                msg: format!("failed to initialize path guard: {e}"),
            })
        })?;
        // --log flag takes precedence over PATCHLOOM_MCP_LOG env var.
        let call_log = log_flag
            .map(PathBuf::from)
            .or_else(|| std::env::var_os("PATCHLOOM_MCP_LOG").map(PathBuf::from));
        let mut tool_router = handlers::new_tool_router();

        // Register auto-generated tools from the registry. Each tool derives
        // its input schema from the corresponding Operation variant and uses
        // the generic `handle_simple_op` dispatcher.
        for meta in MCP_TOOL_REGISTRY {
            if !surface.allows(meta.tool_name) {
                continue;
            }
            let mut schema = crate::schema::operation_variant_schema(meta.op_name)?;
            if meta.has_strict {
                schema = inject_strict_into_schema(schema);
            }
            // Collect the set of allowed field names from the schema properties
            // so handle_simple_op can reject unknown fields (deny_unknown_fields).
            let allowed_fields: Arc<std::collections::HashSet<String>> = Arc::new(
                schema
                    .get("properties")
                    .and_then(|p| p.as_object())
                    .map(|props| props.keys().cloned().collect())
                    .unwrap_or_default(),
            );

            let input_schema: JsonObject = serde_json::from_value(schema).map_err(|e| {
                anyhow::anyhow!("operation_variant_schema must produce a valid JSON object: {e}")
            })?;

            tool_router.add_route(ToolRoute::new_dyn(
                Tool::new(meta.tool_name, meta.description(), Arc::new(input_schema)),
                move |ctx: ToolCallContext<'_, PatchloomService>| {
                    let fields = Arc::clone(&allowed_fields);
                    let svc = ctx.service.clone();
                    let args = ctx.arguments.unwrap_or_default();
                    Box::pin(async move {
                        // Dyn routes must return CallToolResponse (rmcp 3.x MRTR).
                        // Individual handlers still produce CallToolResult; map via From.
                        svc.blocking(move |svc| {
                            let args_value = serde_json::Value::Object(args);
                            handle_simple_op(svc, meta, args_value, &fields)
                        })
                        .await
                        .map(Into::into)
                    })
                },
            ));
        }

        // Hand-written tools are always built by #[tool_router]; drop any that
        // are outside the active surface (core pack excludes most custom tools).
        if surface != surface::McpSurface::Full {
            let to_remove: Vec<String> = tool_router
                .list_all()
                .into_iter()
                .map(|t| t.name.to_string())
                .filter(|name| !surface.allows(name))
                .collect();
            for name in to_remove {
                tool_router.remove_route(&name);
            }
        }

        Ok(Self {
            tool_router,
            path_guard,
            call_log,
            surface,
        })
    }

    /// Active MCP tool surface (`full` or `core`).
    #[must_use]
    pub(crate) fn surface(&self) -> surface::McpSurface {
        self.surface
    }

    /// Validate a path for both syntactic containment and symlink resolution.
    /// Combines the two checks that must always be called together.
    fn check_path(&self, path: &str) -> Result<(), McpError> {
        self.path_guard
            .check_path(path)
            .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
        Ok(())
    }

    /// The workspace root directory (non-canonicalized).
    fn cwd(&self) -> &std::path::Path {
        self.path_guard.root()
    }

    /// Run a synchronous closure on the blocking thread pool.
    ///
    /// All MCP handlers perform synchronous file I/O. Wrapping them in
    /// `spawn_blocking` prevents blocking the tokio async runtime, which
    /// matters for HTTP transport where concurrent requests would otherwise
    /// serialize on a single async task.
    async fn blocking<F, R>(&self, f: F) -> Result<R, McpError>
    where
        F: FnOnce(&PatchloomService) -> Result<R, McpError> + Send + 'static,
        R: Send + 'static,
    {
        let svc = self.clone();
        tokio::task::spawn_blocking(move || f(&svc))
            .await
            .map_err(|e| McpError::internal_error(format!("task join error: {e}"), None))?
    }

    /// Write a JSONL log entry for a tool call if logging is enabled.
    fn log_tool_call(
        &self,
        tool: &str,
        duration_ms: u64,
        result: &Result<rmcp::model::CallToolResponse, McpError>,
    ) {
        let Some(ref log_path) = self.call_log else {
            return;
        };
        let (ok, error) = match result {
            Ok(rmcp::model::CallToolResponse::Complete(r)) => (!r.is_error.unwrap_or(false), None),
            // MRTR / tasks intermediate results (and future non-exhaustive variants)
            // are not protocol failures for call-log purposes.
            Ok(_) => (true, None),
            Err(e) => (false, Some(format!("{e}"))),
        };
        let ts = {
            let d = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default();
            d.as_millis()
        };
        let mut entry = serde_json::json!({
            "ts": ts,
            "tool": tool,
            "duration_ms": duration_ms,
            "ok": ok,
        });
        if let Some(err_msg) = error {
            entry["error"] = serde_json::Value::String(err_msg);
        }
        if let Ok(mut f) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(log_path)
        {
            use std::io::Write;
            let _ = writeln!(f, "{entry}");
        }
    }

    /// Helper to execute one or more operations as a plan.
    /// Reduces repetitive boilerplate across single-op and batch MCP tools.
    fn run_ops(
        &self,
        ops: Vec<Operation>,
        strict: Option<bool>,
    ) -> Result<CallToolResult, McpError> {
        execute_plan_validated(
            make_plan_strict(ops, strict),
            self.cwd(),
            Some(&self.path_guard),
        )
    }

    /// Helper for single-op case to reduce vec! boilerplate in handlers.
    fn run_one_op(&self, op: Operation, strict: Option<bool>) -> Result<CallToolResult, McpError> {
        self.run_ops(vec![op], strict)
    }

    /// Validate paths for a single operation (including embedded paths for PatchApply).
    fn validate_op_paths(&self, op: &Operation) -> Result<(), McpError> {
        for declared in op.declared_paths() {
            self.check_path(&declared)?;
        }
        if let Operation::PatchApply { diff, .. } = op {
            let patch_files = crate::ops::patch::parse_patch(diff).map_err(|e| {
                McpError::invalid_params(
                    format!("failed to parse diff for path validation: {e}"),
                    None,
                )
            })?;
            for pf in &patch_files {
                self.check_path(&pf.path)?;
                if let Some(from) = &pf.rename_from {
                    self.check_path(from)?;
                }
            }
        }
        Ok(())
    }
}

/// Execute a plan whose paths have already been validated by the caller.
///
/// Each individual MCP tool validates paths via `check_path` before calling
/// this function, so this wrapper does not repeat that pre-validation.
/// The `guard` is still passed through so `execute_plan_direct` can enforce
/// containment checks during actual writes.
fn execute_plan_validated(
    plan: Plan,
    cwd: &std::path::Path,
    guard: Option<&PathGuard>,
) -> Result<CallToolResult, McpError> {
    let (code, json) = crate::cmd::tx::execute_plan_direct(plan, cwd, guard)
        .map_err(|e| McpError::internal_error(format!("plan execution failed: {e}"), None))?;

    exit_code_to_result(code, &json, "Operation completed successfully.")
}

/// Return a successful result with a "no results" message.
///
/// Use for valid queries that produce no matches (e.g. `ast_refs` finding no
/// references, `search_files` with no hits). These are correct answers, not
/// errors. Returning `isError: false` prevents LLM agents from entering
/// unnecessary recovery mode. See #1270.
fn no_results(msg: &str) -> Result<CallToolResult, McpError> {
    Ok(CallToolResult::success(vec![ContentBlock::text(msg)]))
}

/// Convert an exit code + output string into a `CallToolResult`.
///
/// When `output` is non-empty it is used as-is. Otherwise `fallback` is used
/// for both success and error results so callers can provide a descriptive
/// message regardless of exit code. If both are empty and the code indicates
/// failure, a generic "Operation failed with exit code N." message is returned.
fn exit_code_to_result(code: u8, output: &str, fallback: &str) -> Result<CallToolResult, McpError> {
    let msg = if output.trim().is_empty() {
        if fallback.is_empty() && code != exit::SUCCESS {
            format!("Operation failed with exit code {code}.")
        } else {
            fallback.to_string()
        }
    } else {
        output.trim().to_string()
    };
    if code == exit::SUCCESS {
        Ok(CallToolResult::success(vec![ContentBlock::text(msg)]))
    } else {
        Ok(CallToolResult::error(vec![ContentBlock::text(msg)]))
    }
}

/// Execute a read-only doc operation directly (no subprocess).
fn doc_readonly(action: &crate::cmd::doc::DocAction) -> Result<CallToolResult, McpError> {
    let (output, code) =
        match crate::cmd::doc::execute_with_mode(action, crate::cmd::doc::OutputMode::Json) {
            Ok(v) => v,
            // Typed agent errors (type_error on multi-doc bare key, not_found,
            // …) must be tool errors with error_kind, not protocol
            // internal_error (CLI --json parity).
            Err(e) => {
                if crate::exit::classify_typed_error(&e).is_some() {
                    let (payload, _code) = crate::exit::structured_error_payload(&e);
                    let text =
                        serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string());
                    return Ok(CallToolResult::error(vec![ContentBlock::text(text)]));
                }
                return Err(McpError::internal_error(format!("{e}"), None));
            }
        };
    // CHANGES_DETECTED (2) is a valid success for doc diff (differences found).
    // After #1843, doc has always exits 0 for true/false, so do not promote
    // NO_MATCHES (real get/keys/len misses) to success.
    let effective = if code == exit::CHANGES_DETECTED {
        exit::SUCCESS
    } else {
        code
    };
    // CLI --json uses an ok/value envelope (#1838). MCP tools keep returning
    // the bare value so existing agent prompts and tests stay stable.
    let text = if effective == exit::SUCCESS {
        peel_doc_query_success_value(&output)
    } else {
        output
    };
    exit_code_to_result(effective, &text, "No results.")
}

/// If `output` is a successful CLI doc-query envelope, return pretty `value`.
/// Otherwise return the original string (errors, doc diff, already-bare).
fn peel_doc_query_success_value(output: &str) -> String {
    let Ok(v) = serde_json::from_str::<serde_json::Value>(output) else {
        return output.to_string();
    };
    if v.get("ok").and_then(|o| o.as_bool()) != Some(true) {
        return output.to_string();
    }
    let Some(value) = v.get("value") else {
        return output.to_string();
    };
    match serde_json::to_string_pretty(value) {
        Ok(s) => s,
        Err(_) => output.to_string(),
    }
}

fn make_plan_strict(operations: Vec<Operation>, strict: Option<bool>) -> Plan {
    Plan {
        version: crate::plan::SCHEMA_VERSION,
        cwd: None,
        write_policy: None,
        strict,
        operations,
        format: None,
        validate: None,
        verify: None,
        for_each: None,
    }
}

#[cfg(test)]
mod tests;