silver-platter 0.8.4

Large scale VCS change management
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! MCP (Model Context Protocol) server for silver-platter.
//!
//! Exposes silver-platter functionality as MCP tools over stdio.

use breezyshim::tree::WorkingTree as _;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::model::{ServerCapabilities, ServerInfo};
use rmcp::schemars;
use rmcp::tool;
use rmcp::{tool_handler, tool_router};

/// MCP server exposing silver-platter tools.
#[derive(Debug, Clone)]
pub struct SvpMcpServer {
    tool_router: ToolRouter<Self>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct ListProposalsRequest {
    /// Status filter: "open", "merged", or "closed"
    #[schemars(description = "Filter proposals by status: open, merged, or closed")]
    status: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct GetProposalRequest {
    /// URL of the merge proposal
    #[schemars(description = "URL of the merge proposal to inspect")]
    url: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct BatchStatusRequest {
    /// Path to the batch directory
    #[schemars(description = "Path to the batch directory containing batch.yaml")]
    directory: String,

    /// Specific codebase entry to check
    #[schemars(description = "Name of a specific codebase entry to check status for")]
    codebase: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct ApplyRequest {
    /// Shell command to run in the checkout
    #[schemars(description = "Shell command to run in the working directory")]
    command: String,

    /// Path to the working directory (defaults to current directory)
    #[schemars(description = "Path to the working directory to apply changes in")]
    directory: Option<String>,

    /// Whether to commit pending changes: auto, yes, or no
    #[schemars(description = "Whether to commit pending changes: auto, yes, or no")]
    commit_pending: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct RunRequest {
    /// URL of the repository to modify
    #[schemars(description = "URL of the repository to modify")]
    url: String,

    /// Shell command to run in the checkout
    #[schemars(description = "Shell command to run in the repository checkout")]
    command: String,

    /// Branch name for the change
    #[schemars(description = "Branch name for the proposed change")]
    branch: Option<String>,

    /// Publish mode: push, propose, attempt-push, push-derived
    #[schemars(description = "Publish mode: push, propose, attempt-push, or push-derived")]
    mode: Option<String>,

    /// Whether to commit pending changes: auto, yes, or no
    #[schemars(description = "Whether to commit pending changes: auto, yes, or no")]
    commit_pending: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct BatchPublishRequest {
    /// Path to the batch directory
    #[schemars(description = "Path to the batch directory containing batch.yaml")]
    directory: String,

    /// Specific codebase entry to publish (publishes all if omitted)
    #[schemars(description = "Name of a specific codebase entry to publish")]
    codebase: Option<String>,

    /// Whether to refresh changes before publishing
    #[schemars(description = "Whether to refresh changes before publishing")]
    refresh: Option<bool>,

    /// Whether to overwrite existing branches
    #[schemars(description = "Whether to overwrite existing remote branches")]
    overwrite: Option<bool>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct BatchRefreshRequest {
    /// Path to the batch directory
    #[schemars(description = "Path to the batch directory containing batch.yaml")]
    directory: String,

    /// Specific codebase entry to refresh (refreshes all if omitted)
    #[schemars(description = "Name of a specific codebase entry to refresh")]
    codebase: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct ListConflictedRequest {
    /// Branch name to search for conflicted proposals
    #[schemars(description = "Branch name to search for conflicted proposals")]
    branch_name: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct CloseProposalRequest {
    /// URL of the merge proposal to close
    #[schemars(description = "URL of the merge proposal to close")]
    url: String,
}

impl Default for SvpMcpServer {
    fn default() -> Self {
        Self::new()
    }
}

#[tool_router]
impl SvpMcpServer {
    /// Create a new MCP server instance.
    pub fn new() -> Self {
        Self {
            tool_router: Self::tool_router(),
        }
    }

    #[tool(
        description = "List all configured forges (code hosting platforms like GitHub, GitLab, Launchpad)"
    )]
    fn list_forges(&self) -> String {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let mut result = String::new();
        for instance in breezyshim::forge::iter_forge_instances() {
            result.push_str(&format!(
                "{} ({})\n",
                instance.base_url(),
                instance.forge_kind()
            ));
        }
        if result.is_empty() {
            result.push_str("No forges configured.\n");
        }
        result
    }

    #[tool(description = "List merge proposals by the current user, optionally filtered by status")]
    fn list_proposals(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            ListProposalsRequest,
        >,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let statuses = if let Some(status_str) = &req.status {
            let status: crate::proposal::MergeProposalStatus =
                status_str.parse().map_err(|e: String| {
                    rmcp::ErrorData::new(rmcp::model::ErrorCode::INVALID_PARAMS, e, None)
                })?;
            Some(vec![status])
        } else {
            None
        };

        let mut lines = Vec::new();
        for (_forge, proposal) in crate::proposal::iter_all_mps(statuses) {
            if let Ok(url) = proposal.url() {
                lines.push(url.to_string());
            }
        }

        let text = if lines.is_empty() {
            "No merge proposals found.".to_string()
        } else {
            lines.join("\n")
        };

        Ok(rmcp::model::CallToolResult::success(vec![
            rmcp::model::Content::text(text),
        ]))
    }

    #[tool(
        description = "Run a codemod script on a repository and publish the changes as a merge proposal or push"
    )]
    fn run(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            RunRequest,
        >,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let url: url::Url = req.url.parse().map_err(|e: url::ParseError| {
            rmcp::ErrorData::new(rmcp::model::ErrorCode::INVALID_PARAMS, e.to_string(), None)
        })?;

        let command = shlex::split(&req.command).ok_or_else(|| {
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INVALID_PARAMS,
                "Invalid shell command".to_string(),
                None,
            )
        })?;

        let branch = req.branch.unwrap_or_else(|| {
            crate::derived_branch_name(command.first().map(|s| s.as_str()).unwrap_or("change"))
                .to_string()
        });

        let mode: crate::Mode = if let Some(mode_str) = &req.mode {
            mode_str.parse().map_err(|e: String| {
                rmcp::ErrorData::new(rmcp::model::ErrorCode::INVALID_PARAMS, e, None)
            })?
        } else {
            crate::Mode::Propose
        };

        let commit_pending: crate::CommitPending = if let Some(cp_str) = &req.commit_pending {
            cp_str.parse().map_err(|e: String| {
                rmcp::ErrorData::new(rmcp::model::ErrorCode::INVALID_PARAMS, e, None)
            })?
        } else {
            crate::CommitPending::Auto
        };

        let get_description = |result: &crate::codemod::CommandResult,
                               _description_format,
                               _existing_proposal: Option<&breezyshim::forge::MergeProposal>|
         -> String {
            result
                .description
                .clone()
                .unwrap_or_else(|| "Automated change by silver-platter".to_string())
        };

        let retcode = crate::run::apply_and_publish(
            &url,
            &branch,
            &command.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
            mode,
            commit_pending,
            None,
            false,
            None,
            None,
            false,
            None::<fn(&crate::codemod::CommandResult) -> bool>,
            None::<
                fn(
                    &crate::codemod::CommandResult,
                    Option<&breezyshim::forge::MergeProposal>,
                ) -> Option<String>,
            >,
            None::<
                fn(
                    &crate::codemod::CommandResult,
                    Option<&breezyshim::forge::MergeProposal>,
                ) -> Option<String>,
            >,
            get_description,
            None,
            false,
            None,
        );

        if retcode == 0 {
            Ok(rmcp::model::CallToolResult::success(vec![
                rmcp::model::Content::text("Changes applied and published successfully."),
            ]))
        } else {
            Ok(rmcp::model::CallToolResult::error(vec![
                rmcp::model::Content::text(format!("Command failed with exit code {}", retcode)),
            ]))
        }
    }

    #[tool(description = "Get details about a specific merge proposal by its URL")]
    fn get_proposal(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            GetProposalRequest,
        >,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let url: url::Url = req.url.parse().map_err(|e: url::ParseError| {
            rmcp::ErrorData::new(rmcp::model::ErrorCode::INVALID_PARAMS, e.to_string(), None)
        })?;

        let proposal = breezyshim::forge::get_proposal_by_url(&url).map_err(|e| {
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INTERNAL_ERROR,
                format!("Failed to get proposal: {}", e),
                None,
            )
        })?;

        let mut info = Vec::new();
        info.push(format!("URL: {}", proposal.url().unwrap()));

        if let Ok(Some(title)) = proposal.get_title() {
            info.push(format!("Title: {}", title));
        }

        if let Ok(Some(description)) = proposal.get_description() {
            info.push(format!("Description: {}", description));
        }

        if let Ok(merged) = proposal.is_merged() {
            if merged {
                info.push("Status: Merged".to_string());
            } else if let Ok(closed) = proposal.is_closed() {
                if closed {
                    info.push("Status: Closed".to_string());
                } else {
                    info.push("Status: Open".to_string());
                }
            }
        }

        if let Ok(Some(source_url)) = proposal.get_source_branch_url() {
            info.push(format!("Source branch: {}", source_url));
        }

        if let Ok(Some(target_url)) = proposal.get_target_branch_url() {
            info.push(format!("Target branch: {}", target_url));
        }

        if let Ok(mergeable) = proposal.can_be_merged() {
            info.push(format!("Can be merged: {}", mergeable));
        }

        Ok(rmcp::model::CallToolResult::success(vec![
            rmcp::model::Content::text(info.join("\n")),
        ]))
    }

    #[tool(description = "Show status of a batch directory or specific entry within it")]
    fn batch_status(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            BatchStatusRequest,
        >,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let directory = std::path::Path::new(&req.directory)
            .canonicalize()
            .map_err(|e| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("Invalid directory: {}", e),
                    None,
                )
            })?;

        let batch = crate::batch::load_batch_metadata(&directory)
            .map_err(|e| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INTERNAL_ERROR,
                    format!("Failed to load batch metadata: {}", e),
                    None,
                )
            })?
            .ok_or_else(|| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("No batch.yaml found in {}", directory.display()),
                    None,
                )
            })?;

        let mut lines = Vec::new();
        lines.push(format!("Batch: {}", batch.name));
        lines.push(format!("Entries: {}", batch.work.len()));
        lines.push(String::new());

        if let Some(codebase) = &req.codebase {
            let entry = batch.work.get(codebase.as_str()).ok_or_else(|| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("Entry '{}' not found in batch", codebase),
                    None,
                )
            })?;
            lines.push(format!("{}: {}", codebase, entry.status()));
        } else {
            for (name, entry) in batch.work.iter() {
                lines.push(format!("{}: {}", name, entry.status()));
            }
        }

        Ok(rmcp::model::CallToolResult::success(vec![
            rmcp::model::Content::text(lines.join("\n")),
        ]))
    }

    #[tool(description = "Apply a codemod script to an existing local checkout without publishing")]
    fn apply(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            ApplyRequest,
        >,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let directory = req
            .directory
            .as_deref()
            .map(std::path::Path::new)
            .unwrap_or_else(|| std::path::Path::new("."));

        let command = shlex::split(&req.command).ok_or_else(|| {
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INVALID_PARAMS,
                "Invalid shell command".to_string(),
                None,
            )
        })?;

        let commit_pending: crate::CommitPending = if let Some(cp_str) = &req.commit_pending {
            cp_str.parse().map_err(|e: String| {
                rmcp::ErrorData::new(rmcp::model::ErrorCode::INVALID_PARAMS, e, None)
            })?
        } else {
            crate::CommitPending::Auto
        };

        let (local_tree, subpath) =
            breezyshim::workingtree::open_containing(directory).map_err(|e| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INTERNAL_ERROR,
                    format!("Failed to open working tree: {}", e),
                    None,
                )
            })?;

        breezyshim::workspace::check_clean_tree(
            &local_tree,
            &local_tree.basis_tree().unwrap(),
            subpath.as_path(),
        )
        .map_err(|e| {
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INTERNAL_ERROR,
                format!("Working tree is not clean: {}", e),
                None,
            )
        })?;

        let result = crate::codemod::script_runner(
            &local_tree,
            &command.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
            subpath.as_path(),
            commit_pending,
            None,
            None,
            None,
            std::process::Stdio::inherit(),
        )
        .map_err(|e| {
            breezyshim::workspace::reset_tree(&local_tree, None, Some(subpath.as_path())).ok();
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INTERNAL_ERROR,
                format!("Script failed: {}", e),
                None,
            )
        })?;

        let mut info = Vec::new();
        if let Some(description) = &result.description {
            info.push(format!("Description: {}", description));
        }
        info.push(format!("Old revision: {}", result.old_revision));
        info.push(format!("New revision: {}", result.new_revision));

        Ok(rmcp::model::CallToolResult::success(vec![
            rmcp::model::Content::text(info.join("\n")),
        ]))
    }

    #[tool(
        description = "Publish a batch or specific entry, creating merge proposals or pushing changes"
    )]
    fn batch_publish(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            BatchPublishRequest,
        >,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let directory = std::path::Path::new(&req.directory)
            .canonicalize()
            .map_err(|e| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("Invalid directory: {}", e),
                    None,
                )
            })?;

        let mut batch = crate::batch::load_batch_metadata(&directory)
            .map_err(|e| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INTERNAL_ERROR,
                    format!("Failed to load batch metadata: {}", e),
                    None,
                )
            })?
            .ok_or_else(|| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("No batch.yaml found in {}", directory.display()),
                    None,
                )
            })?;

        let refresh = req.refresh.unwrap_or(false);
        let overwrite = if req.overwrite.unwrap_or(false) {
            Some(true)
        } else {
            None
        };

        let mut lines = Vec::new();
        let mut errors = 0;
        let batch_name = batch.name.clone();

        if let Some(codebase) = &req.codebase {
            let entry = batch.get_mut(codebase).ok_or_else(|| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("Entry '{}' not found in batch", codebase),
                    None,
                )
            })?;
            match entry.publish(&batch_name, refresh, overwrite) {
                Ok(result) => {
                    lines.push(format!("{}: published (mode: {})", codebase, result.mode));
                    if let Some(proposal) = &result.proposal {
                        if let Ok(url) = proposal.url() {
                            lines.push(format!("  Proposal: {}", url));
                        }
                    }
                }
                Err(e) => {
                    lines.push(format!("{}: failed - {}", codebase, e));
                    errors += 1;
                }
            }
        } else {
            let names: Vec<String> = batch.work.keys().cloned().collect();
            for name in &names {
                let entry = batch.get_mut(name).unwrap();
                match entry.publish(&batch_name, refresh, overwrite) {
                    Ok(result) => {
                        lines.push(format!("{}: published (mode: {})", name, result.mode));
                        if let Some(proposal) = &result.proposal {
                            if let Ok(url) = proposal.url() {
                                lines.push(format!("  Proposal: {}", url));
                            }
                        }
                    }
                    Err(crate::publish::Error::EmptyMergeProposal) => {
                        lines.push(format!("{}: no changes left, removed", name));
                        batch.remove(name).ok();
                    }
                    Err(e) => {
                        lines.push(format!("{}: failed - {}", name, e));
                        errors += 1;
                    }
                }
            }
        }

        crate::batch::save_batch_metadata(&directory, &batch).map_err(|e| {
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INTERNAL_ERROR,
                format!("Failed to save batch metadata: {}", e),
                None,
            )
        })?;

        if batch.work.is_empty() {
            lines.push(format!(
                "\nNo work left in batch; you can remove {}",
                directory.display()
            ));
        }

        if errors > 0 {
            lines.insert(0, format!("{} entries failed to publish", errors));
        }

        Ok(rmcp::model::CallToolResult::success(vec![
            rmcp::model::Content::text(lines.join("\n")),
        ]))
    }

    #[tool(description = "Refresh changes in a batch by re-running the recipe script on entries")]
    fn batch_refresh(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            BatchRefreshRequest,
        >,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let directory = std::path::Path::new(&req.directory)
            .canonicalize()
            .map_err(|e| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("Invalid directory: {}", e),
                    None,
                )
            })?;

        let mut batch = crate::batch::load_batch_metadata(&directory)
            .map_err(|e| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INTERNAL_ERROR,
                    format!("Failed to load batch metadata: {}", e),
                    None,
                )
            })?
            .ok_or_else(|| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("No batch.yaml found in {}", directory.display()),
                    None,
                )
            })?;

        let mut lines = Vec::new();
        let mut errors = 0;

        if let Some(codebase) = &req.codebase {
            let entry = batch.work.get_mut(codebase.as_str()).ok_or_else(|| {
                rmcp::ErrorData::new(
                    rmcp::model::ErrorCode::INVALID_PARAMS,
                    format!("Entry '{}' not found in batch", codebase),
                    None,
                )
            })?;
            match entry.refresh(&batch.recipe, None) {
                Ok(()) => lines.push(format!("{}: refreshed", codebase)),
                Err(e) => {
                    lines.push(format!("{}: failed - {}", codebase, e));
                    errors += 1;
                }
            }
        } else {
            let names: Vec<String> = batch.work.keys().cloned().collect();
            for name in &names {
                let entry = batch.work.get_mut(name.as_str()).unwrap();
                match entry.refresh(&batch.recipe, None) {
                    Ok(()) => lines.push(format!("{}: refreshed", name)),
                    Err(e) => {
                        lines.push(format!("{}: failed - {}", name, e));
                        errors += 1;
                    }
                }
            }
        }

        crate::batch::save_batch_metadata(&directory, &batch).map_err(|e| {
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INTERNAL_ERROR,
                format!("Failed to save batch metadata: {}", e),
                None,
            )
        })?;

        if errors > 0 {
            lines.insert(0, format!("{} entries failed to refresh", errors));
        }

        Ok(rmcp::model::CallToolResult::success(vec![
            rmcp::model::Content::text(lines.join("\n")),
        ]))
    }

    #[tool(
        description = "List open merge proposals that have merge conflicts for a given branch name"
    )]
    fn list_conflicted(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            ListConflictedRequest,
        >,
    ) -> String {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let mut lines = Vec::new();
        for (url, _main_branch, _subpath, _resume_branch, _forge, mp, _) in
            crate::proposal::iter_conflicted(&req.branch_name)
        {
            let mp_url = mp.url().unwrap_or(url);
            lines.push(mp_url.to_string());
        }

        if lines.is_empty() {
            format!(
                "No conflicted proposals found for branch '{}'.",
                req.branch_name
            )
        } else {
            format!(
                "Conflicted proposals for branch '{}':\n{}",
                req.branch_name,
                lines.join("\n")
            )
        }
    }

    #[tool(description = "Close a merge proposal by its URL")]
    fn close_proposal(
        &self,
        rmcp::handler::server::wrapper::Parameters(req): rmcp::handler::server::wrapper::Parameters<
            CloseProposalRequest,
        >,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        breezyshim::init();
        breezyshim::plugin::load_plugins();

        let url: url::Url = req.url.parse().map_err(|e: url::ParseError| {
            rmcp::ErrorData::new(rmcp::model::ErrorCode::INVALID_PARAMS, e.to_string(), None)
        })?;

        let proposal = breezyshim::forge::get_proposal_by_url(&url).map_err(|e| {
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INTERNAL_ERROR,
                format!("Failed to get proposal: {}", e),
                None,
            )
        })?;

        proposal.close().map_err(|e| {
            rmcp::ErrorData::new(
                rmcp::model::ErrorCode::INTERNAL_ERROR,
                format!("Failed to close proposal: {}", e),
                None,
            )
        })?;

        Ok(rmcp::model::CallToolResult::success(vec![
            rmcp::model::Content::text(format!("Proposal {} closed.", url)),
        ]))
    }
}

