omni-dev 0.32.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, and Datadog.
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! MCP tool handlers for git operations.
//!
//! Each handler delegates to the same `run_*` function that the CLI uses, so
//! the MCP surface and the CLI share a single implementation.

use std::path::PathBuf;

use rmcp::{
    handler::server::wrapper::Parameters,
    model::{CallToolResult, Content},
    schemars, tool, tool_router, ErrorData as McpError,
};
use serde::Deserialize;
use serde_json::json;
use tokio_util::sync::CancellationToken;

use super::cancel::spawn_blocking_cancellable;
use super::error::tool_error;
use super::server::OmniDevServer;
use super::truncate::{truncate_response, DEFAULT_MAX_RESPONSE_BYTES};
use super::validate::{validate_range, validate_repo_path};

/// Parameters for the `git_view_commits` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct GitViewCommitsParams {
    /// Commit range to analyze (e.g., `HEAD~3..HEAD`, `abc123..def456`).
    /// Defaults to `HEAD` when omitted.
    #[serde(default)]
    pub range: Option<String>,
    /// Path to the git repository. Must be absolute when provided.
    /// Defaults to the current working directory.
    #[serde(default)]
    pub repo_path: Option<String>,
}

/// Parameters for the `git_branch_info` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct GitBranchInfoParams {
    /// Base branch to compare against, e.g. `main` or `develop`.
    /// When omitted, resolved remote-first: `origin/main`, `origin/master`,
    /// local `main`, then local `master`.
    #[serde(default)]
    pub branch: Option<String>,
    /// Path to the git repository. Defaults to the current working directory.
    #[serde(default)]
    pub repo_path: Option<String>,
}

/// Parameters for the `git_check_commits` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct GitCheckCommitsParams {
    /// Commit range to check (e.g., `HEAD~3..HEAD`, `abc123..def456`).
    /// Required — unlike the CLI, this tool does not default to "commits ahead
    /// of the base branch".
    pub range: String,
    /// Optional explicit path to the guidelines file. When omitted the tool
    /// falls back to `.omni-dev/commit-guidelines.md` via the standard
    /// resolution chain.
    #[serde(default)]
    pub guidelines_path: Option<String>,
    /// Path to the git repository. Defaults to the current working directory.
    #[serde(default)]
    pub repo_path: Option<String>,
    /// When true, warnings are treated as non-zero exit conditions.
    /// Defaults to `false` (only errors fail).
    #[serde(default)]
    pub strict: bool,
    /// Claude model override (e.g. `claude-sonnet-4-6`). Defaults to the model
    /// from settings, then the built-in default, when omitted.
    #[serde(default)]
    pub model: Option<String>,
}

/// Parameters for the `git_twiddle_commits` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct GitTwiddleCommitsParams {
    /// Commit range to twiddle (e.g., `HEAD~3..HEAD`, `abc123..def456`).
    /// Defaults to `HEAD~5..HEAD` when omitted.
    #[serde(default)]
    pub range: Option<String>,
    /// Claude model override (e.g. `claude-sonnet-4-6`). Defaults to the model
    /// from settings, then the built-in default, when omitted.
    #[serde(default)]
    pub model: Option<String>,
    /// When true, proposed amendments are returned without being applied.
    /// When false (or omitted), amendments are applied automatically — the
    /// MCP boundary is non-interactive and therefore forces `--auto-apply`
    /// semantics; no editor is started.
    #[serde(default)]
    pub dry_run: bool,
    /// Path to the git repository. Defaults to the current working directory.
    #[serde(default)]
    pub repo_path: Option<String>,
}

/// Parameters for the `git_staged_commit` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct GitStagedCommitParams {
    /// When true, the generated commit message is returned without being
    /// committed to the repository. Defaults to `false` (commit applied).
    #[serde(default)]
    pub print_only: bool,
    /// Claude model override (e.g. `claude-sonnet-4-6`). Defaults to the model
    /// from settings, then the built-in default, when omitted.
    #[serde(default)]
    pub model: Option<String>,
    /// Path to the git repository. Defaults to the current working directory.
    #[serde(default)]
    pub repo_path: Option<String>,
}

