mcp-server-git 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: mcp-server-git
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: A Model Context Protocol server providing tools to read, search, and manipulate Git repositories programmatically via LLMs
5
5
  Author: Anthropic, PBC.
6
6
  Maintainer-email: David Soria Parra <davidsp@anthropic.com>
@@ -20,6 +20,8 @@ Description-Content-Type: text/markdown
20
20
 
21
21
  # mcp-server-git: A git MCP server
22
22
 
23
+ ## Overview
24
+
23
25
  A Model Context Protocol server for Git repository interaction and automation. This server provides tools to read, search, and manipulate Git repositories via Large Language Models.
24
26
 
25
27
  Please note that mcp-server-git is currently in early development. The functionality and available tools are subject to change and expansion as we continue to develop and improve the server.
@@ -28,17 +30,13 @@ Please note that mcp-server-git is currently in early development. The functiona
28
30
 
29
31
  The current list of tools includes:
30
32
 
31
- - `git_read_file`: Read contents of a file at a specific Git reference
32
- - `git_list_files`: List all files in a repository or subdirectory
33
- - `git_file_history`: Get commit history for a specific file
34
- - `git_commit`: Create Git commits with messages and specified files
35
- - `git_search_code`: Search repository content with pattern matching
36
- - `git_get_diff`: View diffs between Git references
37
- - `git_get_repo_structure`: View repository file structure
38
- - `git_list_repos`: List available Git repositories
39
- - `git_log`: Retrieve commit log for the repository
40
- - `git_list_branches`: List all branches in the repository
41
- - `git_list_tags`: List all tags in the repository
33
+ - `git_status`: Shows the working tree status
34
+ - `git_diff_unstaged`: Shows changes in the working directory that are not yet staged
35
+ - `git_diff_staged`: Shows changes that are staged for commit
36
+ - `git_commit`: Records changes to the repository
37
+ - `git_add`: Adds file contents to the staging area
38
+ - `git_reset`: Unstages all staged changes
39
+ - `git_log`: Shows the commit logs
42
40
 
43
41
  This list is expected to grow as we add more functionality to the server. We welcome contributions from the community to expand and enhance the available tools.
44
42
 
@@ -64,10 +62,14 @@ python -m mcp_server_git
64
62
  ```
65
63
 
66
64
  ## Configuration
65
+
67
66
  ### Configure for Claude.app
68
67
 
69
68
  Add to your Claude settings:
70
69
 
70
+ <details>
71
+ <summary>Using uvx</summary>
72
+
71
73
  ```json
72
74
  "mcpServers": {
73
75
  "git": {
@@ -76,8 +78,10 @@ Add to your Claude settings:
76
78
  }
77
79
  }
78
80
  ```
81
+ </details>
79
82
 
80
- Alternatively, if using pip installation:
83
+ <details>
84
+ <summary>Using pip installation</summary>
81
85
 
82
86
  ```json
83
87
  "mcpServers": {
@@ -87,11 +91,15 @@ Alternatively, if using pip installation:
87
91
  }
88
92
  }
89
93
  ```
94
+ </details>
90
95
 
91
96
  ### Configure for Zed
92
97
 
93
98
  Add to your Zed settings.json:
94
99
 
100
+ <details>
101
+ <summary>Using uvx</summary>
102
+
95
103
  ```json
96
104
  "context_servers": [
97
105
  "mcp-server-git": {
@@ -100,18 +108,35 @@ Add to your Zed settings.json:
100
108
  }
101
109
  ],
102
110
  ```
111
+ </details>
103
112
 
104
- Alternatively, if using pip installation:
113
+ <details>
114
+ <summary>Using pip installation</summary>
105
115
 
106
116
  ```json
107
117
  "context_servers": {
108
118
  "mcp-server-git": {
109
119
  "command": "python",
110
- "args": ["-m", "mcp-server-git"]
120
+ "args": ["-m", "mcp_server_git"]
111
121
  }
112
122
  },
