pathfinder-mcp 0.3.1

Pathfinder — The Headless IDE MCP Server for AI Coding Agents
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::needless_return)]
use crate::server::types::ReplaceFullParams;
use crate::server::PathfinderServer;

use super::helpers::UnsupportedDiagLawyer;
use pathfinder_common::config::PathfinderConfig;
use pathfinder_common::sandbox::Sandbox;
use pathfinder_common::types::{VersionHash, WorkspaceRoot};
use pathfinder_search::MockScout;
use pathfinder_treesitter::mock::MockSurgeon;
use rmcp::handler::server::wrapper::Parameters;
use std::sync::Arc;
use tempfile::tempdir;

fn make_server_with_lawyer(
    ws_dir: &tempfile::TempDir,
    mock_surgeon: MockSurgeon,
    mock_lawyer: pathfinder_lsp::MockLawyer,
) -> PathfinderServer {
    let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
    let config = PathfinderConfig::default();
    let sandbox = Sandbox::new(ws.path(), &config.sandbox);
    PathfinderServer::with_all_engines(
        ws,
        config,
        sandbox,
        Arc::new(MockScout::default()),
        Arc::new(mock_surgeon),
        Arc::new(mock_lawyer),
    )
}

/// Helper: write a tiny Go source file and build a `MockSurgeon` whose
/// `resolve_full_range` returns a range covering the whole file.
fn setup_full_replace_fixture(
    ws_dir: &tempfile::TempDir,
    filepath: &str,
    src: &str,
) -> (MockSurgeon, VersionHash) {
    let abs = ws_dir.path().join(filepath);
    std::fs::create_dir_all(abs.parent().unwrap()).unwrap();
    std::fs::write(&abs, src).unwrap();

    let src_bytes = src.as_bytes();
    let hash = VersionHash::compute(src_bytes);

    let mock_surgeon = MockSurgeon::new();
    mock_surgeon
        .resolve_full_range_results
        .lock()
        .unwrap()
        .push(Ok((
            pathfinder_treesitter::surgeon::FullRange {
                start_byte: 0,
                end_byte: src_bytes.len(),
                indent_column: 0,
            },
            std::sync::Arc::from(src_bytes),
            hash.clone(),
        )));

    (mock_surgeon, hash)
}

// ── no_lsp: did_open returns NoLspAvailable → validation skipped ────

#[tokio::test]
async fn test_run_lsp_validation_no_lsp() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    mock_lawyer.set_did_open_error(pathfinder_lsp::LspError::NoLspAvailable);

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — no_lsp gracefully degrades");
    let resp = result.0;

    assert!(resp.success);
    assert_eq!(resp.validation.status, "skipped");
    assert!(resp.validation_skipped);
    assert_eq!(resp.validation_skipped_reason.as_deref(), Some("no_lsp"));
}

// ── unsupported: did_open returns UnsupportedCapability → skipped ───

#[tokio::test]
async fn test_run_lsp_validation_unsupported() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    mock_lawyer.set_did_open_error(pathfinder_lsp::LspError::UnsupportedCapability {
        capability: "textDocument/diagnostic".to_owned(),
    });

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — unsupported gracefully degrades");
    let resp = result.0;

    assert_eq!(resp.validation.status, "skipped");
    assert!(resp.validation_skipped);
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("pull_diagnostics_unsupported")
    );
}

// ── pre_diag_timeout: first pull_diagnostics errors → skipped ───────

#[tokio::test]
async fn test_run_lsp_validation_pre_diag_timeout() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // did_open succeeds (default); first pull_diagnostics returns a protocol
    // error — any error that is not UnsupportedCapability maps to
    // "diagnostic_timeout" in run_lsp_validation.
    mock_lawyer.push_pull_diagnostics_result(Err("LSP timed out".to_owned()));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — pre-diag timeout gracefully degrades");
    let resp = result.0;

    assert!(resp.success);
    assert_eq!(resp.validation.status, "skipped");
    assert!(resp.validation_skipped);
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("lsp_protocol_error")
    );
}