/// Parameters for the `git_amend_commits` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct GitAmendCommitsParams {
    /// Amendments to apply, as an inline YAML document with an `amendments`
    /// list. Each entry needs `commit` (full 40-char SHA), `message` (the new
    /// message), and `summary` (may be empty), matching the YAML produced by
    /// `git_twiddle_commits` in `dry_run` mode. Applied deterministically — no
    /// AI is involved.
    pub amendments_yaml: String,
    /// When true, permits amending commits that already exist in a remote main
    /// branch (rewrites published history). Defaults to `false`, which refuses
    /// such commits — mirrors the CLI `--allow-pushed` flag.
    #[serde(default)]
    pub allow_pushed: bool,
    /// Path to the git repository. Defaults to the current working directory.
    #[serde(default)]
    pub repo_path: Option<String>,
}

/// Parameters for the `git_create_pr` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct GitCreatePrParams {
    /// Claude model override (e.g. `claude-sonnet-4-6`). Defaults to the model
    /// from settings, then the built-in default, when omitted.
    #[serde(default)]
    pub model: Option<String>,
    /// Base branch the PR would merge into, e.g. `main` or `develop`.
    /// Defaults to the primary remote's main branch when omitted.
    #[serde(default)]
    pub base_branch: Option<String>,
    /// Path to the git repository. Defaults to the current working directory.
    #[serde(default)]
    pub repo_path: Option<String>,
}

