Itâs your first week at CodeCraft Studios, and youâre witnessing something that makes every developer cringe. The teamâs pull requests look like this:
Meanwhile, the code review backlog is growing because reviewers canât understand what changed or why. Sarah from the backend team spent 30 minutes trying to figure out what âvarious improvementsâ actually meant, while Mike from frontend had to dig through 47 files to understand a âsmall fix.â
The team knows they need better PR descriptions, but everyoneâs too busy shipping features to write detailed explanations. They need a solution that helps without slowing them down.
Your mission: Build an intelligent PR Agent that analyzes code changes and suggests helpful descriptions automatically.
What Youâll See: A real PR at CodeCraft Studios titled âvarious improvementsâ and the description simply says âFixed some stuff and made updatesâ. Classic, right?
The Confusion: Watch as teammates struggle:
The Pain Point: The screencast shows the actual diffâ8 files scattered across multiple services with zero context. Reviewers have to piece together the story themselves, wasting precious time and possibly missing critical issues.
Why This Matters: This is exactly the PR chaos your MCP server will solve! By the end of this module, youâll turn these cryptic PRs into clear, actionable descriptions that make everyoneâs life easier.
In this first module, youâll create the foundation of CodeCraft Studiosâ automation system: an MCP server that transforms how the team writes pull requests. This module focuses on core MCP concepts that youâll build upon in Modules 2 and 3.
The Solution in Action: Watch how your MCP server will transform PR chaos into clarity:
analyze_file_changes - Grabs all the changes (453 lines across 8 files!)get_pr_templates - Shows Claude the 7 templates to choose fromsuggest_template - Claude picks âFeatureâ (smart choice!)What Youâll See: Claude doesnât just pick a templateâit:
The âWowâ Moment â¨: In just seconds, your MCP server helps Claude transform the same branch into a PR that actually explains whatâs going on. No more confused reviewers, no more âwhat does this do?â comments.
This is what youâll build: A tool that turns PR dread into PR delightâletâs get started!
In this foundational module, youâll master:
Your PR Agent will solve CodeCraft Studiosâ problem using a key principle of MCP development: instead of hard-coding rigid rules about what makes a good PR, youâll provide Claude with raw git data and let it intelligently suggest appropriate descriptions.
This approach works because:
Youâll implement three essential tools that establish patterns for the entire automation system:
Clone the starter code repository:
git clone https://github.com/huggingface/mcp-course.gitNavigate to the starter code directory:
cd mcp-course/projects/unit3/build-mcp-server/starterInstall dependencies:
You might want to create a virtual environment for this project:
uv venv .venv
source .venv/bin/activate # On Windows use: .venv\Scripts\activateuv sync --all-extrasThis is your first hands-on MCP development experience! Open server.py and implement the three tools following the TODO comments. The starter code provides the basic structure - you need to:
analyze_file_changes to run git commands and return diff dataget_pr_templates to manage and return PR templatessuggest_template to map change types to templatesDonât worry about making everything perfect - youâll refine these skills as you progress through the unit.
Unlike traditional systems that categorize changes based on file extensions or rigid patterns, your implementation should:
MCP Philosophy: Instead of building complex logic into your tools, provide Claude with rich data and let its intelligence make the decisions. This makes your code simpler and more flexible than traditional rule-based systems.
Run the validation script to check your implementation:
uv run python validate_starter.py
Test your implementation with the provided test suite:
uv run pytest test_server.py -v
Configure your server directly in Claude Code:
# Add the MCP server to Claude Code
claude mcp add pr-agent -- uv --directory /absolute/path/to/starter run server.py
# Verify the server is configured
claude mcp listThen:
Common first error: If you get âMCP tool response exceeds maximum allowed tokens (25000)â, this is expected! Large repositories can generate massive diffs. This is a valuable learning moment - see the âHandling Large Outputsâ section for the solution.
@mcp.tool()
async def tool_name(param1: str, param2: bool = True) -> str:
"""Tool description for Claude.
Args:
param1: Description of parameter
param2: Optional parameter with default
"""
# Your implementation
result = {"key": "value"}
return json.dumps(result)Always handle potential errors gracefully:
try:
result = subprocess.run(["git", "diff"], capture_output=True, text=True)
return json.dumps({"output": result.stdout})
except Exception as e:
return json.dumps({"error": str(e)})Error Handling: Always return valid JSON from your tools, even for errors. Claude needs structured data to understand what went wrong and provide helpful responses to users.
Real-world constraint: MCP tools have a token limit of 25,000 tokens per response. Large git diffs can easily exceed this limit 10x or more! This is a critical lesson for production MCP development.
When implementing analyze_file_changes, youâll likely encounter this error:
Error: MCP tool response (262521 tokens) exceeds maximum allowed tokens (25000)Why this happens:
This teaches us an important principle: Always design tools with output limits in mind. Hereâs the solution:
@mcp.tool()
async def analyze_file_changes(base_branch: str = "main",
include_diff: bool = True,
max_diff_lines: int = 500) -> str:
"""Analyze file changes with smart output limiting.
Args:
base_branch: Branch to compare against
include_diff: Whether to include the actual diff
max_diff_lines: Maximum diff lines to include (default 500)
"""
try:
# Get the diff
result = subprocess.run(
["git", "diff", f"{base_branch}...HEAD"],
capture_output=True,
text=True
)
diff_output = result.stdout
diff_lines = diff_output.split('\n')
# Smart truncation if needed
if len(diff_lines) > max_diff_lines:
truncated_diff = '\n'.join(diff_lines[:max_diff_lines])
truncated_diff += f"\n\n... Output truncated. Showing {max_diff_lines} of {len(diff_lines)} lines ..."
diff_output = truncated_diff
# Get summary statistics
stats_result = subprocess.run(
["git", "diff", "--stat", f"{base_branch}...HEAD"],
capture_output=True,
text=True
)
return json.dumps({
"stats": stats_result.stdout,
"total_lines": len(diff_lines),
"diff": diff_output if include_diff else "Use include_diff=true to see diff",
"files_changed": self._get_changed_files(base_branch)
})
except Exception as e:
return json.dumps({"error": str(e)})Best practices for large outputs:
By default, MCP servers run commands in their installation directory, not in Claudeâs current working directory. This means your git commands might analyze the wrong repository!
To solve this, MCP provides roots - a way for clients to inform servers about relevant directories. Claude Code automatically provides its working directory as a root.
Hereâs how to access it in your tool:
@mcp.tool()
async def analyze_file_changes(...):
# Get Claude's working directory from roots
context = mcp.get_context()
roots_result = await context.session.list_roots()
# Extract the path from the FileUrl object
working_dir = roots_result.roots[0].uri.path
# Use it for all git commands
result = subprocess.run(
["git", "diff", "--name-status"],
capture_output=True,
text=True,
cwd=working_dir # Run in Claude's directory!
)This ensures your tools operate on the repository Claude is actually working with, not the MCP serverâs installation location.
Import errors: Ensure youâve run uv sync
Git errors: Make sure youâre in a git repository
No output: MCP servers communicate via stdio - test with Claude Desktop
JSON errors: All tools must return valid JSON strings
Token limit exceeded: This is expected with large diffs! Implement output limiting as shown above
âResponse too largeâ errors: Add max_diff_lines parameter or set include_diff=false
Git commands run in wrong directory: MCP servers run in their installation directory by default, not Claudeâs working directory. To fix this, use MCP roots to access Claudeâs current directory:
# Get Claude's working directory from roots
context = mcp.get_context()
roots_result = await context.session.list_roots()
working_dir = roots_result.roots[0].uri.path # FileUrl object has .path property
# Use it in subprocess calls
subprocess.run(["git", "diff"], cwd=working_dir)Claude Code automatically provides its working directory as a root, allowing your MCP server to operate in the correct location.
Congratulations! Youâve built your first MCP server with Tools - the foundation for everything that follows in Unit 3.
/projects/unit3/build-mcp-server/solution/ to see different implementation approachesModule 2 will build directly on the server you created here, adding dynamic event handling to complement your static file analysis tools!
With your PR Agent working, CodeCraft Studios developers are already writing better pull requests. But next week, youâll face a new challenge: critical CI/CD failures are slipping through unnoticed. Module 2 will add real-time monitoring to catch these issues before they reach production.
unit3/build-mcp-server-solution-walkthrough.md