|
1 | 1 | # The git MCP server: tools that read and change a Git repository through |
2 | | -# GitPython. Repository confinement (`--repository`, `validate_repo_path` on the |
3 | | -# path given, `validate_opened_repo` on the directories git then uses) and the |
4 | | -# flag-injection guards live beside the handlers because every tool call must |
5 | | -# pass them before any git command runs. |
| 2 | +# GitPython, and prompts that embed a repository's changes in a message for the |
| 3 | +# model (#5195). Repository confinement (`--repository`, `validate_repo_path` on |
| 4 | +# the path given, `validate_opened_repo` on the directories git then uses) and |
| 5 | +# the flag-injection guards live beside the handlers because every tool call and |
| 6 | +# prompt must pass them before any git command runs. |
6 | 7 | # |
7 | 8 | # Built on the MCP Python SDK's high-level `MCPServer` (#5174), the API these |
8 | 9 | # reference servers are meant to teach: each tool is a typed function, and the |
@@ -861,6 +862,93 @@ def writes(*, destructive: bool, idempotent: bool) -> ToolAnnotations: |
861 | 862 | ) |
862 | 863 |
|
863 | 864 |
|
| 865 | +class GitPrompts(str, Enum): |
| 866 | + COMMIT_MESSAGE = "git_commit_message" |
| 867 | + SUMMARIZE_CHANGES = "git_summarize_changes" |
| 868 | + |
| 869 | + |
| 870 | +def _fenced(text: str, info: str = "diff") -> str: |
| 871 | + """`text` in a Markdown code fence longer than any backtick run inside it. |
| 872 | +
|
| 873 | + A diff can itself hold a ``` line (a Markdown file's code block), which |
| 874 | + would close a fixed three-backtick fence early. |
| 875 | + """ |
| 876 | + # One pass for the longest run: growing the fence and searching again for |
| 877 | + # each extra backtick is quadratic in a long run, under the git lock. |
| 878 | + longest = run = 0 |
| 879 | + for char in text: |
| 880 | + run = run + 1 if char == "`" else 0 |
| 881 | + longest = max(longest, run) |
| 882 | + fence = "`" * max(3, longest + 1) |
| 883 | + body = text.rstrip("\n") |
| 884 | + return f"{fence}{info}\n{body}\n{fence}" |
| 885 | + |
| 886 | + |
| 887 | +def commit_message_prompt(repo: git.Repo) -> str: |
| 888 | + """The git_commit_message prompt's text: the staged diff and the request.""" |
| 889 | + diff = git_diff_staged(repo) |
| 890 | + if not diff.strip(): |
| 891 | + return ( |
| 892 | + "There are no staged changes in this repository, so there is nothing " |
| 893 | + "to write a commit message for. Tell the user to stage changes first " |
| 894 | + "(git_add); git_status shows what is modified or untracked." |
| 895 | + ) |
| 896 | + return ( |
| 897 | + "Write a commit message for the staged changes below. Start with an " |
| 898 | + "imperative subject line of at most 72 characters, then a blank line and " |
| 899 | + "a short body explaining what changed and why, only if the subject alone " |
| 900 | + "does not say enough. Follow the repository's existing convention if " |
| 901 | + "its history shows one (git_log).\n\n" |
| 902 | + f"Staged changes:\n{_fenced(diff)}" |
| 903 | + ) |
| 904 | + |
| 905 | + |
| 906 | +def summarize_changes_prompt(repo: git.Repo, target: str | None = None) -> str: |
| 907 | + """The git_summarize_changes prompt's text: the changes and the request.""" |
| 908 | + if target: |
| 909 | + # git_diff applies the flag-injection guard and resolves the target. |
| 910 | + diff = git_diff(repo, target) |
| 911 | + scope = f"compared with `{target}`" |
| 912 | + changes = f"Diff against {target}:\n{_fenced(diff)}" if diff.strip() else "" |
| 913 | + else: |
| 914 | + staged = git_diff_staged(repo) |
| 915 | + unstaged = git_diff_unstaged(repo) |
| 916 | + scope = "in the working tree" |
| 917 | + parts = [f"Status:\n{_fenced(git_status(repo), 'text')}"] |
| 918 | + if staged.strip(): |
| 919 | + parts.append(f"Staged changes:\n{_fenced(staged)}") |
| 920 | + if unstaged.strip(): |
| 921 | + parts.append(f"Unstaged changes:\n{_fenced(unstaged)}") |
| 922 | + # The porcelain status is empty only on a clean tree; an untracked file |
| 923 | + # alone leaves both diffs empty but is still a change to summarize. |
| 924 | + clean = not repo.git.status("--porcelain").strip() |
| 925 | + changes = "" if clean else "\n\n".join(parts) |
| 926 | + if not changes: |
| 927 | + return f"There are no changes {scope} to summarize. Tell the user so." |
| 928 | + return ( |
| 929 | + f"Summarize the changes {scope} below for a reviewer, in plain " |
| 930 | + "language. Group related changes, explain the intent behind them rather " |
| 931 | + "than restating each line, and point out anything that looks unfinished " |
| 932 | + "or risky.\n\n" |
| 933 | + f"{changes}" |
| 934 | + ) |
| 935 | + |
| 936 | + |
| 937 | +@contextmanager |
| 938 | +def reported_as_invalid_params() -> Iterator[None]: |
| 939 | + """Turn an anticipated failure in a prompt into a JSON-RPC -32602 error. |
| 940 | +
|
| 941 | + `prompts/get` has no `isError` result: the spec's error handling for it is |
| 942 | + a JSON-RPC error, and a repository path, target or guard the request named |
| 943 | + is an invalid argument. Without this, MCPServer hides the message behind |
| 944 | + "Error rendering prompt" (code 0 or -32603, depending on the era). |
| 945 | + """ |
| 946 | + try: |
| 947 | + yield |
| 948 | + except ANTICIPATED_ERRORS as e: |
| 949 | + raise MCPError(code=INVALID_PARAMS, message=str(e)) from e |
| 950 | + |
| 951 | + |
864 | 952 | def create_server(repository: Path | None) -> MCPServer: |
865 | 953 | """The git server, confined to `repository` when one is given.""" |
866 | 954 |
|
@@ -901,6 +989,43 @@ def open_repo(repo_path: str) -> git.Repo: |
901 | 989 | raise |
902 | 990 | return repo |
903 | 991 |
|
| 992 | + # Prompts (#5195): each embeds what the repository holds now in one user |
| 993 | + # message, through the same `open_repo` (and so the same confinement) and |
| 994 | + # the same guarded helpers as the tools, under the same lock. |
| 995 | + @server.prompt( |
| 996 | + name=GitPrompts.COMMIT_MESSAGE.value, |
| 997 | + title="Draft a commit message", |
| 998 | + description="Asks the model for a commit message for the staged changes", |
| 999 | + ) |
| 1000 | + def commit_message( |
| 1001 | + repo_path: Annotated[str, Field(description="The path to the Git repository.")], |
| 1002 | + ) -> str: |
| 1003 | + with _GIT_LOCK, reported_as_invalid_params(), open_repo(repo_path) as repo: |
| 1004 | + return commit_message_prompt(repo) |
| 1005 | + |
| 1006 | + @server.prompt( |
| 1007 | + name=GitPrompts.SUMMARIZE_CHANGES.value, |
| 1008 | + title="Summarize changes", |
| 1009 | + description=( |
| 1010 | + "Asks the model to summarize the working tree's staged and unstaged " |
| 1011 | + "changes, or the diff against a branch or commit" |
| 1012 | + ), |
| 1013 | + ) |
| 1014 | + def summarize_changes( |
| 1015 | + repo_path: Annotated[str, Field(description="The path to the Git repository.")], |
| 1016 | + target: Annotated[ |
| 1017 | + Optional[str], |
| 1018 | + Field( |
| 1019 | + description=( |
| 1020 | + "Branch or commit to diff against. Defaults to the working " |
| 1021 | + "tree's staged and unstaged changes" |
| 1022 | + ) |
| 1023 | + ), |
| 1024 | + ] = None, |
| 1025 | + ) -> str: |
| 1026 | + with _GIT_LOCK, reported_as_invalid_params(), open_repo(repo_path) as repo: |
| 1027 | + return summarize_changes_prompt(repo, target) |
| 1028 | + |
904 | 1029 | @server.tool( |
905 | 1030 | name=GitTools.STATUS.value, |
906 | 1031 | description="Shows the working tree status", |
|
0 commit comments