Skip to content

Commit eced757

Browse files
cliffhallclaude
andcommitted
feat(git): add prompts that embed the repository's changes
Add two prompts to demonstrate the Prompts feature beside the tools: git_commit_message embeds the staged diff and asks for a commit message, and git_summarize_changes embeds the working tree's status and staged and unstaged diffs (or the diff against a target) and asks for a summary. Both open the repository through open_repo and reuse the tools' helpers, so --repository confinement and the flag-injection guards apply unchanged, under the same lock. An anticipated failure is a JSON-RPC -32602 error carrying the tool's message, since prompts/get has no isError result. Tested in both protocol eras. Closes modelcontextprotocol#5195 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit eced757

4 files changed

Lines changed: 425 additions & 8 deletions

File tree

‎src/git/README.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,25 @@ Roots is deprecated in 2026-07-28, and this server never asks a client for Roots
111111
- **A tool that fails** returns a result with `isError: true` whose text is `Error executing tool <name>: <message>`, so the model can read it and correct the call. This covers git errors (an unknown revision, a failed command), a `repo_path` that is not a repository or is outside `--repository`, the flag-injection guards, and arguments that do not match the tool's input schema.
112112
- **An unknown tool name** is a protocol error, JSON-RPC `-32602` (`Unknown tool: <name>`), as the specification requires in both eras. Before 2.0.0 it was an `isError` result.
113113

114+
### Prompts
115+
116+
Beside its tools, the server offers two prompts, which a client typically shows the user as slash commands. Each reads the repository when it is requested and returns one user message that embeds the changes, ready to send to the model. They open the repository the way the tools do, so `--repository` confines them too, and the same flag-injection guards apply. They behave the same in both protocol eras.
117+
118+
1. `git_commit_message`
119+
- Asks the model for a commit message for the staged changes
120+
- Arguments:
121+
- `repo_path` (string, required): Path to the Git repository
122+
- Returns: A message embedding the staged diff and asking for a commit message, or one saying nothing is staged
123+
124+
2. `git_summarize_changes`
125+
- Asks the model to summarize the working tree's changes, or the diff against a branch or commit
126+
- Arguments:
127+
- `repo_path` (string, required): Path to the Git repository
128+
- `target` (string, optional): Branch or commit to diff against. Without it, the working tree's status and its staged and unstaged diffs are summarized
129+
- Returns: A message embedding those changes and asking for a summary, or one saying there are none
130+
131+
A prompt request that fails (a `repo_path` that is not a repository or is outside `--repository`, an unknown `target`, a `target` starting with `-`) is a JSON-RPC `-32602` error carrying the message a tool would report, since `prompts/get` has no `isError` result.
132+
114133
## Installation
115134

116135
### Using uv (recommended)

‎src/git/src/mcp_server_git/server.py‎

Lines changed: 122 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# 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.
67
#
78
# Built on the MCP Python SDK's high-level `MCPServer` (#5174), the API these
89
# reference servers are meant to teach: each tool is a typed function, and the
@@ -596,6 +597,86 @@ def writes(*, destructive: bool, idempotent: bool) -> ToolAnnotations:
596597
)
597598

598599