113
123
  ```
124
+ </details>
125
+
126
+ ## Debugging
127
+
128
+ You can use the MCP inspector to debug the server. For uvx installations:
129
+
130
+ ```
131
+ npx @modelcontextprotocol/inspector uvx mcp-server-git
132
+ ```
114
133
 
134
+ Or if you've installed the package in a specific directory or are developing on it:
135
+
136
+ ```
137
+ cd path/to/servers/src/git
138
+ npx @modelcontextprotocol/inspector uv run mcp-server-git
139
+ ```
115
140
 
116
141
  ## Contributing
117
142
 
@@ -121,3 +146,7 @@ For examples of other MCP servers and implementation patterns, see:
121
146
  https://github.com/modelcontextprotocol/servers
122
147
 
123
148
  Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-server-git even more powerful and useful.
149
+
150
+ ## License
151
+
152
+ mcp-server-git is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.
@@ -1,5 +1,7 @@
1
1
  # mcp-server-git: A git MCP server
2
2
 
3
+ ## Overview
4
+
3
5
  A Model Context Protocol server for Git repository interaction and automation. This server provides tools to read, search, and manipulate Git repositories via Large Language Models.
4
6
 
5
7
  Please note that mcp-server-git is currently in early development. The functionality and available tools are subject to change and expansion as we continue to develop and improve the server.
@@ -8,17 +10,13 @@ Please note that mcp-server-git is currently in early development. The functiona
8
10
 
9
11
  The current list of tools includes:
10
12
 
11
- - `git_read_file`: Read contents of a file at a specific Git reference
12
- - `git_list_files`: List all files in a repository or subdirectory
13
- - `git_file_history`: Get commit history for a specific file
14
- - `git_commit`: Create Git commits with messages and specified files
15
- - `git_search_code`: Search repository content with pattern matching
16
- - `git_get_diff`: View diffs between Git references
17
- - `git_get_repo_structure`: View repository file structure
18
- - `git_list_repos`: List available Git repositories
19
- - `git_log`: Retrieve commit log for the repository
20
- - `git_list_branches`: List all branches in the repository
21
- - `git_list_tags`: List all tags in the repository
13
+ - `git_status`: Shows the working tree status
14
+ - `git_diff_unstaged`: Shows changes in the working directory that are not yet staged
15
+ - `git_diff_staged`: Shows changes that are staged for commit
16
+ - `git_commit`: Records changes to the repository
17
+ - `git_add`: Adds file contents to the staging area
18
+ - `git_reset`: Unstages all staged changes
19
+ - `git_log`: Shows the commit logs
22
20
 
23
21
  This list is expected to grow as we add more functionality to the server. We welcome contributions from the community to expand and enhance the available tools.
24
22
 
@@ -44,10 +42,14 @@ python -m mcp_server_git
44
42
  ```
45
43
 
46
44
  ## Configuration
45
+
47
46
  ### Configure for Claude.app
48
47
 
49
48
  Add to your Claude settings:
50
49
 
50
+ <details>
51
+ <summary>Using uvx</summary>
52
+
51
53
  ```json
52
54
  "mcpServers": {
53
55
  "git": {
@@ -56,8 +58,10 @@ Add to your Claude settings:
56
58
  }
57
59
  }
58
60
  ```
61
+ </details>
59
62
 
60
- Alternatively, if using pip installation:
63
+ <details>
64
+ <summary>Using pip installation</summary>
61
65
 
62
66
  ```json
63
67
  "mcpServers": {
@@ -67,11 +71,15 @@ Alternatively, if using pip installation:
67
71
  }
68
72
  }
69
73
  ```
74
+ </details>
70
75
 
71
76
  ### Configure for Zed
72
77
 
73
78
  Add to your Zed settings.json:
74
79
 
80
+ <details>
81
+ <summary>Using uvx</summary>
82
+
75
83
  ```json
76
84
  "context_servers": [
77
85
  "mcp-server-git": {
@@ -80,18 +88,35 @@ Add to your Zed settings.json:
80
88
  }
81
89
  ],
82
90
  ```
91
+ </details>
83
92
 
84
- Alternatively, if using pip installation:
93
+ <details>
94
+ <summary>Using pip installation</summary>
85
95
 
86
96
  ```json
87
97
  "context_servers": {
88
98
  "mcp-server-git": {
89
99
  "command": "python",
90
- "args": ["-m", "mcp-server-git"]
100
+ "args": ["-m", "mcp_server_git"]
91
101
  }
92
102
  },
93
103
  ```
104
+ </details>
105
+
106
+ ## Debugging
107
+
108
+ You can use the MCP inspector to debug the server. For uvx installations:
109
+
110
+ ```
111
+ npx @modelcontextprotocol/inspector uvx mcp-server-git
112
+ ```
94
113
 
114
+ Or if you've installed the package in a specific directory or are developing on it:
115
+
116
+ ```
117
+ cd path/to/servers/src/git
118
+ npx @modelcontextprotocol/inspector uv run mcp-server-git
119
+ ```
95
120
 
96
121
  ## Contributing
97
122
 
@@ -101,3 +126,7 @@ For examples of other MCP servers and implementation patterns, see:
101
126
  https://github.com/modelcontextprotocol/servers