#[allow(missing_docs)] // #[tool_router] generates a pub `git_tool_router` fn.
#[tool_router(router = git_tool_router, vis = "pub")]
impl OmniDevServer {
    /// Tool: analyse commits in a range and return repository information as YAML.
    #[tool(
        description = "Analyze commits in a range and return repository information as YAML. \
                       Use this when you have an explicit commit range (e.g. `HEAD~3..HEAD`); \
                       use `git_branch_info` instead to analyze the current branch against a base \
                       branch without computing the range yourself. \
                       Mirrors `omni-dev git commit message view`."
    )]
    pub async fn git_view_commits(
        &self,
        Parameters(params): Parameters<GitViewCommitsParams>,
        cancellation: CancellationToken,
    ) -> Result<CallToolResult, McpError> {
        let range = params.range.as_deref().unwrap_or("HEAD").to_string();
        validate_range(&range)?;
        let repo_path = params.repo_path.clone();
        repo_path.as_deref().map(validate_repo_path).transpose()?;

        tracing::debug!(
            tool = "git_view_commits",
            range = %range,
            repo_path = ?repo_path,
            "invoking tool"
        );

        let range_for_task = range.clone();
        let yaml = spawn_blocking_cancellable(&cancellation, move || {
            crate::cli::git::run_view(&range_for_task, repo_path.as_deref())
        })
        .await?;

        Ok(build_truncated_result(yaml))
    }

    /// Tool: analyse branch commits and return repository info as YAML.
    #[tool(
        description = "Analyze the current branch's commits against a base branch and return \
                       repository information as YAML. Use this when you want the diff against \
                       `main`/`master` (or another base) without computing an explicit range; \
                       use `git_view_commits` instead when you already have a range. \
                       Mirrors `omni-dev git branch info`."
    )]
    pub async fn git_branch_info(
        &self,
        Parameters(params): Parameters<GitBranchInfoParams>,
    ) -> Result<CallToolResult, McpError> {
        let branch = params.branch.clone();
        let repo_path = params.repo_path.clone();

        let yaml = tokio::task::spawn_blocking(move || {
            crate::cli::git::run_info(branch.as_deref(), repo_path.as_deref())
        })
        .await
        .map_err(|e| tool_error(anyhow::anyhow!("join error: {e}")))?
        .map_err(tool_error)?;

        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }

    /// Tool: validate commit messages against guidelines.
    #[tool(
        description = "Validate commit messages in a range against commit guidelines \
                       (read-only — never modifies commits). Use this to report problems; use \
                       `git_twiddle_commits` instead to rewrite the messages. `range` is required \
                       (e.g. `HEAD~3..HEAD`). Mirrors `omni-dev git commit message check`. Returns \
                       a YAML payload with the full CheckReport, a pass/fail summary, and the exit \
                       code the CLI would use (honouring `strict`)."
    )]
    pub async fn git_check_commits(
        &self,
        Parameters(params): Parameters<GitCheckCommitsParams>,
    ) -> Result<CallToolResult, McpError> {
        let outcome = crate::cli::git::run_check(
            &params.range,
            params.guidelines_path.as_deref().map(std::path::Path::new),
            params.repo_path.as_deref().map(std::path::Path::new),
            params.strict,
            params.model,
        )
        .await
        .map_err(tool_error)?;

        Ok(CallToolResult::success(vec![Content::text(
            format_check_payload(&outcome),
        )]))
    }

    /// Tool: AI-powered commit message improvement.
    #[tool(
        description = "Generate improved commit messages for a range (e.g. `HEAD~3..HEAD`) and \
                       (by default) apply them. Mutating: rewrites commit messages unless \
                       `dry_run = true`. Use this to fix messages; use `git_check_commits` instead \
                       to only report problems without modifying anything. Mirrors \
                       `omni-dev git commit message twiddle --auto-apply`. Set `dry_run = true` to \
                       return the proposed amendments as YAML without applying them. The editor is \
                       never started from this tool. Commits already contained in a remote main \
                       branch are refused (rewriting published history); overriding requires a \
                       human running `omni-dev git commit message amend --allow-pushed` from the CLI."
    )]
    pub async fn git_twiddle_commits(
        &self,
        Parameters(params): Parameters<GitTwiddleCommitsParams>,
    ) -> Result<CallToolResult, McpError> {
        let range = params.range.clone();
        let model = params.model.clone();
        let dry_run = params.dry_run;
        let repo_path: Option<PathBuf> = params.repo_path.as_deref().map(PathBuf::from);

        let outcome =
            crate::cli::git::run_twiddle(range.as_deref(), model, dry_run, repo_path.as_deref())
                .await
                .map_err(tool_error)?;

        Ok(CallToolResult::success(vec![Content::text(
            format_twiddle_payload(&outcome, dry_run),
        )]))
    }

    /// Tool: apply commit message amendments from an inline YAML document.
    #[tool(
        description = "Apply commit message amendments deterministically from an inline YAML \
                       document (no AI). This is the apply-messages-from-YAML counterpart to \
                       `git_twiddle_commits`: use `git_twiddle_commits` with `dry_run = true` to \
                       generate the `amendments` YAML, then pass it here to apply. Mutating: \
                       rewrites commit messages via `git commit --amend` / interactive rebase. \
                       Mirrors `omni-dev git commit message amend`. Commits already contained in a \
                       remote main branch are refused unless `allow_pushed = true` (rewriting \
                       published history)."
    )]
    pub async fn git_amend_commits(
        &self,
        Parameters(params): Parameters<GitAmendCommitsParams>,
        cancellation: CancellationToken,
    ) -> Result<CallToolResult, McpError> {
        let repo_path = params.repo_path.clone();
        repo_path.as_deref().map(validate_repo_path).transpose()?;

        let amendments_yaml = params.amendments_yaml.clone();
        let allow_pushed = params.allow_pushed;
        let outcome = spawn_blocking_cancellable(&cancellation, move || {
            crate::cli::git::run_amend(
                &amendments_yaml,
                allow_pushed,
                repo_path.as_deref().map(std::path::Path::new),
            )
        })
        .await?;

        Ok(CallToolResult::success(vec![Content::text(
            format_amend_payload(&outcome),
        )]))
    }

    /// Tool: generate a commit message from staged changes and commit them.
    #[tool(
        description = "Generate a Conventional Commits message from the currently staged diff \
                       and (by default) commit it via `git commit -m`. Mirrors \
                       `omni-dev git commit message staged`. Set `print_only = true` to return \
                       the generated message without committing."
    )]
    pub async fn git_staged_commit(
        &self,
        Parameters(params): Parameters<GitStagedCommitParams>,
    ) -> Result<CallToolResult, McpError> {
        let print_only = params.print_only;
        let model = params.model.clone();
        params
            .repo_path
            .as_deref()
            .map(validate_repo_path)
            .transpose()?;
        let repo_path: Option<PathBuf> = params.repo_path.as_deref().map(PathBuf::from);

        let outcome =
            crate::cli::git::run_staged(print_only, model, None, None, repo_path.as_deref())
                .await
                .map_err(tool_error)?;

        Ok(CallToolResult::success(vec![Content::text(
            format_staged_payload(&outcome, print_only),
        )]))
    }

    /// Tool: generate a PR title + description via the AI.
    #[tool(
        description = "Generate an AI-drafted pull request title and description for the \
                       current branch. Mirrors `omni-dev git branch create pr` in its \
                       content-generation phase — this tool returns the proposed PR content as \
                       YAML and does NOT push the branch or invoke `gh pr create`."
    )]
    pub async fn git_create_pr(
        &self,
        Parameters(params): Parameters<GitCreatePrParams>,
    ) -> Result<CallToolResult, McpError> {
        let model = params.model.clone();
        let base_branch = params.base_branch.clone();
        let repo_path: Option<PathBuf> = params.repo_path.as_deref().map(PathBuf::from);

        let outcome =
            crate::cli::git::run_create_pr(model, base_branch.as_deref(), repo_path.as_deref())
                .await
                .map_err(tool_error)?;

        Ok(CallToolResult::success(vec![Content::text(
            outcome.pr_yaml,
        )]))
    }
}

