Unit 3 MCP Server

#19
by eleali - opened
Hugging Face MCP Course org

i have a project in this dir:
PS C:\Users\PC\Desktop\Software\pr-agent-test>
in this project, i made a diff(added a line in my python file)
and asked claude code, anylyze the files and find the diff and according to the diff, suggest me a good github pr template.
The way i do is to use my own mcp server. my server.py code is like this:
import json
import os
import subprocess
from typing import Optional
from pathlib import Path

from mcp.server.fastmcp import FastMCP

Initialize the FastMCP server

mcp = FastMCP("pr-agent")

PR template directory (shared between starter and solution)

TEMPLATES_DIR = Path(file).parent.parent.parent / "templates"

Default PR templates

DEFAULT_TEMPLATES = {
"bug.md": "Bug Fix",
"feature.md": "Feature",
"docs.md": "Documentation",
"refactor.md": "Refactor",
"test.md": "Test",
"performance.md": "Performance",
"security.md": "Security"
}

Type mapping for PR templates

TYPE_MAPPING = {
"bug": "bug.md",
"fix": "bug.md",
"feature": "feature.md",
"enhancement": "feature.md",
"docs": "docs.md",
"documentation": "docs.md",
"refactor": "refactor.md",
"cleanup": "refactor.md",
"test": "test.md",
"testing": "test.md",
"performance": "performance.md",
"optimization": "performance.md",
"security": "security.md"
}

TODO: Implement analyze_file_changes tool that gets git diff information

HINT: Use subprocess.run(["git", "diff", "--name-status", "main...HEAD"])

@mcp.tool()
async def analyze_file_changes(
base_branch: str = "main",
include_diff: bool = True,
max_diff_lines: int = 500,
working_directory: Optional[str] = None
) -> str:
"""Get the full diff and list of changed files in the current git repository.

Args:
    base_branch: Base branch to compare against (default: main)
    include_diff: Include the full diff content (default: true)
    max_diff_lines: Maximum number of diff lines to include (default: 500)
    working_directory: Directory to run git commands in (default: current directory)
"""
    # TODO: Get the working directory (try MCP context roots first, fallback to os.getcwd())
# TODO: Run git commands: diff --name-status, diff --stat, git log --oneline
# TODO: Handle subprocess errors and return JSON error response
# TODO: Truncate long diffs and include debug info
try:
    if working_directory is None:
        try:
            context = mcp.get_context()
            roots_result = await context.session.list_roots()
            root = roots_result.roots[0]

            working_directory = root.uri.path

            if os.name == "nt" and working_directory.startswith("/"):
                working_directory = working_directory.lstrip("/")
        except Exception:
            # If we can't get roots, fall back to current directory
            pass
    
    # Use provided working directory or current directory
    cwd = working_directory if working_directory else os.getcwd()
    
    # Debug output
    debug_info = {
        "provided_working_directory": working_directory,
        "actual_cwd": cwd,
        "server_process_cwd": os.getcwd(),
        "server_file_location": str(Path(__file__).parent),
        "roots_check": None
    }
    
    # Add roots debug info
    try:
        context = mcp.get_context()
        roots_result = await context.session.list_roots()
        debug_info["roots_check"] = {
            "found": True,
            "count": len(roots_result.roots),
            "roots": [str(root.uri) for root in roots_result.roots]
        }
    except Exception as e:
        debug_info["roots_check"] = {
            "found": False,
            "error": str(e)
        }
    
    # Get list of changed files
    files_result = subprocess.run(
        ["git", "diff", "--name-status", f"{base_branch}...HEAD"],
        capture_output=True,
        text=True,
        check=True,
        cwd=cwd
    )
    
    # Get diff statistics
    stat_result = subprocess.run(
        ["git", "diff", "--stat", f"{base_branch}...HEAD"],
        capture_output=True,
        text=True,
        cwd=cwd
    )
    
    # Get the actual diff if requested
    diff_content = ""
    truncated = False
    if include_diff:
        diff_result = subprocess.run(
            ["git", "diff", f"{base_branch}...HEAD"],
            capture_output=True,
            text=True,
            cwd=cwd
        )
        diff_lines = diff_result.stdout.split('\n')
        
        # Check if we need to truncate
        if len(diff_lines) > max_diff_lines:
            diff_content = '\n'.join(diff_lines[:max_diff_lines])
            diff_content += f"\n\n... Output truncated. Showing {max_diff_lines} of {len(diff_lines)} lines ..."
            diff_content += "\n... Use max_diff_lines parameter to see more ..."
            truncated = True
        else:
            diff_content = diff_result.stdout
    
    # Get commit messages for context
    commits_result = subprocess.run(
        ["git", "log", "--oneline", f"{base_branch}..HEAD"],
        capture_output=True,
        text=True,
        cwd=cwd
    )
    
    analysis = {
        "base_branch": base_branch,
        "files_changed": files_result.stdout,
        "statistics": stat_result.stdout,
        "commits": commits_result.stdout,
        "diff": diff_content if include_diff else "Diff not included (set include_diff=true to see full diff)",
        "truncated": truncated,
        "total_diff_lines": len(diff_lines) if include_diff else 0,
        "_debug": debug_info
    }
    
    return json.dumps(analysis, indent=2)
    
