Add MCP PR agent project (Units 1-3)
Browse filesFiles changed (12)
- LICENSEAdded+21
- README.mdAdded+134
- mcp-server/server.pyAdded+181
- quiz-answers/QUIZ_ANSWERS.mdAdded+85
- requirements.txtAdded+2
- templates/bug.mdAdded+18
- templates/docs.mdAdded+13
- templates/feature.mdAdded+22
- templates/performance.mdAdded+15
- templates/refactor.mdAdded+18
- templates/security.mdAdded+18
- templates/test.mdAdded+16
123456789101112131415161718192021MIT License
Copyright (c) 2026 ISLAM-PO
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# MCP PR Agent β Model Context Protocol Course Project
[](https://huggingface.co/ISLAM-PO)[](LICENSE)
> **MCP Course (Units 1β3)** project for the [Hugging Face MCP Course](https://huggingface.co/learn/mcp-course), built in partnership with Anthropic.
A production-ready **MCP server** that helps developers create better pull requests by analyzing git changes and suggesting appropriate PR templates. The server exposes 3 tools, 2 resources, and 1 prompt via the Model Context Protocol.
## Table of Contents
- [Overview](#overview)- [Project Structure](#project-structure)- [Tools](#tools)- [Quick Start](#quick-start)- [Usage with Claude Code](#usage-with-claude-code)- [Quiz Answers (Unit 1)](#quiz-answers-unit-1)- [Certifications](#certifications)- [License](#license)
## Overview
This project demonstrates the full MCP workflow:
1. **Unit 1 (Fundamentals)**: MCP architecture (Host/Client/Server), three capability types (Tools/Resources/Prompts), transport mechanisms (stdio/HTTP+SSE), JSON-RPC 2.02. **Unit 2 (Building with MCP)**: Implementing MCP clients and servers using SDKs3. **Unit 3 (Deployed Use Case)**: Building a deployed MCP application (PR agent with GitHub/Slack integration)
## Project Structure
```mcp_course_project/βββ README.mdβββ LICENSEβββ requirements.txtβββ mcp-server/β βββ server.py # MCP PR agent server (3 tools, 2 resources, 1 prompt)βββ templates/β βββ bug.mdβ βββ feature.mdβ βββ docs.mdβ βββ refactor.mdβ βββ test.mdβ βββ performance.mdβ βββ security.mdβββ quiz-answers/ βββ QUIZ_ANSWERS.md # Unit 1 quiz (5/5 correct)```
## Tools
| Tool | Description ||------|-------------|| `analyze_file_changes` | Get git diff, changed files, commits, and statistics. Supports truncation for large diffs. || `get_pr_templates` | List all available PR templates with their content. || `suggest_template` | Suggest the most appropriate PR template based on change type. |
## Resources
| Resource | Description ||----------|-------------|| `templates://list` | List all available PR templates || `config://project` | Project configuration and metadata |
## Prompts
| Prompt | Description ||--------|-------------|| `review_code` | Generate a code review prompt for a given code snippet |
## Quick Start
### 1. Install dependencies
```bashpip install -r requirements.txt```
### 2. Run the MCP server
```bashpython mcp-server/server.py```
The server uses stdio transport by default, compatible with Claude Code, Cursor, and other MCP clients.
### 3. Test with Claude Code
```bash# Add the MCP serverclaude mcp add pr-agent -- python /absolute/path/to/mcp-server/server.py
# Verify it's configuredclaude mcp list
# Use it# "Analyze my changes and suggest a PR template"```
## Usage with Claude Code
Once configured, you can ask Claude:- "Analyze my file changes and suggest a PR template"- "What PR templates are available?"- "Review this code for issues"
## Quiz Answers (Unit 1)
All 5 quiz questions with correct answers are in `quiz-answers/QUIZ_ANSWERS.md`.
**Key concepts:**- **Host**: User-facing AI application (Claude Desktop, Cursor)- **Client**: Manages 1:1 communication with an MCP Server- **Server**: Exposes tools, resources, and prompts via MCP- **MΓN Problem**: M apps Γ N tools = MΓN integrations β MCP reduces to M + N
Take the interactive quiz: https://huggingface.co/spaces/mcp-course/unit_1_quiz
## Certifications
| Certificate | Requirements | Link ||-------------|-------------|------|| **Fundamentals** | Complete Unit 1 (pass quiz β₯80%) | https://huggingface.co/spaces/mcp-course/unit_1_quiz || **Completion** | Complete Units 2 & 3 (build + deploy MCP app) | Project-based (this repo demonstrates Unit 3) |
## License
MIT License. See `LICENSE`.
## Acknowledgements
Built as the Unit 3 project of the [Hugging Face MCP Course](https://huggingface.co/learn/mcp-course),built in partnership with [Anthropic](https://www.anthropic.com). Source starter code from[huggingface/mcp-course](https://github.com/huggingface/mcp-course).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181#!/usr/bin/env python3"""MCP PR Agent Server β MCP Course (Unit 3)
A deployed MCP server that helps developers create better pull requests byanalyzing git changes and suggesting appropriate PR templates.
Built for the Hugging Face MCP Course (https://huggingface.co/learn/mcp-course).Adapted to use mcp.server.MCPServer (mcp 2.x) instead of the deprecated FastMCP."""
import jsonimport osimport subprocessfrom pathlib import Pathfrom typing import Optional
from mcp.server import MCPServer
mcp = MCPServer("pr-agent")
# PR template directoryTEMPLATES_DIR = Path(__file__).parent.parent / "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 = { "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",}
@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) """ try: cwd = working_directory if working_directory else os.getcwd()
files_result = subprocess.run( ["git", "diff", "--name-status", f"{base_branch}...HEAD"], capture_output=True, text=True, check=True, cwd=cwd, )
stat_result = subprocess.run( ["git", "diff", "--stat", f"{base_branch}...HEAD"], capture_output=True, text=True, cwd=cwd, )
diff_content = "" truncated = False total_diff_lines = 0 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") total_diff_lines = len(diff_lines)
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
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", "truncated": truncated, "total_diff_lines": total_diff_lines, }
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)})
@mcp.tool()async def get_pr_templates() -> str: """List available PR templates with their content.""" templates = [] for filename, template_type in DEFAULT_TEMPLATES.items(): template_path = TEMPLATES_DIR / filename if template_path.exists(): templates.append( { "filename": filename, "type": template_type, "content": template_path.read_text(encoding="utf-8"), } ) if not templates: return json.dumps({"error": "No templates found", "templates_dir": str(TEMPLATES_DIR)}) return json.dumps(templates, indent=2)
@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.) """ templates_response = await get_pr_templates() templates = json.loads(templates_response)
if "error" in templates: return templates_response
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], )
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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# MCP Course β Quiz Answers Reference
This file compiles the correct answers for the Unit 1 quiz (MCP Fundamentals).Use it as a study guide when taking the interactive quiz on Hugging Face.
**Quiz link:** https://huggingface.co/spaces/mcp-course/unit_1_quiz
**Passing score:** 80% or higher (EXAM_PASSING_SCORE = 0.8)
---
## Unit 1: MCP Fundamentals (5 questions)
| # | Question | Correct Answer ||---|----------|----------------|| 1 | What is the primary purpose of Model Context Protocol (MCP)? | **B** β To enable AI models to connect with external data sources, tools, and environments || 2 | What problem does MCP primarily aim to solve? | **C** β The MΓN Integration Problem || 3 | Which of the following is a key benefit of MCP? | **C** β Standardization and interoperability in the AI ecosystem || 4 | In MCP terminology, what is a "Host"? | **B** β The user-facing AI application || 5 | What does "MΓN Integration Problem" refer to in the context of AI applications? | **B** β The challenge of connecting M AI applications to N external tools without a standard |
**Score: 5/5 = 100% β
**
---
## Key Concepts (from Unit 1)
### Architecture- **Host**: The user-facing AI application (e.g., Claude Desktop, Cursor)- **Client**: Component within the host that manages communication with a specific MCP Server (1:1 connection)- **Server**: External program/service that exposes tools, resources, and prompts via MCP
### Three Capability Types1. **Tools** β Executable functions that perform actions (model-controlled, require user approval)2. **Resources** β Read-only data sources for context retrieval (application-controlled, like GET endpoints)3. **Prompts** β Predefined templates/workflows that guide interactions
### Transport Mechanisms- **stdio** β Local process communication (stdin/stdout)- **HTTP + SSE** β Remote server communication (Server-Sent Events)
### JSON-RPC 2.0MCP uses JSON-RPC 2.0 as the message format. Three message types:1. **Requests** β Client β Server (initiate operations)2. **Responses** β Server β Client (reply to requests)3. **Notifications** β One-way messages (no response needed)
### MΓN Integration ProblemWithout MCP: M AI apps Γ N data sources = MΓN custom integrationsWith MCP: M + N (write once, use everywhere)
### Key Terminology- **Sampling**: Server requests LLM interactions from the Client (human-in-the-loop)- **Dynamic Capability Discovery**: Client queries available Tools/Resources/Prompts at runtime- **Stateless transport**: Each request is independent (no session state on server)
---
## Certification
| Certificate | Requirements | Link ||-------------|-------------|------|| **Fundamentals** | Complete Unit 1 (pass quiz β₯80%) | https://huggingface.co/spaces/mcp-course/unit_1_quiz || **Completion** | Complete Units 2 & 3 (build + deploy MCP app) | (project-based, no separate quiz) |
## Project: PR Agent MCP Server
The Unit 3 project is a PR (Pull Request) agent MCP server that:- Analyzes git changes (`analyze_file_changes`)- Lists PR templates (`get_pr_templates`)- Suggests appropriate templates (`suggest_template`)
Source code: `mcp-server/server.py`Templates: `templates/` (7 templates: bug, feature, docs, refactor, test, performance, security)
### Running the server```bashpython mcp-server/server.py```
### Testing```bash# With Claude Code:claude mcp add pr-agent -- python /path/to/mcp-server/server.py```12mcp>=1.0.0huggingface_hub>=0.25.0123456789101112131415161718## Bug Fix
### Description<!-- Brief description of the bug being fixed -->
### Root Cause<!-- What caused the bug? -->
### Solution<!-- How does this PR fix the bug? -->
### Testing- [ ] Added/updated tests- [ ] Manually tested the fix- [ ] Verified no regressions
### Related IssuesFixes #<!-- issue number -->12345678910111213## Documentation Update
### Description<!-- What documentation is being updated? -->
### Changes<!-- List of specific changes made -->
### Review Checklist- [ ] Grammar and spelling checked- [ ] Technical accuracy verified- [ ] Examples tested- [ ] Links verified12345678910111213141516171819202122## New Feature
### Description<!-- Brief description of the new feature -->
### Motivation<!-- Why is this feature needed? -->
### Implementation<!-- High-level overview of the implementation -->
### Testing- [ ] Added unit tests- [ ] Added integration tests- [ ] Tested edge cases
### Documentation- [ ] Updated relevant documentation- [ ] Added usage examples
### Breaking Changes<!-- List any breaking changes -->123456789101112131415## Performance Improvement
### Description<!-- What performance issue is being addressed? -->
### Metrics<!-- Before/after performance metrics -->
### Changes<!-- Specific optimizations made -->
### Testing- [ ] Benchmarks added/updated- [ ] No functionality regression- [ ] Tested under various loads123456789101112131415161718## Code Refactoring
### Description<!-- What code is being refactored? -->
### Motivation<!-- Why is this refactoring needed? -->
### Changes<!-- List of specific refactoring changes -->
### Testing- [ ] All existing tests pass- [ ] No functional changes- [ ] Performance impact assessed
### Risk Assessment<!-- Any risks with this refactoring? -->123456789101112131415161718## Security Update
### Description<!-- Brief description of security issue (be careful not to expose vulnerabilities) -->
### Impact<!-- Who/what is affected? -->
### Solution<!-- How does this PR address the security issue? -->
### Testing- [ ] Security tests added- [ ] Penetration testing performed- [ ] No new vulnerabilities introduced
### References<!-- Link to security advisories if applicable -->12345678910111213141516## Test Update
### Description<!-- What tests are being added or updated? -->
### Coverage- Previous coverage: <!-- X% -->- New coverage: <!-- Y% -->
### Test Types- [ ] Unit tests- [ ] Integration tests- [ ] End-to-end tests
### Related Features<!-- List features/components being tested -->LICENSEAdded+21
README.mdAdded+134
mcp-server/server.pyAdded+181
quiz-answers/QUIZ_ANSWERS.mdAdded+85
requirements.txtAdded+2
templates/bug.mdAdded+18
templates/docs.mdAdded+13
templates/feature.mdAdded+22
templates/performance.mdAdded+15
templates/refactor.mdAdded+18
templates/security.mdAdded+18
templates/test.mdAdded+16