102
127
 
103
128
  Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-server-git even more powerful and useful.
129
+
130
+ ## License
131
+
132
+ mcp-server-git is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.
@@ -1,6 +1,6 @@
1
1
  [project]
2
- name = "mcp-server-git"
3
- version = "0.3.0"
2
+ name="mcp-server-git"
3
+ version = "0.4.0"
4
4
  description = "A Model Context Protocol server providing tools to read, search, and manipulate Git repositories programmatically via LLMs"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -0,0 +1,25 @@
1
+ import click
2
+ from functools import partial
3
+ from pathlib import Path
4
+ import logging
5
+ import sys
6
+ from .server import serve
7
+
8
+ @click.command()
9
+ @click.option("--repository", "-r", type=Path, help="Git repository path")
10
+ @click.option("-v", "--verbose", count=True)
11
+ def main(repository: Path | None, verbose: bool) -> None:
12
+ """MCP Git Server - Git functionality for MCP"""
13
+ import asyncio
14
+
15
+ logging_level = logging.WARN
16
+ if verbose == 1:
17
+ logging_level = logging.INFO
18
+ elif verbose >= 2:
19
+ logging_level = logging.DEBUG
20
+
21
+ logging.basicConfig(level=logging_level, stream=sys.stderr)
22
+ asyncio.run(serve(repository))
23
+
24
+ if __name__ == "__main__":
25
+ main()
@@ -0,0 +1,228 @@
1
+ import logging
2
+ import json
3
+ from pathlib import Path
4
+ from typing import Sequence
5
+ from mcp.server import Server
6
+ from mcp.server.session import ServerSession
7
+ from mcp.server.stdio import stdio_server
8
+ from mcp.types import (
9
+ ClientCapabilities,
10
+ TextContent,
11
+ Tool,
12
+ ListRootsResult,
13
+ RootsCapability,
14
+ )
15
+ from enum import Enum
16
+ import git
17
+ from pydantic import BaseModel, Field
18
+ from typing import List, Optional
19
+
20
+ class GitStatus(BaseModel):
21
+ repo_path: str
22
+
23
+ class GitDiffUnstaged(BaseModel):
24
+ repo_path: str
25
+
26
+ class GitDiffStaged(BaseModel):
27
+ repo_path: str
28
+
29
+ class GitCommit(BaseModel):
30
+ repo_path: str
31
+ message: str
32
+
33
+ class GitAdd(BaseModel):
34
+ repo_path: str
35
+ files: List[str]
36
+
37
+ class GitReset(BaseModel):
38
+ repo_path: str
39
+
40
+ class GitLog(BaseModel):
41
+ repo_path: str
42
+ max_count: int = 10
43
+
44
+ class GitTools(str, Enum):
45
+ STATUS = "git_status"
46
+ DIFF_UNSTAGED = "git_diff_unstaged"
47
+ DIFF_STAGED = "git_diff_staged"
48
+ COMMIT = "git_commit"
49
+ ADD = "git_add"
50
+ RESET = "git_reset"
51
+ LOG = "git_log"
52
+
53
+ def git_status(repo: git.Repo) -> str:
54
+ return repo.git.status()
55
+
56
+ def git_diff_unstaged(repo: git.Repo) -> str:
57
+ return repo.git.diff()
58
+
59
+ def git_diff_staged(repo: git.Repo) -> str:
60
+ return repo.git.diff("--cached")
61
+
62
+ def git_commit(repo: git.Repo, message: str) -> str:
63
+ commit = repo.index.commit(message)
64
+ return f"Changes committed successfully with hash {commit.hexsha}"
65
+
66
+ def git_add(repo: git.Repo, files: list[str]) -> str:
67
+ repo.index.add(files)
68
+ return "Files staged successfully"
69
+
70
+ def git_reset(repo: git.Repo) -> str:
71
+ repo.index.reset()
72
+ return "All staged changes reset"
73
+
74
+ def git_log(repo: git.Repo, max_count: int = 10) -> list[str]:
75
+ commits = list(repo.iter_commits(max_count=max_count))
76
+ log = []
77
+ for commit in commits:
78
+ log.append(
79
+ f"Commit: {commit.hexsha}\n"
80
+ f"Author: {commit.author}\n"
81
+ f"Date: {commit.authored_datetime}\n"
82
+ f"Message: {commit.message}\n"
83
+ )
84
+ return log
85
+
86
+ async def serve(repository: Path | None) -> None:
87
+ logger = logging.getLogger(__name__)
88
+
89
+ if repository is not None:
90
+ try:
91
+ git.Repo(repository)
92
+ logger.info(f"Using repository at {repository}")
93
+ except git.InvalidGitRepositoryError:
94
+ logger.error(f"{repository} is not a valid Git repository")
95
+ return
96
+
97
+ server = Server("mcp-git")
98
+
99
+ @server.list_tools()
100
+ async def list_tools() -> list[Tool]:
101
+ return [
102
+ Tool(
103
+ name=GitTools.STATUS,
104
+ description="Shows the working tree status",
105
+ inputSchema=GitStatus.schema(),
106
+ ),
107
+ Tool(
108
+ name=GitTools.DIFF_UNSTAGED,
109
+ description="Shows changes in the working directory that are not yet staged",
110
+ inputSchema=GitDiffUnstaged.schema(),
111
+ ),
112
+ Tool(
113
+ name=GitTools.DIFF_STAGED,
114
+ description="Shows changes that are staged for commit",
115
+ inputSchema=GitDiffStaged.schema(),
116
+ ),
117
+ Tool(
118
+ name=GitTools.COMMIT,
119
+ description="Records changes to the repository",
120
+ inputSchema=GitCommit.schema(),
121
+ ),
122
+ Tool(
123
+ name=GitTools.ADD,
124
+ description="Adds file contents to the staging area",
125
+ inputSchema=GitAdd.schema(),
126
+ ),
127
+ Tool(
128
+ name=GitTools.RESET,
129
+ description="Unstages all staged changes",
130
+ inputSchema=GitReset.schema(),
131
+ ),
132
+ Tool(
133
+ name=GitTools.LOG,
134
+ description="Shows the commit logs",
135
+ inputSchema=GitLog.schema(),
136
+ ),
137
+ ]
138
+
139
+ async def list_repos() -> Sequence[str]:
140
+ async def by_roots() -> Sequence[str]:
141
+ if not isinstance(server.request_context.session, ServerSession):
142
+ raise TypeError("server.request_context.session must be a ServerSession")
143
+
144
+ if not server.request_context.session.check_client_capability(
145
+ ClientCapabilities(roots=RootsCapability())
146
+ ):
147
+ return []
148
+
149
+ roots_result: ListRootsResult = await server.request_context.session.list_roots()
150
+ logger.debug(f"Roots result: {roots_result}")
151
+ repo_paths = []
152
+ for root in roots_result.roots:
153
+ path = root.uri.path
154
+ try:
155
+ git.Repo(path)
156
+ repo_paths.append(str(path))
157
+ except git.InvalidGitRepositoryError:
158
+ pass
159
+ return repo_paths
160
+
161
+ def by_commandline() -> Sequence[str]:
162
+ return [str(repository)] if repository is not None else []
163
+
164
+ cmd_repos = by_commandline()
165
+ root_repos = await by_roots()
166
+ return [*root_repos, *cmd_repos]
167
+
168
+ @server.call_tool()
169
+ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
170
+ repo_path = Path(arguments["repo_path"])
171
+ repo = git.Repo(repo_path)
172
+
173
+ match name:
174
+ case GitTools.STATUS:
175
+ status = git_status(repo)
176
+ return [TextContent(
177
+ type="text",
178
+ text=f"Repository status:\n{status}"
179
+ )]
180
+
181
+ case GitTools.DIFF_UNSTAGED:
182
+ diff = git_diff_unstaged(repo)
183
+ return [TextContent(
184
+ type="text",
185
+ text=f"Unstaged changes:\n{diff}"
186
+ )]
187
+
188
+ case GitTools.DIFF_STAGED:
189
+ diff = git_diff_staged(repo)
190
+ return [TextContent(
191
+ type="text",
192
+ text=f"Staged changes:\n{diff}"
193
+ )]
194
+
195
+ case GitTools.COMMIT:
196
+ result = git_commit(repo, arguments["message"])
197
+ return [TextContent(
198
+ type="text",
199
+ text=result
200
+ )]
201
+
202
+ case GitTools.ADD:
203
+ result = git_add(repo, arguments["files"])
204
+ return [TextContent(
205
+ type="text",
206
+ text=result
207
+ )]
208
+
209
+ case GitTools.RESET:
210
+ result = git_reset(repo)
211
+ return [TextContent(
212
+ type="text",
213
+ text=result
214
+ )]
215
+
216
+ case GitTools.LOG:
217
+ log = git_log(repo, arguments.get("max_count", 10))
218
+ return [TextContent(
219
+ type="text",
220
+ text="Commit history:\n" + "\n".join(log)
221
+ )]
222
+
223
+ case _:
224
+ raise ValueError(f"Unknown tool: {name}")
225
+
226
+ options = server.create_initialization_options()
227
+ async with stdio_server() as (read_stream, write_stream):
228
+ await server.run(read_stream, write_stream, options, raise_exceptions=True)
@@ -167,7 +167,7 @@ wheels = [
167
167
 
168
168
  [[package]]
169
169
  name = "mcp-server-git"
170
- version = "0.2.0"
170
+ version = "0.3.0"
171
171
  source = { editable = "." }
172
172
  dependencies = [
173
173
  { name = "click" },
@@ -1,500 +0,0 @@
1
- import logging
2
- import json
3
- import sys
4
- import click
5
- import anyio
6
- import anyio.lowlevel
7
- from pathlib import Path
8
- from git.types import Sequence
9
- from mcp.server import Server
10
- from mcp.server.session import ServerSession
11
- from mcp.server.stdio import stdio_server
12
- from mcp.types import (
13
- ClientCapabilities,
14
- TextContent,
15
- Tool,
16
- EmbeddedResource,
17
- ImageContent,
18
- ListRootsResult,
19
- RootsCapability,
20
- )
21
- from enum import Enum
22
- import git
23
- from git.objects import Blob, Tree
24
-
25
- from pydantic import BaseModel, Field
26
- from typing import List, Optional
27
-
28
-
29
- class ReadFileInput(BaseModel):
30
- repo_path: str
31
- file_path: str
32
- ref: str = "HEAD"
33
-
34
-
35
- class ListFilesInput(BaseModel):
36
- repo_path: str
37
- path: str = ""
38
- ref: str = "HEAD"
39
-
40
-
41
- class FileHistoryInput(BaseModel):
42
- repo_path: str
43
- file_path: str
44
- max_entries: int = 10
45
-
46
-
47
- class CommitInput(BaseModel):
48
- repo_path: str
49
- message: str
50
- files: Optional[List[str]] = Field(
51
- None,
52
- description="List of files to stage and commit. If omitted, all changes will be staged.",
53
- )
54
-
55
-
56
- class SearchCodeInput(BaseModel):
57
- repo_path: str
58
- query: str
59
- file_pattern: str = "*"
60
- ref: str = "HEAD"
61
-
62
-
63
- class GetDiffInput(BaseModel):
64
- repo_path: str
65
- ref1: str
66
- ref2: str
67
- file_path: Optional[str] = None
68
-
69
-
70
- class GetRepoStructureInput(BaseModel):
71
- repo_path: str
72
- ref: str = "HEAD"
73
-
74
-
75
- class ListReposInput(BaseModel):
76
- pass
77
-
78
-
79
- class GitLogInput(BaseModel):
80
- repo_path: str
81
- max_count: int = 10
82
- ref: str = "HEAD"
83
-
84
-
85
- class ListBranchesInput(BaseModel):
86
- repo_path: str
87
-
88
-
89
- class ListTagsInput(BaseModel):
90
- repo_path: str
91
-
92
-
93
- class GitTools(str, Enum):
94
- READ_FILE = "git_read_file"
95
- LIST_FILES = "git_list_files"
96
- FILE_HISTORY = "git_file_history"
97
- COMMIT = "git_commit"
98
- SEARCH_CODE = "git_search_code"
99
- GET_DIFF = "git_get_diff"
100
- GET_REPO_STRUCTURE = "git_get_repo_structure"
101
- LIST_REPOS = "git_list_repos"
102
- GIT_LOG = "git_log"
103
- LIST_BRANCHES = "git_list_branches"
104
- LIST_TAGS = "git_list_tags"
105
-
106
-
107
- def git_read_file(repo: git.Repo, file_path: str, ref: str = "HEAD") -> str:
108
- tree = repo.commit(ref).tree
109
- blob = tree / file_path
110
- try:
111
- return blob.data_stream.read().decode("utf-8", errors="replace")
112
- except UnicodeDecodeError:
113
- # If it's a binary file, return a message indicating that
114
- return "[Binary file content not shown]"
115
-
116
-
117
- def git_list_files(repo: git.Repo, path: str = "", ref: str = "HEAD") -> Sequence[str]:
118
- tree = repo.commit(ref).tree
119
- if path:
120
- tree = tree / path
121
- # Use traverse() and isinstance() to get only blobs (files) recursively
122
- return [str(o.path) for o in tree.traverse() if isinstance(o, Blob)]
123
-
124
-
125
- def git_file_history(
126
- repo: git.Repo, file_path: str, max_entries: int = 10
127
- ) -> Sequence[str]:
128
- commits = list(repo.iter_commits(paths=file_path, max_count=max_entries))
129
- history = []
130
- for commit in commits:
131
- history.append(
132
- f"Commit: {commit.hexsha}\n"
133
- f"Author: {commit.author}\n"
134
- f"Date: {commit.authored_datetime}\n"
135
- f"Message: {commit.message}\n"
136
- )
137
- return history
138
-
139
-
140
- def git_commit(repo: git.Repo, message: str, files: list[str] | None = None) -> str:
141
- if files is not None:
142
- repo.index.add(files)
143
- else:
144
- repo.index.add("*") # Stage all changes
145
- commit = repo.index.commit(message)
146
- return f"Changes committed successfully with hash {commit.hexsha}"
147
-
148
-
149
- def git_search_code(
150
- repo: git.Repo, query: str, file_pattern: str = "*", ref: str = "HEAD"
151
- ) -> list[str]:
152
- results = []
153
- tree = repo.commit(ref).tree
154
- for blob in tree.traverse():
155
- if isinstance(blob, Blob) and Path(blob.path).match(file_pattern):
156
- try:
157
- content = blob.data_stream.read().decode("utf-8", errors="replace")
158
- for i, line in enumerate(content.splitlines()):
159
- if query in line:
160
- results.append(f"{blob.path}:{i+1}: {line}")
161
- except UnicodeDecodeError:
162
- # Skip binary files
163
- continue
164
- return results
165
-
166
-
167
- def git_get_diff(
168
- repo: git.Repo, ref1: str, ref2: str, file_path: str | None = None
169
- ) -> str:
170
- if file_path:
171
- return repo.git.diff(ref1, ref2, "--", file_path)
172
- return repo.git.diff(ref1, ref2)
173
-
174
-
175
- def git_get_repo_structure(repo: git.Repo, ref: str = "HEAD") -> str:
176
- tree = repo.commit(ref).tree
177
-
178
- def build_tree(tree_obj: Tree) -> dict:
179
- result = {}
180
- for item in tree_obj:
181
- if isinstance(item, Tree):
182
- result[item.name] = build_tree(item)
183
- else:
184
- result[item.name] = item.type
185
- return result
186
-
187
- structure = build_tree(tree)
188
- return str(structure)
189
-
190
-
191
- def git_log(repo: git.Repo, max_count: int = 10, ref: str = "HEAD") -> list[str]:
192
- commits = list(repo.iter_commits(ref, max_count=max_count))
193
- log = []
194
- for commit in commits:
195
- log.append(
196
- f"Commit: {commit.hexsha}\n"
197
- f"Author: {commit.author}\n"
198
- f"Date: {commit.authored_datetime}\n"
199
- f"Message: {commit.message}\n"
200
- )
201
- return log
202
-
203
-
204
- def git_list_branches(repo: git.Repo) -> list[str]:
205
- return [str(branch) for branch in repo.branches]
206
-
207
-
208
- def git_list_tags(repo: git.Repo) -> list[str]:
209
- return [str(tag) for tag in repo.tags]
210
-
211
-
212
- async def serve(repository: Path | None) -> None:
213
- # Set up logging
214
- logger = logging.getLogger(__name__)
215
-
216
- if repository is not None:
217
- try:
218
- git.Repo(repository)
219
- logger.info(f"Using repository at {repository}")
220
- except git.InvalidGitRepositoryError:
221
- logger.error(f"{repository} is not a valid Git repository")
222
- return
223
-
224
- # Create server
225
- server = Server("mcp-git")
226
-
227
- @server.list_tools()
228
- async def list_tools() -> list[Tool]:
229
- return [
230
- Tool(
231
- name=GitTools.READ_FILE,
232
- description="Retrieves and returns the content of a specified file from "
233
- "a Git repository at a given reference (commit, branch, or tag). This "
234
- "allows you to view file contents at any point in the repository's "
235
- "history.",
236
- inputSchema=ReadFileInput.schema(),
237
- ),
238
- Tool(
239
- name=GitTools.LIST_FILES,
240
- description="Enumerates all files in a Git repository or a specific "
241
- "directory within the repository. This tool can be used to explore the "
242
- "file structure of a project at a particular reference.",
243
- inputSchema=ListFilesInput.schema(),
244
- ),
245
- Tool(
246
- name=GitTools.FILE_HISTORY,
247
- description="Retrieves the commit history for a specific file, showing "
248
- "how it has changed over time. This includes commit hashes, authors, "
249
- "dates, and commit messages, allowing you to track the evolution of a "
250
- "file.",
251
- inputSchema=FileHistoryInput.schema(),
252
- ),
253
- Tool(
254
- name=GitTools.COMMIT,
255
- description="Commits changes to the repository. You can "
256
- "specify particular files to commit or commit all staged changes. This "
257
- "tool allows you to create new snapshots of your project with "
258
- "descriptive commit messages.",
259
- inputSchema=CommitInput.schema(),
260
- ),
261
- Tool(
262
- name=GitTools.SEARCH_CODE,
263
- description="Searches for specific patterns or text across all files in "
264
- "the repository. This powerful tool allows you to find occurrences of "
265
- "code, comments, or any text within your project, optionally filtering "
266
- "by file patterns and at a specific reference.",
267
- inputSchema=SearchCodeInput.schema(),
268
- ),
269
- Tool(
270
- name=GitTools.GET_DIFF,
271
- description="Computes and displays the differences between two Git "
272
- "references (commits, branches, or tags). This tool is crucial for "
273
- "understanding changes between different versions of your codebase, "
274
- "optionally focusing on a specific file.",
275
- inputSchema=GetDiffInput.schema(),
276
- ),
277
- Tool(
278
- name=GitTools.GET_REPO_STRUCTURE,
279
- description="Generates a representation of the repository's file and "
280
- "directory structure at a given reference. This provides a high-level "
281
- "overview of your project's organization, helping you understand the "
282
- "layout of your codebase.",
283
- inputSchema=GetRepoStructureInput.schema(),
284
- ),
285
- Tool(
286
- name=GitTools.LIST_REPOS,
287
- description="Enumerates all available Git repositories from the "
288
- "specified roots. This tool helps you manage and navigate multiple "
289
- "repositories, providing a comprehensive list of Git projects "
290
- "accessible to the current session.",
291
- inputSchema=ListReposInput.schema(),
292
- ),
293
- Tool(
294
- name=GitTools.GIT_LOG,
295
- description="Retrieves the commit log for the repository, showing the "
296
- "history of commits including commit hashes, authors, dates, and "
297
- "commit messages. This tool provides an overview of the project's "
298
- "development history.",
299
- inputSchema=GitLogInput.schema(),
300
- ),
301
- Tool(
302
- name=GitTools.LIST_BRANCHES,
303
- description="Lists all branches in the Git repository. This tool "
304
- "provides an overview of the different lines of development in the "
305
- "project.",
306
- inputSchema=ListBranchesInput.schema(),
307
- ),
308
- Tool(
309
- name=GitTools.LIST_TAGS,
310
- description="Lists all tags in the Git repository. This tool "
311
- "provides an overview of the tagged versions or releases in the "
312
- "project.",
313
- inputSchema=ListTagsInput.schema(),
314
- ),
315
- ]
316
-
317
- async def list_repos() -> Sequence[str]:
318
- async def by_roots() -> Sequence[str]:
319
- if not isinstance(server.request_context.session, ServerSession):
320
- raise TypeError(
321
- "server.request_context.session must be a ServerSession"
322
- )
323
-
324
- if not server.request_context.session.check_client_capability(
325
- ClientCapabilities(roots=RootsCapability())
326
- ):
327
- return []
328
-
329
- roots_result: ListRootsResult = (
330
- await server.request_context.session.list_roots()
331
- )
332
- logger.debug(f"Roots result: {roots_result}")
333
- repo_paths = []
334
- for root in roots_result.roots:
335
- path = root.uri.path
336
- try:
337
- # Verify this is a git repo
338
- git.Repo(path)
339
- repo_paths.append(str(path))
340
- except git.InvalidGitRepositoryError:
341
- pass
342
- return repo_paths
343
-
344
- def by_commandline() -> Sequence[str]:
345
- return [str(repository)] if repository is not None else []
346
-
347
- cmd_repos = by_commandline()
348
- root_repos = await by_roots()
349
- return [*root_repos, *cmd_repos]
350
-
351
- @server.call_tool()
352
- async def call_tool(
353
- name: str, arguments: dict
354
- ) -> list[TextContent | ImageContent | EmbeddedResource]:
355
- if name == GitTools.LIST_REPOS:
356
- result = await list_repos()
357
- logging.debug(f"repos={result}")
358
- return [
359
- TextContent(
360
- type="text",
361
- text=f"Here is some JSON that contains a list of git repositories: {json.dumps(result)}",
362
- )
363
- ]
364
-
365
- repo_path = Path(arguments["repo_path"])
366
- repo = git.Repo(repo_path)
367
-
368
- match name:
369
- case GitTools.READ_FILE:
370
- content = git_read_file(
371
- repo, arguments["file_path"], arguments.get("ref", "HEAD")
372
- )
373
- return [
374
- TextContent(
375
- type="text",
376
- text=f"Here is some JSON that contains the contents of a file: {json.dumps({'content': content})}",
377
- )
378
- ]
379
-
380
- case GitTools.LIST_FILES:
381
- files = git_list_files(
382
- repo, arguments.get("path", ""), arguments.get("ref", "HEAD")
383
- )
384
- return [
385
- TextContent(
386
- type="text",
387
- text=f"Here is some JSON that contains a list of files: {json.dumps({'files': list(files)})}",
388
- )
389
- ]
390
-
391
- case GitTools.FILE_HISTORY:
392
- history = git_file_history(
393
- repo, arguments["file_path"], arguments.get("max_entries", 10)
394
- )
395
- return [
396
- TextContent(
397
- type="text",
398
- text=f"Here is some JSON that contains a file's history: {json.dumps({'history': list(history)})}",
399
- )
400
- ]
401
-
402
- case GitTools.COMMIT:
403
- result = git_commit(repo, arguments["message"], arguments.get("files"))
404
- return [
405
- TextContent(
406
- type="text",
407
- text=f"Here is some JSON that contains the commit result: {json.dumps({'result': result})}",
408
- )
409
- ]
410
-
411
- case GitTools.SEARCH_CODE:
412
- results = git_search_code(
413
- repo,
414
- arguments["query"],
415
- arguments.get("file_pattern", "*"),
416
- arguments.get("ref", "HEAD"),
417
- )
418
- return [
419
- TextContent(
420
- type="text",
421
- text=f"Here is some JSON that contains code search matches: {json.dumps({'matches': results})}",
422
- )
423
- ]
424
-
425
- case GitTools.GET_DIFF:
426
- diff = git_get_diff(
427
- repo,
428
- arguments["ref1"],
429
- arguments["ref2"],
430
- arguments.get("file_path"),
431
- )
432
- return [
433
- TextContent(
434
- type="text",
435
- text=f"Here is some JSON that contains a diff: {json.dumps({'diff': diff})}",
436
- )
437
- ]
438
-
439
- case GitTools.GET_REPO_STRUCTURE:
440
- structure = git_get_repo_structure(repo, arguments.get("ref", "HEAD"))
441
- return [
442
- TextContent(
443
- type="text",
444
- text=f"Here is some JSON that contains the repository structure: {json.dumps({'structure': structure})}",
445
- )
446
- ]
447
-
448
- case GitTools.GIT_LOG:
449
- log = git_log(
450
- repo, arguments.get("max_count", 10), arguments.get("ref", "HEAD")
451
- )
452
- return [
453
- TextContent(
454
- type="text",
455
- text=f"Here is some JSON that contains the git log: {json.dumps({'log': log})}",
456
- )
457
- ]
458
-
459
- case GitTools.LIST_BRANCHES:
460
- branches = git_list_branches(repo)
461
- return [
462
- TextContent(
463
- type="text",
464
- text=f"Here is some JSON that contains a list of branches: {json.dumps({'branches': branches})}",
465
- )
466
- ]
467
-
468
- case GitTools.LIST_TAGS:
469
- tags = git_list_tags(repo)
470
- return [
471
- TextContent(
472
- type="text",
473
- text=f"Here is some JSON that contains a list of tags: {json.dumps({'tags': tags})}",
474
- )
475
- ]
476
-
477
- case _:
478
- raise ValueError(f"Unknown tool: {name}")
479
-
480
- # Run the server
481
- options = server.create_initialization_options()
482
- async with stdio_server() as (read_stream, write_stream):
483
- await server.run(read_stream, write_stream, options, raise_exceptions=True)
484
-
485
-
486
- @click.command()
487
- @click.option("-r", "--repository", type=click.Path(path_type=Path, dir_okay=True))
488
- @click.option("-v", "--verbose", count=True)
489
- def main(repository: Path | None, verbose: int):
490
- logging_level = logging.WARN
491
- if verbose == 1:
492
- logging_level = logging.INFO
493
- elif verbose >= 2:
494
- logging_level = logging.DEBUG
495
- logging.basicConfig(level=logging_level, stream=sys.stderr)
496
- anyio.run(serve, repository)
497
-
498
-
499
- if __name__ == "__main__":
500
- main()
File without changes