use rmcp::{
ErrorData as McpError,
RoleServer,
ServerHandler,
handler::server::{
router::tool::ToolRouter,
wrapper::Parameters,
},
model::*,
service::RequestContext,
tool,
tool_handler,
tool_router,
};
use serde_json::json;
use std::sync::Arc;
use tokio::sync::RwLock;
use crate::{BranchManager, VcsManager, Config, BranchStatus};
#[derive(Clone)]
pub struct CodetreeServer {
branch_manager: Arc<RwLock<BranchManager>>,
git_manager: Arc<VcsManager>,
codetree_config: Config,
#[allow(dead_code)]
tool_router: ToolRouter<Self>,
}
impl CodetreeServer {
pub fn new(
branch_manager: Arc<RwLock<BranchManager>>,
git_manager: Arc<VcsManager>,
codetree_config: Config,
) -> Self {
Self {
branch_manager,
git_manager,
codetree_config,
tool_router: Self::tool_router(),
}
}
fn _create_resource_text(&self, uri: &str, name: &str) -> Resource {
Resource::new(
rmcp::model::RawResource {
uri: uri.to_string(),
name: name.to_string(),
title: None,
description: None,
mime_type: Some("text/plain".to_string()),
size: None,
icons: None,
meta: None,
},
None,
)
}
}
#[tool_router]
impl CodetreeServer {
#[tool(description = "Initialize codetree in current directory")]
async fn init_repository(
&self,
Parameters(args): Parameters<InitRepositoryArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
match crate::commands::init_command(args.force).await {
Ok(()) => {
let result = json!({
"success": true,
"message": if args.force {
"Repository reinitialized with codetree"
} else {
"Repository initialized with codetree"
},
"config_file": ".codetree/config.toml"
});
Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
}
Err(e) => {
let result = json!({"success": false, "error": e.to_string()});
Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
}
}
}
#[tool(description = "Start a new mini-operation branch")]
async fn start_op(
&self,
Parameters(args): Parameters<StartOpArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let slug = crate::utils::slugify(&args.description);
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let branch_prefix: String = if let Some(template_name) = &args.template {
if let Some(tmpl) = self.codetree_config.get_template(template_name) {
tmpl.branch_prefix.clone().unwrap_or_else(|| self.codetree_config.git.branch_prefix.clone())
} else {
let err = json!({"success": false, "error": format!("Unknown template: '{}'", template_name)});
return Ok(CallToolResult::success(vec![Content::text(err.to_string())]));
}
} else {
self.codetree_config.git.branch_prefix.clone()
};
let branch_name = format!("{}_{}_{}", branch_prefix, timestamp, slug);
let current = match self.git_manager.get_current_branch().await {
Ok(b) => b,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
};
let base_branch = {
let bm = self.branch_manager.read().await;
if let Some(branch) = bm.get_branch(¤t) {
if matches!(branch.status, crate::BranchStatus::Active) {
current.clone()
} else {
self.codetree_config.git.base_branch.clone()
}
} else {
self.codetree_config.git.base_branch.clone()
}
};
let res = if args.branchless {
let mut bm = self.branch_manager.write().await;
match bm.register_branch_full(&branch_name, args.files.clone().unwrap_or_default(), args.description, args.depends_on.clone().unwrap_or_default(), args.template.clone(), args.tags.clone().unwrap_or_default(), args.agent_id.clone()).await {
Ok(_) => {
if let Some(branch) = bm.branches.get_mut(&branch_name) {
branch.branchless = true;
let _ = bm.save().await;
}
json!({"success": true, "branch": branch_name, "status": "created_branchless", "base": current})
}
Err(e) => json!({"success": false, "error": e.to_string()}),
}
} else if args.worktree {
let worktree_path = self.git_manager.repo_path().join(".codetree").join("worktrees").join(&branch_name);
match tokio::fs::create_dir_all(&worktree_path).await {
Ok(_) => match self.git_manager.add_worktree_new_branch(&branch_name, &worktree_path, &base_branch).await {
Ok(_) => {
let mut bm = self.branch_manager.write().await;
match bm.register_branch_full(&branch_name, args.files.clone().unwrap_or_default(), args.description, args.depends_on.clone().unwrap_or_default(), args.template.clone(), args.tags.clone().unwrap_or_default(), args.agent_id.clone()).await {
Ok(_) => {
let _ = bm.set_branch_worktree(&branch_name, worktree_path.clone()).await;
json!({"success": true, "branch": branch_name, "status": "created_worktree", "base": base_branch, "worktree": worktree_path.to_string_lossy()})
}
Err(e) => json!({"success": false, "error": e.to_string()}),
}
}
Err(e) => json!({"success": false, "error": e.to_string()}),
}
Err(e) => json!({"success": false, "error": e.to_string()}),
}
} else {
match self.git_manager.create_branch(&branch_name, Some(&base_branch)).await {
Ok(_) => {
if args.parallel {
let mut bm = self.branch_manager.write().await;
match bm.register_branch_full(&branch_name, args.files.clone().unwrap_or_default(), args.description, args.depends_on.clone().unwrap_or_default(), args.template.clone(), args.tags.clone().unwrap_or_default(), args.agent_id.clone()).await {
Ok(_) => json!({"success": true, "branch": branch_name, "status": "created_parallel", "base": base_branch, "current": current}),
Err(e) => json!({"success": false, "error": e.to_string()}),
}
} else {
match self.git_manager.checkout_branch(&branch_name).await {
Ok(_) => {
let mut bm = self.branch_manager.write().await;
match bm.register_branch_full(&branch_name, args.files.clone().unwrap_or_default(), args.description, args.depends_on.clone().unwrap_or_default(), args.template.clone(), args.tags.clone().unwrap_or_default(), args.agent_id.clone()).await {
Ok(_) => json!({"success": true, "branch": branch_name, "status": "started", "base": base_branch}),
Err(e) => json!({"success": false, "error": e.to_string()}),
}
}
Err(e) => json!({"success": false, "error": e.to_string()}),
}
}
}
Err(e) => json!({"success": false, "error": e.to_string()}),
}
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Save all current changes to the active operation branch")]
async fn save_changes(
&self,
Parameters(args): Parameters<SaveChangesArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let current = match self.git_manager.get_current_branch().await {
Ok(b) => b,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
};
let status = match self.git_manager.get_status().await {
Ok(s) => s,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
};
let files: Vec<String> = [status.untracked, status.modified, status.staged].concat();
if files.is_empty() {
return Ok(CallToolResult::success(vec![Content::text(json!({"success": true, "message": "No changes to save", "branch": current}).to_string())]));
}
let msg = if let Some(msg) = args.message {
msg
} else {
let summary = if files.len() == 1 {
files[0].clone()
} else if files.len() <= 4 {
files.join(", ")
} else {
format!("{} files", files.len())
};
let bm = self.branch_manager.read().await;
if let Some(branch) = bm.get_branch(¤t) {
if let Some(template_name) = &branch.template {
if let Some(tmpl) = self.codetree_config.get_template(template_name) {
tmpl.commit_message_format.replace("{description}", &summary)
} else {
format!("Save changes to {}", summary)
}
} else {
format!("Save changes to {}", summary)
}
} else {
format!("Save changes to {}", summary)
}
};
let should_validate = !args.no_validate.unwrap_or(false) && (args.validate.unwrap_or(false) || self.codetree_config.validation.is_required());
if should_validate {
if let Some(cmd) = &self.codetree_config.validation.command {
let output = match tokio::process::Command::new("sh")
.arg("-c")
.arg(cmd)
.output()
.await
{
Ok(o) => o,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": format!("Failed to run validation: {}", e)}).to_string())])),
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": format!("Validation failed: {}", stderr.trim())}).to_string())]));
}
} else if self.codetree_config.validation.is_required() || args.validate.unwrap_or(false) {
return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": "Validation requested but no command configured. Set [validation] command in config.toml."}).to_string())]));
}
}
let res = match self.git_manager.add_all().await {
Ok(_) => match self.git_manager.commit(&msg).await {
Ok(commit_hash) => {
let agent_id = {
let mut bm = self.branch_manager.write().await;
let _ = bm.update_branch_files(¤t, &files).await;
bm.get_branch(¤t).and_then(|b| b.agent_id.clone())
};
if let Ok(mut prov) = crate::provenance::ProvenanceLog::load(self.git_manager.repo_path()) {
prov.record(&commit_hash, ¤t, agent_id, args.prompt.clone());
let _ = prov.save(self.git_manager.repo_path());
}
json!({"success": true, "branch": current, "files": files.len(), "message": msg, "commit": commit_hash})
}
Err(e) => json!({"success": false, "error": e.to_string()}),
},
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Show provenance for a file or line: the commit, operation, agent, and prompt that produced it")]
async fn why(
&self,
Parameters(args): Parameters<WhyArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let prov = match crate::provenance::ProvenanceLog::load(self.git_manager.repo_path()) {
Ok(p) => p,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
};
let res = match crate::commands::why::lookup_why(&self.git_manager, &prov, &args.file).await {
Ok(info) => json!({
"success": true,
"file": info.file,
"line": info.line,
"commit": info.commit,
"timestamp": info.timestamp,
"message": info.message,
"operation": info.operation,
"agent_id": info.agent_id,
"prompt": info.prompt,
}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Create a labeled turn-level checkpoint as a rewind target. Recorded even on a clean tree; survives save")]
async fn checkpoint(
&self,
Parameters(args): Parameters<CheckpointArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::snapshot::create_checkpoint(&self.git_manager, args.label).await {
Ok((id, commit, branch, files)) => json!({
"success": true, "checkpoint_id": id, "commit": commit, "branch": branch, "files": files
}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Rewind the working tree to a checkpoint (HEAD/history untouched). dry_run previews changed files")]
async fn rewind(
&self,
Parameters(args): Parameters<RewindArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let dry_run = args.dry_run.unwrap_or(false);
let res = match crate::commands::snapshot::rewind_working_tree(&self.git_manager, args.id, dry_run).await {
Ok((commit, label, changed)) => json!({
"success": true, "checkpoint_id": args.id, "commit": commit, "label": label,
"dry_run": dry_run, "changed_files": changed
}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Combine divergent commits of an operation (e.g. two agents on one operation) into a single merge commit")]
async fn converge_op(
&self,
Parameters(args): Parameters<ConvergeOpArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let mut bm = self.branch_manager.write().await;
let res = match crate::commands::converge::converge_operations(
&self.git_manager,
&mut bm,
args.operation,
args.dry_run.unwrap_or(false),
).await {
Ok(report) => json!({
"success": true,
"dry_run": report.dry_run,
"operations": report.operations,
}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Merge all active operations into one working state (megamerge) so cross-operation conflicts surface before finish")]
async fn megamerge_op(
&self,
Parameters(args): Parameters<MegamergeOpArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let mut bm = self.branch_manager.write().await;
let res = match crate::commands::megamerge::megamerge_state(
&self.git_manager,
&mut bm,
args.abort.unwrap_or(false),
).await {
Ok(outcome) => json!({
"success": true,
"aborted": outcome.aborted,
"commit": outcome.commit,
"operations": outcome.operations,
"conflicts": outcome.conflicts,
}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Route working-tree changes back to the operations that own them (megamerge mode)")]
async fn route_op(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let mut bm = self.branch_manager.write().await;
let res = match crate::commands::megamerge::route_changes(&self.git_manager, &mut bm).await {
Ok(report) => json!({
"success": true,
"routed": report.routed,
"unrouted": report.unrouted,
"operations": report.operations,
}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Merge an operation branch back into the base branch")]
async fn merge_branch(
&self,
Parameters(args): Parameters<MergeBranchArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let target = match args.branch {
Some(b) => b,
None => match self.git_manager.get_current_branch().await {
Ok(b) => b,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
}
};
let base = &self.codetree_config.git.base_branch;
let res = match self.git_manager.checkout_branch(base).await {
Ok(_) => {
let cache_path = self.git_manager.repo_path()
.join(".codetree").join("resolutions.json");
let mut cache = match crate::resolution::ResolutionCache::load(&cache_path).await {
Ok(c) => c,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(
json!({"success": false, "error": e.to_string()}).to_string())])),
};
let merge_result = if self.codetree_config.merge.drivers.is_empty() {
if args.squash {
self.git_manager.squash_merge_branch_with_cache(&target, &mut cache).await
} else {
self.git_manager.merge_branch_with_cache(&target, &mut cache).await
}
} else {
let mut mgr = (*self.git_manager).clone();
mgr.set_merge_drivers(self.codetree_config.merge.drivers.clone());
if args.squash {
mgr.squash_merge_branch_with_cache(&target, &mut cache).await
} else {
mgr.merge_branch_with_cache(&target, &mut cache).await
}
};
match merge_result {
Ok(result) => {
if !result.driver_resolved.is_empty() {
let _ = cache.save(&cache_path).await;
}
if !result.resolved_from_cache && !result.conflicts.is_empty() {
let files: Vec<_> = result.conflicts.iter()
.map(|c| c.path.as_str()).collect();
json!({
"success": true,
"merged_branch": target,
"base_branch": base,
"squashed": args.squash,
"conflicts_pending": true,
"conflict_files": files,
"next_step": "resolve_op"
})
} else {
let resolved_from_cache = result.resolved_from_cache;
match self.git_manager.delete_branch(&target, false).await {
Ok(_) => {
let mut bm = self.branch_manager.write().await;
let _ = bm.mark_branch_merged(&target).await;
json!({"success": true, "merged_branch": target, "base_branch": base, "squashed": args.squash, "auto_resolved": resolved_from_cache})
}
Err(e) => json!({"success": false, "error": e.to_string()}),
}
}
}
Err(e) => json!({"success": false, "error": e.to_string()}),
}
}
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Resolve pending merge conflicts and finalize the merge. After merge_branch returns conflicts_pending, edit the files and call this to finish.")]
async fn resolve_op(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::merge::resolve_command().await {
Ok(()) => json!({"success": true, "message": "Conflicts resolved and merge finalized"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Finish an operation by merging it back to base and cleaning up")]
async fn finish_op(
&self,
Parameters(args): Parameters<FinishOpArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::finish_command(args.branch, None, false).await {
Ok(()) => json!({"success": true, "message": "Operation finished"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Withdraw an operation by fully reverting and removing it")]
async fn withdraw_op(
&self,
Parameters(args): Parameters<WithdrawOpArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::withdraw_command(Some(args.branch), None).await {
Ok(()) => json!({"success": true, "message": "Operation withdrawn"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Compare diffs across all active operations")]
async fn compare_ops(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::compare_command().await {
Ok(()) => json!({"success": true, "message": "Comparison displayed"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Rebase all active operation branches onto the base branch")]
async fn rebase_ops(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::rebase_command(false).await {
Ok(()) => json!({"success": true, "message": "All active branches rebased"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Get current status of all managed branches")]
async fn get_status(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let current = match self.git_manager.get_current_branch().await {
Ok(b) => b,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
};
let status = match self.git_manager.get_status().await {
Ok(s) => s,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
};
let branch_manager = self.branch_manager.read().await;
let branches = branch_manager.list_branches();
let active: Vec<serde_json::Value> = branches
.iter()
.filter(|b| matches!(b.status, BranchStatus::Active))
.map(|b| json!({"name": b.name, "description": b.change_group.description, "created_at": b.created_at, "files": b.change_group.files.len()}))
.collect();
let active_refs: Vec<_> = branches.iter()
.filter(|b| matches!(b.status, BranchStatus::Active))
.collect();
let mut conflicts = Vec::new();
if active_refs.len() >= 2 {
for i in 0..active_refs.len() {
for j in (i + 1)..active_refs.len() {
let files_i: std::collections::HashSet<&String> = active_refs[i].change_group.files.iter().collect();
let shared: Vec<&String> = active_refs[j].change_group.files.iter()
.filter(|f| files_i.contains(f))
.collect();
if !shared.is_empty() {
conflicts.push(json!({
"between": [active_refs[i].name, active_refs[j].name],
"files": shared
}));
}
}
}
}
let result = json!({
"success": true,
"current_branch": current,
"modified": status.modified.len(),
"untracked": status.untracked.len(),
"staged": status.staged.len(),
"active_operations": active.len(),
"operations": active,
"conflicts": conflicts
});
Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
}
#[tool(description = "List all managed branches")]
async fn list_branches(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let branch_manager = self.branch_manager.read().await;
let branches = branch_manager.list_branches();
let branch_data: Vec<serde_json::Value> = branches
.iter()
.map(|b| json!({
"name": b.name,
"status": b.status.as_str(),
"created_at": b.created_at,
"description": b.change_group.description,
"files": b.change_group.files.len()
}))
.collect();
let result = json!({
"success": true,
"branches": branch_data,
"total": branch_data.len()
});
Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
}
#[tool(description = "Undo an operation (last by default, or specify by index). Use index=null for last operation.")]
async fn undo_op(
&self,
Parameters(args): Parameters<UndoOpArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let is_list = args.list.unwrap_or(false);
let res = match crate::commands::undo_command(args.index, is_list).await {
Ok(()) if is_list => json!({"success": true, "message": "Operations listed"}),
Ok(()) => json!({"success": true, "message": "Operation undone"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Publish an operation branch as a GitHub PR. Pushes to remote and auto-creates PR if gh CLI is installed.")]
async fn publish_op(
&self,
Parameters(args): Parameters<PublishOpArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::publish_command(args.branch).await {
Ok(()) => json!({"success": true, "message": "PR published"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Freeze a file or directory so no operation can modify it")]
async fn freeze_path(
&self,
Parameters(args): Parameters<FreezePathArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::freeze_command(args.path).await {
Ok(()) => json!({"success": true, "message": "Path frozen"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Unfreeze a file or directory, allowing modifications again")]
async fn unfreeze_path(
&self,
Parameters(args): Parameters<UnfreezePathArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::unfreeze_command(args.path, args.force.unwrap_or(false)).await {
Ok(()) => json!({"success": true, "message": "Path unfrozen"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "List all frozen paths in the repository")]
async fn list_frozen(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::frozen_command().await {
Ok(()) => json!({"success": true, "message": "Frozen paths listed"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Manually release a file lock (e.g. if an agent crashed)")]
async fn unlock_file(
&self,
Parameters(args): Parameters<UnlockFileArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::unlock_command(args.path).await {
Ok(()) => json!({"success": true, "message": "File unlocked"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "List all active file locks and which operation holds them")]
async fn list_locks(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::locks_command().await {
Ok(()) => json!({"success": true, "message": "Locks listed"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Evaluate and compare candidate operations in a group")]
async fn evaluate_candidates(
&self,
Parameters(args): Parameters<EvaluateCandidatesArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::evaluate_command(args.group).await {
Ok(()) => json!({"success": true, "message": "Candidates evaluated"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Promote a candidate operation: merge the winner and withdraw all others in the group")]
async fn promote_candidate(
&self,
Parameters(args): Parameters<PromoteCandidateArgs>,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let res = match crate::commands::promote_command(args.group, args.operation).await {
Ok(()) => json!({"success": true, "message": "Candidate promoted"}),
Err(e) => json!({"success": false, "error": e.to_string()}),
};
Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
}
#[tool(description = "Show current position in the version tree: current branch, parent, base, divergence, siblings, children")]
async fn whereami(
&self,
_ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let current = match self.git_manager.get_current_branch().await {
Ok(b) => b,
Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
};
let base_branch = self.codetree_config.git.base_branch.clone();
let (ahead, behind) = self.git_manager.get_branch_divergence(¤t, &base_branch)
.unwrap_or((0, 0));
let bm = self.branch_manager.read().await;
let branch_info = bm.get_branch(¤t);
let parent = branch_info
.and_then(|b| b.parent_branch.clone())
.unwrap_or_else(|| {
let git_branch_names: Vec<String> = bm.list_branches()
.into_iter()
.filter(|b| matches!(b.status, crate::BranchStatus::Active) && !b.branchless)
.map(|b| b.name.clone())
.collect();
self.git_manager.get_branch_parent(¤t, &base_branch, &git_branch_names)
.unwrap_or_else(|_| base_branch.clone())
});
let siblings: Vec<String> = bm.list_branches()
.into_iter()
.filter(|b| {
matches!(b.status, crate::BranchStatus::Active)
&& !b.branchless
&& b.name != current
&& b.parent_branch.as_deref() == Some(&parent)
})
.map(|b| b.name.clone())
.collect();
let children: Vec<String> = bm.list_branches()
.into_iter()
.filter(|b| {
matches!(b.status, crate::BranchStatus::Active)
&& !b.branchless
&& b.parent_branch.as_deref() == Some(¤t)
})
.map(|b| b.name.clone())
.collect();
let result = json!({
"success": true,
"current_branch": current,
"base_branch": base_branch,
"parent_branch": parent,
"ahead": ahead,
"behind": behind,
"siblings": siblings,
"children": children,
"description": branch_info.map(|b| b.change_group.description.clone()),
"tags": branch_info.map(|b| b.tags.clone()).unwrap_or_default(),
"agent_id": branch_info.and_then(|b| b.agent_id.clone()),
});
Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
}
}
#[tool_handler]
impl ServerHandler for CodetreeServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(
ServerCapabilities::builder()
.enable_tools()
.enable_resources()
.build(),
)
.with_server_info(Implementation::from_build_env())
.with_protocol_version(ProtocolVersion::V_2024_11_05)
.with_instructions(
"CodeTree is an AI-native VCS for autonomous coding agents. Tools: init_repository, start_op, save_changes, finish_op, withdraw_op, compare_ops, rebase_ops, merge_branch, resolve_op, undo_op, publish_op, get_status, list_branches, freeze_path, unfreeze_path, list_frozen, unlock_file, list_locks, evaluate_candidates, promote_candidate, whereami, why, checkpoint, rewind, converge_op, megamerge_op, route_op".to_string(),
)
}
async fn list_resources(
&self,
_request: Option<PaginatedRequestParams>,
_ctx: RequestContext<RoleServer>,
) -> Result<ListResourcesResult, McpError> {
Ok(ListResourcesResult {
resources: vec![
self._create_resource_text("config://codetree", "Configuration"),
self._create_resource_text("status://branches", "Branch Status"),
self._create_resource_text("diff://current", "Current Diff"),
],
next_cursor: None,
meta: None,
})
}
async fn read_resource(
&self,
request: ReadResourceRequestParams,
_ctx: RequestContext<RoleServer>,
) -> Result<ReadResourceResult, McpError> {
match request.uri.as_str() {
"config://codetree" => {
let config = json!({
"git": {
"branch_prefix": self.codetree_config.git.branch_prefix,
"base_branch": self.codetree_config.git.base_branch,
"auto_push": self.codetree_config.git.auto_push,
"remote_name": self.codetree_config.git.remote_name
}
});
Ok(ReadResourceResult::new(vec![ResourceContents::text(config.to_string(), request.uri.clone())]))
}
"status://branches" => {
let branch_manager = self.branch_manager.read().await;
let branches = branch_manager.list_branches();
let (total, active, merged, archived) = branches.iter().fold(
(0, 0, 0, 0),
|(total, active, merged, archived), b| {
(
total + 1,
active + if matches!(b.status, BranchStatus::Active) { 1 } else { 0 },
merged + if matches!(b.status, BranchStatus::Merged) { 1 } else { 0 },
archived + if matches!(b.status, BranchStatus::Archived) { 1 } else { 0 },
)
},
);
let status = json!({"total": total, "active": active, "merged": merged, "archived": archived});
Ok(ReadResourceResult::new(vec![ResourceContents::text(status.to_string(), request.uri.clone())]))
}
"diff://current" => {
match self.git_manager.get_diff() {
Ok(diff) => {
let content = if diff.is_empty() {
"No changes in working tree.".to_string()
} else {
diff
};
Ok(ReadResourceResult::new(vec![ResourceContents::text(content, request.uri.clone())]))
}
Err(e) => Ok(ReadResourceResult::new(vec![ResourceContents::text(format!("Error reading diff: {}", e), request.uri.clone())])),
}
}
_ => Err(McpError::resource_not_found(
"resource_not_found",
Some(json!({"uri": request.uri})),
)),
}
}
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct InitRepositoryArgs {
#[schemars(description = "Force reinitialization if already initialized")]
#[serde(default = "default_force")]
pub force: bool,
}
fn default_force() -> bool {
false
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct StartOpArgs {
#[schemars(description = "Description for the mini-operation (used in branch name)")]
pub description: String,
#[schemars(description = "Create branch without checking out (parallel operation)")]
#[serde(default = "default_parallel")]
pub parallel: bool,
#[schemars(description = "Create a git worktree for the operation (implies parallel)")]
#[serde(default = "default_worktree")]
pub worktree: bool,
#[schemars(description = "Branchless mode: track as bookmark without creating a git branch")]
#[serde(default = "default_branchless")]
pub branchless: bool,
#[schemars(description = "Files assigned to this operation (pre-declares scope)")]
#[serde(default)]
pub files: Option<Vec<String>>,
#[schemars(description = "Operations this one depends on (must finish first)")]
#[serde(default)]
pub depends_on: Option<Vec<String>>,
#[schemars(description = "Operation template (refactor, bugfix, feature)")]
pub template: Option<String>,
#[schemars(description = "Tags for grouping operations (e.g., sprint-42, bugfix-week)")]
#[serde(default)]
pub tags: Option<Vec<String>>,
#[schemars(description = "Agent identifier for multi-agent tracking")]
#[serde(default)]
pub agent_id: Option<String>,
}
fn default_branchless() -> bool {
false
}
fn default_worktree() -> bool {
false
}
fn default_parallel() -> bool {
false
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct SaveChangesArgs {
#[schemars(description = "Optional commit message")]
pub message: Option<String>,
#[schemars(description = "Run validation command before committing")]
pub validate: Option<bool>,
#[schemars(description = "Skip validation even if config requires it")]
pub no_validate: Option<bool>,
#[schemars(description = "Prompt/intent that produced this change (recorded as provenance, queried via the why tool)")]
pub prompt: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct WhyArgs {
#[schemars(description = "File to explain (`path` or `path:line`, 1-based line)")]
pub file: String,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct CheckpointArgs {
#[schemars(description = "Label for the checkpoint (e.g. the prompt or intent of this turn)")]
pub label: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct RewindArgs {
#[schemars(description = "Checkpoint id to rewind to (from the checkpoint tool or `snapshots`)")]
pub id: usize,
#[schemars(description = "Preview changed files without touching the working tree")]
pub dry_run: Option<bool>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct ConvergeOpArgs {
#[schemars(description = "Operation to converge (default: every operation with divergence)")]
pub operation: Option<String>,
#[schemars(description = "Preview divergent heads without converging")]
pub dry_run: Option<bool>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct MegamergeOpArgs {
#[schemars(description = "Discard the megamerge and restore the base branch")]
pub abort: Option<bool>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct MergeBranchArgs {
#[schemars(description = "Branch to merge (defaults to current)")]
pub branch: Option<String>,
#[schemars(description = "Combine all feature-branch commits into a single commit")]
#[serde(default = "default_squash")]
pub squash: bool,
}
fn default_squash() -> bool {
false
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct FinishOpArgs {
#[schemars(description = "Branch to finish (defaults to current)")]
pub branch: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct WithdrawOpArgs {
#[schemars(description = "Branch or bookmark to fully revert")]
pub branch: String,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct UndoOpArgs {
#[schemars(description = "Operation index to undo (omit for most recent)")]
#[serde(default)]
pub index: Option<usize>,
#[schemars(description = "List all undoable operations with indices")]
#[serde(default)]
pub list: Option<bool>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct PublishOpArgs {
#[schemars(description = "Branch to publish (defaults to current)")]
pub branch: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct FreezePathArgs {
#[schemars(description = "Path to freeze (file or directory)")]
pub path: String,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct UnfreezePathArgs {
#[schemars(description = "Path to unfreeze")]
pub path: String,
#[schemars(description = "Skip confirmation prompt")]
#[serde(default)]
pub force: Option<bool>,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct UnlockFileArgs {
#[schemars(description = "Path to unlock")]
pub path: String,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct EvaluateCandidatesArgs {
#[schemars(description = "Candidate group name to evaluate")]
pub group: String,
}
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct PromoteCandidateArgs {
#[schemars(description = "Candidate group name")]
pub group: String,
#[schemars(description = "Operation name to promote as the winner")]
pub operation: String,
}
#[cfg(test)]
mod tests {
#[test]
fn test_codetree_server_creation() {
}
}