except subprocess.CalledProcessError as e:
    return json.dumps({"error": f"Git error: {e.stderr}"})
except Exception as e:
    return json.dumps({"error": str(e)})

TODO: Implement get_pr_templates tool that lists available PR templates

@mcp.tool()
async def get_pr_templates() -> str:
"""List available PR templates with their content."""
# TODO: Read template files from TEMPLATES_DIR or use default content
# TODO: Return JSON list of {"filename": "...", "type": "...", "content": "..."}
templates = [
{
"filename": filename,
"type": template_type,
"content": (TEMPLATES_DIR / filename).read_text()
}
for filename, template_type in DEFAULT_TEMPLATES.items()
]

return json.dumps(templates, indent=2)

TODO: Implement suggest_template tool that recommends PR template

@mcp.tool()
async def suggest_template(changes_summary: str, change_type: str) -> str:
"""Let Claude analyze the changes and suggest the most appropriate PR template.

Args:
    changes_summary: Your analysis of what the changes do
    change_type: The type of change you've identified (bug, feature, docs, refactor, test, etc.)
"""
 # TODO: Use TYPE_MAPPING to find best template filename
# TODO: Call get_pr_templates() and select matching template
# TODO: Return JSON with recommended_template, reasoning, and template_content
# Get available templates
templates_response = await get_pr_templates()
templates = json.loads(templates_response)

# Find matching template
template_file = TYPE_MAPPING.get(change_type.lower(), "feature.md")
selected_template = next(
    (t for t in templates if t["filename"] == template_file),
    templates[0]  # Default to first template if no match
)

suggestion = {
    "recommended_template": selected_template,
    "reasoning": f"Based on your analysis: '{changes_summary}', this appears to be a {change_type} change.",
    "template_content": selected_template["content"],
    "usage_hint": "Claude can help you fill out this template based on the specific changes in your PR."
}

return json.dumps(suggestion, indent=2)

if name == "main":
mcp.run()
this is the solution code for the unit 3 mcp server.

as u can see the claude code should analyze the project and according to the diff it finds, it should suggest me pr template and this is the prompt i use:

Can you analyze my changes and suggest me a PR template?
this is the full output:

Can you analyze my changes and suggest me a PR template?

● I'll analyze your changes and suggest an appropriate PR template for you.

● pr-agent - analyze_file_changes (MCP)(base_branch: "main", include_diff: true)
⎿ {
"result": "{\n "base_branch": "main",\n "files_changed": "M\tapp.py\n",\n "statistics": " app.py | 3 ++-\n 1 file changed, 2 insertions(+), 1 deletion(-)\n",\n "commits": "e4a2f05 A\na
ed86c1 it will work\n0eeafd9 new\ne70ac91 Update greeting\n",\n "diff": "diff --git a/app.py b/app.py\nindex 1385fe3..602cca7 100644\n--- a/app.py\n+++ b/app.py\n@@ -1 +1,2 @@\n-print(\"Hello, wo
… +5 lines (ctrl+o to expand)

  • Lollygagging… (esc to interrupt · 2m 1s · ↑ 573 tokens)
    as u can see, it found the diff and printed out but here is the problem. when it wants permission from me to use the analyze_file_changes tool from my server.py, i click yes and then it starts using the tool but it stucks there. if it stucks then how did i get the correct result with this tool? i have sended u the output and yes we can see the diff then what is the problem? the problem is:
    as u can see in the output i have sended:

  • Lollygagging… (esc to interrupt · 2m 1s · ↑ 573 tokens)
    it took 2m 1 s. this is the part it stucks. if i dont manually break out of this by pressing ctrl + c twice, it can stuck here infinitly(i guess)
    when i use ctrl + c twice, it breaks out and show me the output of the anylze file changes tool. normally it should contniue working, after getting the diff with anylze file changes tool, it should also want permission to use get_pr_templates tool to look up the available templates and then it should also want permission to use suggest_template tool to suggest me the pr template. this i swhat it should have done. but again it doesnt go like this. how can i accomplish this? why it stucks right there even if it can get the diff with analyze changed files tool

Sign up or log in to comment