Skip to main content

poly_mcp/modules/
git.rs

1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use git2::{Repository, StatusOptions, DiffOptions, BranchType, ObjectType};
4use std::collections::HashMap;
5use std::path::Path;
6
7pub struct GitModule;
8
9impl Default for GitModule {
10    fn default() -> Self {
11        Self::new()
12    }
13}
14
15impl GitModule {
16    pub fn new() -> Self {
17        Self
18    }
19
20    pub fn get_tools(&self) -> Vec<Value> {
21        vec![
22            json!({
23                "name": "git_status",
24                "description": "Get git repository status",
25                "inputSchema": {
26                    "type": "object",
27                    "properties": {
28                        "path": {
29                            "type": "string",
30                            "description": "Path to git repository (default: current directory)"
31                        }
32                    }
33                }
34            }),
35            json!({
36                "name": "git_diff",
37                "description": "Get diff of changes in repository",
38                "inputSchema": {
39                    "type": "object",
40                    "properties": {
41                        "path": {
42                            "type": "string",
43                            "description": "Path to git repository (default: current directory)"
44                        },
45                        "staged": {
46                            "type": "boolean",
47                            "description": "Show staged changes only (default: false)"
48                        },
49                        "file": {
50                            "type": "string",
51                            "description": "Specific file to diff"
52                        }
53                    }
54                }
55            }),
56            json!({
57                "name": "git_commit",
58                "description": "Create a git commit",
59                "inputSchema": {
60                    "type": "object",
61                    "properties": {
62                        "path": {
63                            "type": "string",
64                            "description": "Path to git repository (default: current directory)"
65                        },
66                        "message": {
67                            "type": "string",
68                            "description": "Commit message"
69                        },
70                        "author_name": {
71                            "type": "string",
72                            "description": "Author name"
73                        },
74                        "author_email": {
75                            "type": "string",
76                            "description": "Author email"
77                        }
78                    },
79                    "required": ["message"]
80                }
81            }),
82            json!({
83                "name": "git_branch",
84                "description": "List, create, or delete branches",
85                "inputSchema": {
86                    "type": "object",
87                    "properties": {
88                        "path": {
89                            "type": "string",
90                            "description": "Path to git repository (default: current directory)"
91                        },
92                        "action": {
93                            "type": "string",
94                            "enum": ["list", "create", "delete"],
95                            "description": "Action to perform (default: list)"
96                        },
97                        "name": {
98                            "type": "string",
99                            "description": "Branch name (for create/delete)"
100                        }
101                    }
102                }
103            }),
104            json!({
105                "name": "git_checkout",
106                "description": "Checkout a branch or commit",
107                "inputSchema": {
108                    "type": "object",
109                    "properties": {
110                        "path": {
111                            "type": "string",
112                            "description": "Path to git repository (default: current directory)"
113                        },
114                        "target": {
115                            "type": "string",
116                            "description": "Branch name or commit hash to checkout"
117                        },
118                        "create": {
119                            "type": "boolean",
120                            "description": "Create branch if it doesn't exist (default: false)"
121                        }
122                    },
123                    "required": ["target"]
124                }
125            }),
126            json!({
127                "name": "git_blame",
128                "description": "Show what revision and author last modified each line of a file",
129                "inputSchema": {
130                    "type": "object",
131                    "properties": {
132                        "path": {
133                            "type": "string",
134                            "description": "Path to git repository (default: current directory)"
135                        },
136                        "file": {
137                            "type": "string",
138                            "description": "File to blame"
139                        }
140                    },
141                    "required": ["file"]
142                }
143            }),
144            json!({
145                "name": "git_log",
146                "description": "Show commit logs",
147                "inputSchema": {
148                    "type": "object",
149                    "properties": {
150                        "path": {
151                            "type": "string",
152                            "description": "Path to git repository (default: current directory)"
153                        },
154                        "limit": {
155                            "type": "number",
156                            "description": "Number of commits to show (default: 10)"
157                        },
158                        "file": {
159                            "type": "string",
160                            "description": "Show commits for specific file"
161                        }
162                    }
163                }
164            }),
165            json!({
166                "name": "git_tag",
167                "description": "List, create, or delete tags",
168                "inputSchema": {
169                    "type": "object",
170                    "properties": {
171                        "path": {
172                            "type": "string",
173                            "description": "Path to git repository (default: current directory)"
174                        },
175                        "action": {
176                            "type": "string",
177                            "enum": ["list", "create", "delete"],
178                            "description": "Action to perform (default: list)"
179                        },
180                        "name": {
181                            "type": "string",
182                            "description": "Tag name (for create/delete)"
183                        },
184                        "message": {
185                            "type": "string",
186                            "description": "Tag message (for annotated tags)"
187                        }
188                    }
189                }
190            }),
191        ]
192    }
193
194    pub async fn status(&self, args: Value) -> Result<Value> {
195        let path = args["path"].as_str().unwrap_or(".");
196        let repo = Repository::open(path)?;
197
198        let mut opts = StatusOptions::new();
199        opts.include_untracked(true);
200        let statuses = repo.statuses(Some(&mut opts))?;
201
202        let mut staged = Vec::new();
203        let mut unstaged = Vec::new();
204        let mut untracked = Vec::new();
205
206        for entry in statuses.iter() {
207            let path = entry.path().unwrap_or("");
208            let status = entry.status();
209
210            if status.is_index_new() || status.is_index_modified() || status.is_index_deleted() {
211                staged.push(json!({
212                    "path": path,
213                    "status": format!("{:?}", status)
214                }));
215            }
216
217            if status.is_wt_modified() || status.is_wt_deleted() {
218                unstaged.push(json!({
219                    "path": path,
220                    "status": format!("{:?}", status)
221                }));
222            }
223
224            if status.is_wt_new() {
225                untracked.push(json!({ "path": path }));
226            }
227        }
228
229        // Get current branch
230        let head = repo.head()?;
231        let branch_name = head.shorthand().unwrap_or("HEAD");
232
233        Ok(json!({
234            "staged": staged,
235            "unstaged": unstaged,
236            "untracked": untracked,
237            "branch": branch_name,
238            "is_detached": !head.is_branch()
239        }))
240    }
241
242    pub async fn diff(&self, args: Value) -> Result<Value> {
243        let path = args["path"].as_str().unwrap_or(".");
244        let staged = args["staged"].as_bool().unwrap_or(false);
245        let file_filter = args["file"].as_str();
246
247        let repo = Repository::open(path)?;
248
249        let mut diff_opts = DiffOptions::new();
250        if let Some(file) = file_filter {
251            diff_opts.pathspec(file);
252        }
253
254        let diff = if staged {
255            // Diff between HEAD and index (staged changes)
256            let head = repo.head()?.peel_to_tree()?;
257            let _index = repo.index()?;
258            let index_tree = repo.find_tree(repo.index()?.write_tree()?)?;
259            repo.diff_tree_to_tree(Some(&head), Some(&index_tree), Some(&mut diff_opts))?
260        } else {
261            // Diff between index and working directory (unstaged changes)
262            repo.diff_index_to_workdir(None, Some(&mut diff_opts))?
263        };
264
265        // Build a single patch string instead of per-line JSON objects
266        let mut patch_text = String::with_capacity(4096);
267
268        diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
269            patch_text.push(line.origin());
270            let content = String::from_utf8_lossy(line.content());
271            patch_text.push_str(&content);
272            true
273        })?;
274
275        let stats = diff.stats()?;
276
277        Ok(json!({
278            "staged": staged,
279            "files_changed": stats.files_changed(),
280            "insertions": stats.insertions(),
281            "deletions": stats.deletions(),
282            "patch": patch_text
283        }))
284    }
285
286    pub async fn commit(&self, args: Value) -> Result<Value> {
287        let path = args["path"].as_str().unwrap_or(".");
288        let message = args["message"].as_str().context("Missing 'message' parameter")?;
289
290        let repo = Repository::open(path)?;
291
292        // Get signature
293        let signature = if let (Some(name), Some(email)) = (args["author_name"].as_str(), args["author_email"].as_str()) {
294            git2::Signature::now(name, email)?
295        } else {
296            repo.signature()?
297        };
298
299        // Get current index
300        let mut index = repo.index()?;
301        let tree_id = index.write_tree()?;
302        let tree = repo.find_tree(tree_id)?;
303
304        // Get parent commit
305        let parent_commit = repo.head()?.peel_to_commit()?;
306
307        // Create commit
308        let commit_id = repo.commit(
309            Some("HEAD"),
310            &signature,
311            &signature,
312            message,
313            &tree,
314            &[&parent_commit],
315        )?;
316
317        Ok(json!({
318            "success": true,
319            "commit_id": commit_id.to_string(),
320            "message": message,
321            "author": signature.name().unwrap_or(""),
322            "email": signature.email().unwrap_or("")
323        }))
324    }
325
326    pub async fn branch(&self, args: Value) -> Result<Value> {
327        let path = args["path"].as_str().unwrap_or(".");
328        let action = args["action"].as_str().unwrap_or("list");
329
330        let repo = Repository::open(path)?;
331
332        match action {
333            "list" => {
334                let mut branches = Vec::new();
335
336                for branch in repo.branches(None)? {
337                    let (branch, _) = branch?;
338                    let name = branch.name()?.unwrap_or("");
339                    let is_head = branch.is_head();
340
341                    branches.push(json!({
342                        "name": name,
343                        "is_current": is_head
344                    }));
345                }
346
347                Ok(json!({
348                    "branches": branches,
349                    "count": branches.len()
350                }))
351            }
352            "create" => {
353                let name = args["name"].as_str().context("Missing 'name' parameter")?;
354                let head = repo.head()?;
355                let commit = head.peel_to_commit()?;
356
357                repo.branch(name, &commit, false)?;
358
359                Ok(json!({
360                    "success": true,
361                    "branch": name,
362                    "action": "created"
363                }))
364            }
365            "delete" => {
366                let name = args["name"].as_str().context("Missing 'name' parameter")?;
367                let mut branch = repo.find_branch(name, BranchType::Local)?;
368
369                branch.delete()?;
370
371                Ok(json!({
372                    "success": true,
373                    "branch": name,
374                    "action": "deleted"
375                }))
376            }
377            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
378        }
379    }
380
381    pub async fn checkout(&self, args: Value) -> Result<Value> {
382        let path = args["path"].as_str().unwrap_or(".");
383        let target = args["target"].as_str().context("Missing 'target' parameter")?;
384        let create = args["create"].as_bool().unwrap_or(false);
385
386        let repo = Repository::open(path)?;
387
388        // Try to find existing branch
389        let branch_exists = repo.find_branch(target, BranchType::Local).is_ok();
390
391        if !branch_exists && create {
392            // Create new branch
393            let head = repo.head()?;
394            let commit = head.peel_to_commit()?;
395            repo.branch(target, &commit, false)?;
396        }
397
398        // Checkout the branch
399        let obj = repo.revparse_single(target)?;
400
401        repo.checkout_tree(&obj, None)?;
402        repo.set_head(&format!("refs/heads/{}", target))?;
403
404        Ok(json!({
405            "success": true,
406            "target": target,
407            "created": !branch_exists && create
408        }))
409    }
410
411    pub async fn blame(&self, args: Value) -> Result<Value> {
412        let path = args["path"].as_str().unwrap_or(".");
413        let file = args["file"].as_str().context("Missing 'file' parameter")?;
414
415        let repo = Repository::open(path)?;
416        let blame = repo.blame_file(Path::new(file), None)?;
417
418        let mut lines = Vec::new();
419        // Cache commit lookups — many hunks share the same commit
420        let mut commit_cache: HashMap<git2::Oid, (String, String, i64, String)> = HashMap::new();
421
422        for hunk in blame.iter() {
423            let oid = hunk.final_commit_id();
424            let (author, email, timestamp, message) = match commit_cache.get(&oid) {
425                Some(cached) => cached.clone(),
426                None => {
427                    let commit = repo.find_commit(oid)?;
428                    let entry = (
429                        commit.author().name().unwrap_or("").to_string(),
430                        commit.author().email().unwrap_or("").to_string(),
431                        commit.time().seconds(),
432                        commit.summary().unwrap_or("").to_string(),
433                    );
434                    commit_cache.insert(oid, entry.clone());
435                    entry
436                }
437            };
438
439            lines.push(json!({
440                "line_start": hunk.final_start_line(),
441                "line_count": hunk.lines_in_hunk(),
442                "commit": oid.to_string(),
443                "author": author,
444                "email": email,
445                "timestamp": timestamp,
446                "message": message
447            }));
448        }
449
450        Ok(json!({
451            "file": file,
452            "lines": lines,
453            "total_hunks": lines.len()
454        }))
455    }
456
457    pub async fn log(&self, args: Value) -> Result<Value> {
458        let path = args["path"].as_str().unwrap_or(".");
459        let limit = args["limit"].as_u64().unwrap_or(10) as usize;
460        let file_filter = args["file"].as_str();
461
462        let repo = Repository::open(path)?;
463
464        let mut revwalk = repo.revwalk()?;
465        revwalk.push_head()?;
466
467        let mut commits = Vec::new();
468        let walk_limit = if file_filter.is_some() { limit * 20 } else { limit };
469
470        for oid in revwalk {
471            if commits.len() >= limit {
472                break;
473            }
474
475            let oid = oid?;
476            let commit = repo.find_commit(oid)?;
477
478            // If file filter is specified, check if commit affects the file
479            if let Some(file) = file_filter {
480                let tree = commit.tree()?;
481                if tree.get_path(Path::new(file)).is_err() {
482                    continue;
483                }
484            }
485
486            let id_str = oid.to_string();
487            let short_id = &id_str[..7.min(id_str.len())];
488
489            commits.push(json!({
490                "id": id_str,
491                "short_id": short_id,
492                "author": commit.author().name().unwrap_or(""),
493                "email": commit.author().email().unwrap_or(""),
494                "timestamp": commit.time().seconds(),
495                "message": commit.message().unwrap_or(""),
496                "summary": commit.summary().unwrap_or("")
497            }));
498
499            if commits.len() >= walk_limit {
500                break;
501            }
502        }
503
504        Ok(json!({
505            "commits": commits,
506            "count": commits.len(),
507            "limit": limit
508        }))
509    }
510
511    pub async fn tag(&self, args: Value) -> Result<Value> {
512        let path = args["path"].as_str().unwrap_or(".");
513        let action = args["action"].as_str().unwrap_or("list");
514
515        let repo = Repository::open(path)?;
516
517        match action {
518            "list" => {
519                let mut tags = Vec::new();
520
521                for tag_name in repo.tag_names(None)?.iter().flatten() {
522                    tags.push(json!({
523                        "name": tag_name
524                    }));
525                }
526
527                Ok(json!({
528                    "tags": tags,
529                    "count": tags.len()
530                }))
531            }
532            "create" => {
533                let name = args["name"].as_str().context("Missing 'name' parameter")?;
534                let message = args["message"].as_str();
535
536                let head = repo.head()?;
537                let target = head.peel(ObjectType::Commit)?;
538
539                if let Some(msg) = message {
540                    // Create annotated tag
541                    let sig = repo.signature()?;
542                    repo.tag(name, &target, &sig, msg, false)?;
543                } else {
544                    // Create lightweight tag
545                    repo.tag_lightweight(name, &target, false)?;
546                }
547
548                Ok(json!({
549                    "success": true,
550                    "tag": name,
551                    "action": "created",
552                    "annotated": message.is_some()
553                }))
554            }
555            "delete" => {
556                let name = args["name"].as_str().context("Missing 'name' parameter")?;
557                repo.tag_delete(name)?;
558
559                Ok(json!({
560                    "success": true,
561                    "tag": name,
562                    "action": "deleted"
563                }))
564            }
565            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
566        }
567    }
568}