600+
class GitPrompts(str, Enum):
601+
COMMIT_MESSAGE = "git_commit_message"
602+
SUMMARIZE_CHANGES = "git_summarize_changes"
603+
604+
605+
def _fenced(text: str, info: str = "diff") -> str:
606+
"""`text` in a Markdown code fence longer than any backtick run inside it.
607+
608+
A diff can itself hold a ``` line (a Markdown file's code block), which
609+
would close a fixed three-backtick fence early.
610+
"""
611+
fence = "```"
612+
while fence in text:
613+
fence += "`"
614+
body = text.rstrip("\n")
615+
return f"{fence}{info}\n{body}\n{fence}"
616+
617+
618+
def commit_message_prompt(repo: git.Repo) -> str:
619+
"""The git_commit_message prompt's text: the staged diff and the request."""
620+
diff = git_diff_staged(repo)
621+
if not diff.strip():
622+
return (
623+
"There are no staged changes in this repository, so there is nothing "
624+
"to write a commit message for. Tell the user to stage changes first "
625+
"(git_add); git_status shows what is modified or untracked."
626+
)
627+
return (
628+
"Write a commit message for the staged changes below. Start with an "
629+
"imperative subject line of at most 72 characters, then a blank line and "
630+
"a short body explaining what changed and why, only if the subject alone "
631+
"does not say enough. Follow the repository's existing convention if "
632+
"its history shows one (git_log).\n\n"
633+
f"Staged changes:\n{_fenced(diff)}"
634+
)
635+
636+
637+
def summarize_changes_prompt(repo: git.Repo, target: str | None = None) -> str:
638+
"""The git_summarize_changes prompt's text: the changes and the request."""
639+
if target:
640+
# git_diff applies the flag-injection guard and resolves the target.
641+
diff = git_diff(repo, target)
642+
scope = f"compared with `{target}`"
643+
changes = f"Diff against {target}:\n{_fenced(diff)}" if diff.strip() else ""
644+
else:
645+
staged = git_diff_staged(repo)
646+
unstaged = git_diff_unstaged(repo)
647+
scope = "in the working tree"
648+
parts = [f"Status:\n{_fenced(git_status(repo), 'text')}"]
649+
if staged.strip():
650+
parts.append(f"Staged changes:\n{_fenced(staged)}")
651+
if unstaged.strip():
652+
parts.append(f"Unstaged changes:\n{_fenced(unstaged)}")
653+
changes = "\n\n".join(parts) if staged.strip() or unstaged.strip() else ""
654+
if not changes:
655+
return f"There are no changes {scope} to summarize. Tell the user so."
656+
return (
657+
f"Summarize the changes {scope} below for a reviewer, in plain "
658+
"language. Group related changes, explain the intent behind them rather "
659+
"than restating each line, and point out anything that looks unfinished "
660+
"or risky.\n\n"
661+
f"{changes}"
662+
)
663+
664+
665+
@contextmanager
666+
def reported_as_invalid_params() -> Iterator[None]:
667+
"""Turn an anticipated failure in a prompt into a JSON-RPC -32602 error.
668+
669+
`prompts/get` has no `isError` result: the spec's error handling for it is
670+
a JSON-RPC error, and a repository path, target or guard the request named
671+
is an invalid argument. Without this, MCPServer hides the message behind
672+
"Error rendering prompt" (code 0 or -32603, depending on the era).
673+
"""
674+
try:
675+
yield
676+
except ANTICIPATED_ERRORS as e:
677+
raise MCPError(code=INVALID_PARAMS, message=str(e)) from e
678+
679+
599680
def create_server(repository: Path | None) -> MCPServer:
600681
"""The git server, confined to `repository` when one is given."""
601682

@@ -636,6 +717,43 @@ def open_repo(repo_path: str) -> git.Repo:
636717
raise
637718
return repo
638719

720+
# Prompts (#5195): each embeds what the repository holds now in one user
721+
# message, through the same `open_repo` (and so the same confinement) and
722+
# the same guarded helpers as the tools, under the same lock.
723+
@server.prompt(
724+
name=GitPrompts.COMMIT_MESSAGE.value,
725+
title="Draft a commit message",
726+
description="Asks the model for a commit message for the staged changes",
727+
)
728+
def commit_message(
729+
repo_path: Annotated[str, Field(description="The path to the Git repository.")],
730+
) -> str:
731+
with _GIT_LOCK, reported_as_invalid_params(), open_repo(repo_path) as repo:
732+
return commit_message_prompt(repo)
733+
734+
@server.prompt(
735+
name=GitPrompts.SUMMARIZE_CHANGES.value,
736+
title="Summarize changes",
737+
description=(
738+
"Asks the model to summarize the working tree's staged and unstaged "
739+
"changes, or the diff against a branch or commit"
740+
),
741+
)
742+
def summarize_changes(
743+
repo_path: Annotated[str, Field(description="The path to the Git repository.")],
744+
target: Annotated[
745+
Optional[str],
746+
Field(
747+
description=(
748+
"Branch or commit to diff against. Defaults to the working "
749+
"tree's staged and unstaged changes"
750+
)
751+
),
752+
] = None,
753+
) -> str:
754+
with _GIT_LOCK, reported_as_invalid_params(), open_repo(repo_path) as repo:
755+
return summarize_changes_prompt(repo, target)
756+
639757
@server.tool(
640758
name=GitTools.STATUS.value,
641759
description="Shows the working tree status",

0 commit comments

Comments
 (0)