/// Wraps a text result in a `CallToolResult`, applying the default response
/// cap and emitting a second `Content::text` payload carrying a JSON
/// `{"truncated": bool, "original_bytes": usize}` marker when truncation
/// happened.
///
/// Shared by every tool that can produce large output so the truncation
/// contract is consistent across the MCP surface.
pub(crate) fn build_truncated_result(text: String) -> CallToolResult {
    let original_bytes = text.len();
    let (body, truncated) = truncate_response(text, DEFAULT_MAX_RESPONSE_BYTES);
    if truncated {
        let marker = json!({
            "truncated": true,
            "original_bytes": original_bytes,
            "limit_bytes": DEFAULT_MAX_RESPONSE_BYTES,
        });
        CallToolResult::success(vec![Content::text(body), Content::text(marker.to_string())])
    } else {
        CallToolResult::success(vec![Content::text(body)])
    }
}

/// Indents a multi-line string for inclusion as a YAML block scalar value.
fn indent_for_yaml(body: &str) -> String {
    body.lines()
        .map(|line| format!("  {line}"))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Formats the payload returned by the `git_check_commits` tool.
fn format_check_payload(outcome: &crate::cli::git::CheckOutcome) -> String {
    format!(
        "# git_check_commits outcome\nexit_code: {}\nstrict: {}\nhas_errors: {}\nhas_warnings: {}\ntotal_commits: {}\nreport: |\n{}",
        outcome.exit_code,
        outcome.strict,
        outcome.has_errors,
        outcome.has_warnings,
        outcome.total_commits,
        indent_for_yaml(&outcome.report_yaml),
    )
}

/// Formats the payload returned by the `git_twiddle_commits` tool.
fn format_twiddle_payload(outcome: &crate::cli::git::TwiddleOutcome, dry_run: bool) -> String {
    format!(
        "# git_twiddle_commits outcome\napplied: {}\ndry_run: {}\namendment_count: {}\namendments: |\n{}",
        outcome.applied,
        dry_run,
        outcome.amendment_count,
        indent_for_yaml(&outcome.amendments_yaml),
    )
}

/// Formats the payload returned by the `git_amend_commits` tool.
fn format_amend_payload(outcome: &crate::cli::git::AmendOutcome) -> String {
    format!(
        "# git_amend_commits outcome\napplied: {}\namendment_count: {}",
        outcome.applied, outcome.amendment_count,
    )
}

/// Formats the payload returned by the `git_staged_commit` tool.
fn format_staged_payload(outcome: &crate::cli::git::StagedOutcome, print_only: bool) -> String {
    format!(
        "# git_staged_commit outcome\napplied: {}\nprint_only: {}\nmessage: |\n{}",
        outcome.applied,
        print_only,
        indent_for_yaml(&outcome.message),
    )
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::cli::git::{CheckOutcome, StagedOutcome, TwiddleOutcome};

    #[test]
    fn build_truncated_result_leaves_small_output_alone() {
        let result = build_truncated_result("hello".to_string());
        assert_eq!(result.content.len(), 1);
    }

    #[test]
    fn build_truncated_result_appends_marker_when_over_cap() {
        let big = "x".repeat(DEFAULT_MAX_RESPONSE_BYTES + 1024);
        let result = build_truncated_result(big);
        assert_eq!(result.content.len(), 2, "expected body + truncation marker");
        let marker_raw = result.content[1]
            .as_text()
            .expect("second payload should be text")
            .text
            .clone();
        let parsed: serde_json::Value = serde_json::from_str(&marker_raw).expect("marker is JSON");
        assert_eq!(parsed["truncated"], serde_json::Value::Bool(true));
        let original = parsed["original_bytes"].as_u64().unwrap();
        let limit = parsed["limit_bytes"].as_u64().unwrap();
        assert!(original > limit);
    }

    #[test]
    fn indent_for_yaml_empty_string() {
        assert_eq!(indent_for_yaml(""), "");
    }

    #[test]
    fn indent_for_yaml_single_line() {
        assert_eq!(indent_for_yaml("hello"), "  hello");
    }

    #[test]
    fn indent_for_yaml_multi_line() {
        let input = "line1\nline2\nline3";
        let expected = "  line1\n  line2\n  line3";
        assert_eq!(indent_for_yaml(input), expected);
    }

    #[test]
    fn format_check_payload_includes_all_fields() {
        let outcome = CheckOutcome {
            report_yaml: "checks:\n  - commit: abc\n".to_string(),
            has_errors: true,
            has_warnings: false,
            total_commits: 3,
            strict: true,
            exit_code: 1,
        };
        let payload = format_check_payload(&outcome);
        assert!(payload.contains("exit_code: 1"));
        assert!(payload.contains("strict: true"));
        assert!(payload.contains("has_errors: true"));
        assert!(payload.contains("has_warnings: false"));
        assert!(payload.contains("total_commits: 3"));
        assert!(payload.contains("  checks:"), "report should be indented");
    }

    #[test]
    fn format_check_payload_clean_outcome() {
        let outcome = CheckOutcome {
            report_yaml: String::new(),
            has_errors: false,
            has_warnings: false,
            total_commits: 0,
            strict: false,
            exit_code: 0,
        };
        let payload = format_check_payload(&outcome);
        assert!(payload.contains("exit_code: 0"));
        assert!(payload.contains("strict: false"));
    }

    #[test]
    fn format_twiddle_payload_applied() {
        let outcome = TwiddleOutcome {
            amendments_yaml: "amendments:\n  - commit: abc\n".to_string(),
            applied: true,
            amendment_count: 2,
        };
        let payload = format_twiddle_payload(&outcome, false);
        assert!(payload.contains("applied: true"));
        assert!(payload.contains("dry_run: false"));
        assert!(payload.contains("amendment_count: 2"));
        assert!(payload.contains("  amendments:"));
    }

    #[test]
    fn format_twiddle_payload_dry_run_not_applied() {
        let outcome = TwiddleOutcome {
            amendments_yaml: "amendments: []\n".to_string(),
            applied: false,
            amendment_count: 0,
        };
        let payload = format_twiddle_payload(&outcome, true);
        assert!(payload.contains("applied: false"));
        assert!(payload.contains("dry_run: true"));
        assert!(payload.contains("amendment_count: 0"));
    }

    #[test]
    fn format_staged_payload_applied() {
        let outcome = StagedOutcome {
            message: "feat(cli): add staged subcommand".to_string(),
            applied: true,
        };
        let payload = format_staged_payload(&outcome, false);
        assert!(payload.contains("applied: true"));
        assert!(payload.contains("print_only: false"));
        assert!(payload.contains("  feat(cli): add staged subcommand"));
    }

    #[test]
    fn format_staged_payload_print_only() {
        let outcome = StagedOutcome {
            message: "fix(x): y\n\nBody.".to_string(),
            applied: false,
        };
        let payload = format_staged_payload(&outcome, true);
        assert!(payload.contains("applied: false"));
        assert!(payload.contains("print_only: true"));
        assert!(payload.contains("  fix(x): y"));
        assert!(payload.contains("  Body."));
    }

    // Direct MCP handler invocation — exercises parameter destructuring and
    // error wrapping without needing a full duplex client/server pair.

    #[tokio::test]
    async fn git_branch_info_handler_invalid_repo_path_returns_tool_error() {
        use crate::mcp::server::OmniDevServer;
        use rmcp::handler::server::wrapper::Parameters;

        let server = OmniDevServer::new();
        let params = GitBranchInfoParams {
            branch: None,
            repo_path: Some("/no/such/path/for/mcp/test".to_string()),
        };
        let err = server
            .git_branch_info(Parameters(params))
            .await
            .unwrap_err();
        assert!(!err.message.is_empty(), "expected non-empty error message");
    }

    #[tokio::test]
    async fn git_check_commits_handler_invalid_repo_path_returns_tool_error() {
        use crate::mcp::server::OmniDevServer;
        use rmcp::handler::server::wrapper::Parameters;

        let server = OmniDevServer::new();
        let params = GitCheckCommitsParams {
            range: "HEAD".to_string(),
            guidelines_path: None,
            repo_path: Some("/no/such/path/for/mcp/test".to_string()),
            strict: false,
            model: None,
        };
        let err = server
            .git_check_commits(Parameters(params))
            .await
            .unwrap_err();
        assert!(!err.message.is_empty());
    }

    #[tokio::test]
    async fn git_twiddle_commits_handler_invalid_repo_path_returns_tool_error() {
        use crate::mcp::server::OmniDevServer;
        use rmcp::handler::server::wrapper::Parameters;

        let server = OmniDevServer::new();
        let params = GitTwiddleCommitsParams {
            range: None,
            model: None,
            dry_run: true,
            repo_path: Some("/no/such/path/for/mcp/test".to_string()),
        };
        let err = server
            .git_twiddle_commits(Parameters(params))
            .await
            .unwrap_err();
        assert!(!err.message.is_empty());
    }

    #[tokio::test]
    async fn git_staged_commit_handler_invalid_repo_path_returns_tool_error() {
        use crate::mcp::server::OmniDevServer;
        use rmcp::handler::server::wrapper::Parameters;

        let server = OmniDevServer::new();
        let params = GitStagedCommitParams {
            print_only: true,
            model: None,
            repo_path: Some("/no/such/path/for/mcp/test".to_string()),
        };
        let err = server
            .git_staged_commit(Parameters(params))
            .await
            .unwrap_err();
        assert!(!err.message.is_empty());
    }

    #[tokio::test]
    async fn git_create_pr_handler_invalid_repo_path_returns_tool_error() {
        use crate::mcp::server::OmniDevServer;
        use rmcp::handler::server::wrapper::Parameters;

        let server = OmniDevServer::new();
        let params = GitCreatePrParams {
            model: None,
            base_branch: None,
            repo_path: Some("/no/such/path/for/mcp/test".to_string()),
        };
        let err = server.git_create_pr(Parameters(params)).await.unwrap_err();
        assert!(!err.message.is_empty());
    }

    #[test]
    fn format_amend_payload_reports_applied_and_count() {
        let outcome = crate::cli::git::AmendOutcome {
            applied: true,
            amendment_count: 3,
        };
        let payload = format_amend_payload(&outcome);
        assert!(payload.contains("applied: true"));
        assert!(payload.contains("amendment_count: 3"));
    }

    #[test]
    fn format_amend_payload_reports_noop() {
        let outcome = crate::cli::git::AmendOutcome {
            applied: false,
            amendment_count: 0,
        };
        let payload = format_amend_payload(&outcome);
        assert!(payload.contains("applied: false"));
        assert!(payload.contains("amendment_count: 0"));
    }

    #[tokio::test]
    async fn git_amend_commits_handler_invalid_repo_path_returns_tool_error() {
        use crate::mcp::server::OmniDevServer;
        use rmcp::handler::server::wrapper::Parameters;
        use tokio_util::sync::CancellationToken;

        let server = OmniDevServer::new();
        let params = GitAmendCommitsParams {
            amendments_yaml: "amendments: []\n".to_string(),
            allow_pushed: false,
            repo_path: Some("/no/such/path/for/mcp/test".to_string()),
        };
        let err = server
            .git_amend_commits(Parameters(params), CancellationToken::new())
            .await
            .unwrap_err();
        assert!(!err.message.is_empty());
    }
}