#[tool_handler]
impl rmcp::handler::server::ServerHandler for SvpMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder().enable_tools().build(),
        )
        .with_instructions("Silver-Platter: large-scale VCS change management. Automate contributing changes to source code repositories.".to_string())
    }
}

/// Run the MCP server over stdio.
pub async fn serve_stdio() -> Result<(), Box<dyn std::error::Error>> {
    use rmcp::ServiceExt;

    let server = SvpMcpServer::new();
    let service = server.serve(rmcp::transport::stdio()).await?;
    service.waiting().await?;
    Ok(())
}

/// Run the MCP server over HTTP/SSE.
#[cfg(feature = "mcp-sse")]
pub async fn serve_sse(addr: &str) -> Result<(), Box<dyn std::error::Error>> {
    use rmcp::transport::streamable_http_server::{
        session::local::LocalSessionManager, StreamableHttpServerConfig, StreamableHttpService,
    };
    use std::sync::Arc;

    let ct = tokio_util::sync::CancellationToken::new();

    let config = StreamableHttpServerConfig {
        stateful_mode: true,
        json_response: false,
        sse_keep_alive: Some(std::time::Duration::from_secs(15)),
        sse_retry: Some(std::time::Duration::from_secs(3)),
        cancellation_token: ct.clone(),
    };

    let service = StreamableHttpService::new(
        || Ok(SvpMcpServer::new()),
        Arc::new(LocalSessionManager::default()),
        config,
    );

    let router = axum::Router::new().nest_service("/mcp", service);
    let listener = tokio::net::TcpListener::bind(addr).await?;
    log::info!("MCP SSE server listening on {}", addr);
    axum::serve(listener, router)
        .with_graceful_shutdown(async move { ct.cancelled().await })
        .await?;
    Ok(())
}