// ── pre_diag_unsupported: first pull_diagnostics → UnsupportedCapability
//    → skipped with "pull_diagnostics_unsupported" reason ────────────────

#[tokio::test]
async fn test_run_lsp_validation_pull_diagnostics_unsupported() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    // `mock_surgeon` is used in the first call but we need a fresh surgeon
    // for the second server construction; discard the first fixture result.
    let (_mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    // UnsupportedDiagLawyer always returns UnsupportedCapability from
    // pull_diagnostics, exercising the "pull_diagnostics_unsupported" branch.
    let (mock_surgeon_2, _) = setup_full_replace_fixture(&ws_dir, filepath, src);
    let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
    let config = PathfinderConfig::default();
    let sandbox = Sandbox::new(ws.path(), &config.sandbox);
    let server = PathfinderServer::with_all_engines(
        ws,
        config,
        sandbox,
        Arc::new(MockScout::default()),
        Arc::new(mock_surgeon_2),
        Arc::new(UnsupportedDiagLawyer),
    );

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — pull_diagnostics_unsupported degrades");
    let resp = result.0;

    assert_eq!(resp.validation.status, "skipped");
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("pull_diagnostics_unsupported")
    );
}

// ── post_diag_timeout: second pull_diagnostics errors → skipped ──────

#[tokio::test]
async fn test_run_lsp_validation_post_diag_timeout() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // Pre-edit pull_diagnostics succeeds with empty diags.
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    // Post-edit pull_diagnostics errors (e.g. timeout).
    mock_lawyer.push_pull_diagnostics_result(Err("timeout after 10s".to_owned()));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — post-diag timeout gracefully degrades");
    let resp = result.0;

    assert!(resp.success);
    assert_eq!(resp.validation.status, "skipped");
    assert!(resp.validation_skipped);
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("lsp_protocol_error")
    );
}

// ── blocking: new errors introduced + ignore_validation_failures=false ─

#[tokio::test]
async fn test_run_lsp_validation_blocking() {
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};

    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // Pre-edit: no errors.
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    // Post-edit: one new error introduced.
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: Some("E001".into()),
        message: "undefined: Foo".into(),
        file: filepath.to_owned(),
        start_line: 1,
        end_line: 1,
    }]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    // ignore_validation_failures = false → should block
    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { Foo() }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server.replace_full(Parameters(params)).await;

    let Err(err) = result else {
        panic!("expected VALIDATION_FAILED error when new errors are introduced");
    };
    let code = err
        .data
        .as_ref()
        .and_then(|d| d.get("error"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    assert_eq!(code, "VALIDATION_FAILED", "got: {err:?}");
    // Confirm the introduced error is surfaced (nested under details.introduced_errors
    // because pathfinder_to_error_data serializes ErrorResponse which has a `details` field)
    let introduced = err
        .data
        .as_ref()
        .and_then(|d| d.get("details"))
        .and_then(|d| d.get("introduced_errors"))
        .and_then(|v| v.as_array())
        .map_or(0, Vec::len);
    assert_eq!(
        introduced, 1,
        "one new error should appear in introduced_errors"
    );
}

// ── workspace blocking: new errors in other files block the edit ────────

#[tokio::test]
async fn test_run_lsp_validation_workspace_blocking() {
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};

    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // Pre-edit diagnostics (file + workspace)
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    mock_lawyer.push_pull_workspace_diagnostics_result(Ok(vec![]));

    // Post-edit diagnostics (no errors in single file, but 1 error in workspace)
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    mock_lawyer.push_pull_workspace_diagnostics_result(Ok(vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: Some("E002".into()),
        message: "cannot call Login with 1 argument".into(),
        file: "src/main.go".to_owned(), // Different file!
        start_line: 5,
        end_line: 5,
    }]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    // ignore_validation_failures = false → should block
    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login(a string) { }\n".to_owned(), // changed signature
        ignore_validation_failures: false,
    };
    let result = server.replace_full(Parameters(params)).await;

    let Err(err) = result else {
        panic!("expected VALIDATION_FAILED error when workspace errors are introduced");
    };
    let code = err
        .data
        .as_ref()
        .and_then(|d| d.get("error"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    assert_eq!(code, "VALIDATION_FAILED", "got: {err:?}");

    // Confirm the workspace error is reported
    let introduced = err
        .data
        .as_ref()
        .and_then(|d| d.get("details"))
        .and_then(|d| d.get("introduced_errors"))
        .and_then(|v| v.as_array())
        .expect("should have introduced_errors");
    assert_eq!(
        introduced.len(),
        1,
        "one workspace error should appear in introduced_errors"
    );
    let first_err_file = introduced[0].get("file").and_then(|v| v.as_str()).unwrap();
    assert_eq!(
        first_err_file, "src/main.go",
        "error should be in src/main.go"
    );
}

// ── blocking_ignored: new errors + ignore_validation_failures=true → passes

#[tokio::test]
async fn test_run_lsp_validation_blocking_ignored() {
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};

    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: Some("E001".into()),
        message: "undefined: Foo".into(),
        file: filepath.to_owned(),
        start_line: 1,
        end_line: 1,
    }]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    // ignore_validation_failures = true → should NOT block, file is written
    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { Foo() }\n".to_owned(),
        ignore_validation_failures: true,
    };
    let _result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed when ignore_validation_failures=true");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // One pre-existing warning (non-error) in both pre and post.
    let existing_warning = LspDiagnostic {
        severity: LspDiagnosticSeverity::Warning,
        code: Some("W001".into()),
        message: "unused import".into(),
        file: filepath.to_owned(),
        start_line: 1,
        end_line: 1,
    };
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![existing_warning.clone()]));
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![existing_warning]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — no new errors");
    let resp = result.0;

    assert!(resp.success);
    assert_eq!(resp.validation.status, "passed");
    assert!(!resp.validation_skipped);
    assert!(resp.validation.introduced_errors.is_empty());
    assert!(resp.validation.resolved_errors.is_empty());
}

