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.
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.
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:
@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)})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