// ── empty_diagnostics_both_snapshots: warmup signal ─────────────────────────

#[test]
fn test_build_validation_outcome_empty_snapshots_signals_warmup() {
    // When both pre and post diagnostic snapshots are empty, the validation
    // outcome must be skipped with reason "empty_diagnostics_both_snapshots".
    // This prevents agents from trusting a vacuously-clean pass during LSP warmup.
    use crate::server::tools::edit::text_edit::build_validation_outcome;
    use std::path::Path;

    let outcome = build_validation_outcome(
        &[], // pre_diags: empty (LSP warmup or genuinely clean)
        &[], // post_diags: empty
        false,
        Path::new("src/lib.rs"),
    );

    assert!(
        outcome.skipped,
        "validation_skipped must be true when both snapshots are empty"
    );
    assert_eq!(
        outcome.skipped_reason.as_deref(),
        Some("empty_diagnostics_both_snapshots"),
        "skipped_reason must identify the warmup signal"
    );
    assert_eq!(
        outcome.validation.status, "uncertain",
        "status must be 'uncertain' when both snapshots are empty (LSP may be warming up)"
    );
    assert!(
        !outcome.should_block,
        "should_block must be false — empty snapshots are never a blocker"
    );
}

#[test]
fn test_build_validation_outcome_non_empty_pre_does_not_skip() {
    // If pre_diags has errors but post is empty (errors resolved),
    // we must NOT trigger the warmup-skip path — the diff is meaningful.
    use crate::server::tools::edit::text_edit::build_validation_outcome;
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};
    use std::path::Path;

    let pre = vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: None,
        message: "pre-existing error".to_owned(),
        file: "src/lib.rs".to_owned(),
        start_line: 1,
        end_line: 1,
    }];

    let outcome = build_validation_outcome(&pre, &[], false, Path::new("src/lib.rs"));

    // pre non-empty → NOT the warmup-skip path
    assert!(
        !outcome.skipped,
        "must not skip when pre_diags is non-empty (diff is meaningful)"
    );
    assert_eq!(outcome.validation.status, "passed");
    assert!(!outcome.should_block);
}