Skip to main content
Glama
abhinandanmishra1

Enhanced PR Comments Resolver MCP Server

README.md
# šŸš€ Enhanced PR Comments Resolver - MCP Server v2.1

A comprehensive Model Context Protocol (MCP) server that not only fetches GitHub PR comments but also **intelligently applies and fixes them** directly in your workspace files. This enhanced version includes smart pattern recognition, similar comment linking, and automated issue resolution capabilities optimized for Cursor IDE.

## ✨ Enhanced Features

### šŸ” **Comprehensive Comment Processing**
- Fetches all types of PR comments (issue, review, and general comments)
- Intelligent comment analysis and categorization
- Priority-based comment filtering (High/Medium/Low priority)
- Actionable vs non-actionable comment detection
- **🧠 Smart pattern recognition** across similar comments
- **šŸ”— Comment linking** for consistent fixes across files

### šŸŽÆ **Direct File Modification & Intelligent Fixing**
- **Apply comments directly to files** in your current workspace
- **šŸ¤– Automatic issue resolution** based on comment content
- **🌐 "Apply everywhere" support** for project-wide changes
- Intelligent workspace detection (Git repos, package.json, pyproject.toml, etc.)
- Safe file operations with optional automatic backups
- Batch processing of multiple comments
- Dry-run mode for testing changes
- **šŸ”§ Smart fixes for**: imports, naming, types, formatting, removal, and more

### 🧠 **Enhanced Prompt Generation**
- **Cursor IDE optimized prompts** with enhanced formatting
- Multiple format types: Cursor, JSON, Markdown, Structured
- Context-aware suggestions with file path resolution
- Intelligent action categorization (Bug Fix, Refactor, Style, etc.)
- Enhanced code context with syntax highlighting

### šŸ“ **Comment Embedding**
- Embed PR comments as hidden comments directly in source files
- Track applied suggestions with metadata
- Reference original comment URLs and authors
- Maintain audit trail of changes

### šŸ”§ **Workspace Intelligence**
- Automatic workspace root detection
- Project structure analysis
- Language detection and file type support
- Intelligent file path resolution

## šŸ›  Installation

1. **Clone or download this repository**

2. **Install dependencies using uv** (recommended):
   ```bash
   cd pr-comments-resolver
   uv sync
   ```

   Or using pip:
   ```bash
   pip install -r requirements.txt
   ```

3. **Set up GitHub token** (see GitHub Token Setup section)

## šŸ” GitHub Token Setup

### Why You Need a GitHub Token
- **Higher Rate Limits**: 5,000 requests/hour vs 60 requests/hour
- **Private Repository Access**: Access private repos with proper permissions
- **Better Error Handling**: More detailed API responses

### Getting a GitHub Token
1. Go to [GitHub Settings > Developer settings > Personal access tokens](https://github.com/settings/tokens)
2. Click "Generate new token (classic)"
3. Select scopes: `public_repo` (and `repo` for private repositories)
4. Copy the token immediately

### Setting Up the Token

#### Method 1: Environment Variable (Recommended)
```bash
export GITHUB_TOKEN="your_token_here"
```

#### Method 2: MCP Client Configuration
**For Cursor** (add to your MCP settings):
```json
{
  "mcpServers": {
    "pr-comments-resolver": {
      "command": "python",
      "args": ["/path/to/pr-comments-resolver/main.py"],
      "env": {
        "GITHUB_TOKEN": "your_token_here"
      }
    }
  }
}
```

## šŸš€ Quick Start

### ⚔ ONE-CLICK WORKFLOW (RECOMMENDED) ✨ NEW!
```python
# Complete everything in one go - no redundant API calls!
complete_pr_workflow("https://github.com/owner/repo/pull/123", dry_run=True)

# Apply everything after preview
complete_pr_workflow("https://github.com/owner/repo/pull/123", dry_run=False)
```

**This unified tool:**
- šŸ“ Sets up workspace automatically  
- šŸ“„ Fetches PR comments (with smart caching)
- šŸ“ Embeds comments in files
- šŸ”§ Intelligently fixes all issues
- šŸ”— Links similar patterns across files
- 🌐 Applies "everywhere" comments to all PR files

### šŸ”§ INDIVIDUAL TOOLS (If you need granular control)

#### Step 1: Embed PR Comments
```python
# In Cursor IDE, use the MCP tool to embed comments in files
resolve_pr_comments("https://github.com/owner/repo/pull/123", dry_run=True)
```

#### Step 2: Intelligent Fix & Check
```python
# Automatically check and fix issues mentioned in comments
check_and_fix_applied_comments("https://github.com/owner/repo/pull/123", dry_run=True)

# Apply the fixes
check_and_fix_applied_comments("https://github.com/owner/repo/pull/123", dry_run=False)
```

#### Step 3: Focus on Specific Files
```python
# Check and fix comments for a specific file
check_specific_file_comments("https://github.com/owner/repo/pull/123", "src/components/Button.tsx", dry_run=False)
```

### What You Get
The system will automatically:
- **šŸŽÆ Embed comments** at the right locations in your code
- **šŸ”— Detect similar patterns** across multiple comments 
- **🧠 Apply fixes intelligently** based on comment content
- **🌐 Handle "everywhere" comments** across all PR files
- **šŸ”„ Link related comments** for consistent fixes

**Example embedded comment:**
```javascript
/**
 * PR Comment from @reviewer: you can use theme token here
 * Comment ID: 123456
 * Line: ~42
 */
const color = '#ff0000';  // ← This will be automatically fixed!
```

**After running `check_and_fix_applied_comments`:**
```javascript
const color = theme.colors.primary;  // ← Automatically fixed!
```

## šŸŽ® Usage

### Running the MCP Server
```bash
python main.py
```

### Available Tools

#### šŸ” **Core Functionality**

##### `detect_workspace`
Automatically detect and analyze your current workspace.
```json
{
  "tool": "detect_workspace",
  "arguments": {}
}
```

##### `set_workspace_path`
Set a custom workspace path for file operations.
```json
{
  "tool": "set_workspace_path",
  "arguments": {
    "workspace_path": "/path/to/your/project"
  }
}
```

##### `fetch_pr_comments_tool`
Fetch all comments from a GitHub PR with enhanced processing.
```json
{
  "tool": "fetch_pr_comments_tool",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123"
  }
}
```

##### `complete_pr_workflow` šŸš€ NEW! (RECOMMENDED)
Complete PR comment resolution workflow in one step with smart caching.
```json
{
  "tool": "complete_pr_workflow",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123",
    "workspace_path": "/optional/custom/path",
    "dry_run": true
  }
}
```

**What it does:**
- šŸ“ Sets up workspace (auto-detected or custom)
- šŸ“„ Fetches PR comments (with 5min smart caching)
- šŸ“ Embeds comments in files at correct locations
- šŸ”§ Intelligently fixes all detected issues
- šŸ”— Links similar comments for consistent fixes
- 🌐 Applies "everywhere" comments across all PR files

##### `resolve_pr_comments` ✨ NEW!
Embed PR comments directly in your source files at specific locations.
```json
{
  "tool": "resolve_pr_comments",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123",
    "dry_run": true
  }
}
```

##### `check_and_fix_applied_comments` ✨ NEW!
Intelligently check and fix issues mentioned in PR comments after they're applied.
```json
{
  "tool": "check_and_fix_applied_comments",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123",
    "dry_run": true
  }
}
```

**Features:**
- šŸ”— Links similar comments across files
- 🌐 Applies "everywhere" comments to all PR files  
- 🧠 Intelligent pattern recognition and fixing
- šŸŽÆ Handles imports, naming, types, formatting, and more

##### `check_specific_file_comments` ✨ NEW!
Check and fix comments for a specific file.
```json
{
  "tool": "check_specific_file_comments",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123",
    "file_path": "src/components/Button.tsx",
    "dry_run": true
  }
}
```

#### šŸ› ļø **Utility Tools**

##### `clear_pr_cache` ✨ NEW!
Clear cached PR comments data to force fresh API calls.
```json
{
  "tool": "clear_pr_cache",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123"
  }
}
```

**Cache Features:**
- šŸ“‹ Smart caching with 5-minute TTL
- šŸ—‘ļø Clear specific PR cache or all cached data
- ⚔ Eliminates redundant API calls within the same session
- šŸ”„ Automatic cache invalidation

#### šŸŽÆ **Enhanced Prompt Generation**

##### `generate_cursor_prompt`
Generate optimized prompts for Cursor IDE with intelligent formatting.
```json
{
  "tool": "generate_cursor_prompt",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123",
    "format_type": "cursor"
  }
}
```

**Format Types:**
- `"cursor"` - Optimized for Cursor IDE with enhanced formatting
- `"json"` - Structured JSON format for automated processing
- `"markdown"` - Clean markdown format for documentation
- `"structured"` - Advanced structured format with metadata

#### šŸ”§ **Direct File Modification**

##### `apply_pr_comments`
Apply all actionable PR comments directly to your workspace files.
```json
{
  "tool": "apply_pr_comments",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123",
    "dry_run": true
  }
}
```

##### `apply_single_comment`
Apply a specific comment to a file.
```json
{
  "tool": "apply_single_comment",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123",
    "comment_id": "987654321",
    "dry_run": false
  }
}
```

#### šŸ“ **Comment Integration**

##### `embed_comments_in_files`
Embed PR comments as hidden comments directly in source files.
```json
{
  "tool": "embed_comments_in_files",
  "arguments": {
    "pr_url": "https://github.com/owner/repo/pull/123"
  }
}
```

##### `get_file_context`
Get enhanced context around specific lines in files.
```json
{
  "tool": "get_file_context",
  "arguments": {
    "file_path": "src/main.py",
    "line_number": 42,
    "context_lines": 10
  }
}
```

## šŸŽÆ Intelligent Comment Processing

### Comment Categorization
The server automatically categorizes comments by:

- **Priority Levels**: šŸ”“ HIGH, 🟔 MEDIUM, 🟢 LOW, ⚪ REVIEW
- **Action Types**: šŸ› BUG_FIX, šŸ”§ REFACTOR, āž• ADD_FEATURE, āž– REMOVE, šŸŽØ STYLE, ⚔ OPTIMIZE, šŸ’­ DISCUSS

### Supported Actions
- Variable/function renaming
- Import statement additions
- Typo corrections
- Docstring additions
- Type hint improvements
- Code removal/cleanup
- Style formatting

## šŸ“Š Example Workflows

### 1. Quick PR Review Analysis
```bash
# 1. Detect workspace
detect_workspace()

# 2. Generate Cursor-optimized prompt
generate_cursor_prompt("https://github.com/owner/repo/pull/123", "cursor")

# 3. Review the generated prompt in Cursor
```

### 2. Apply Comments to Workspace
```bash
# 1. Test changes with dry run
apply_pr_comments("https://github.com/owner/repo/pull/123", dry_run=true)

# 2. Apply actual changes
apply_pr_comments("https://github.com/owner/repo/pull/123", dry_run=false)

# 3. Embed comments for reference
embed_comments_in_files("https://github.com/owner/repo/pull/123")
```

### 3. Selective Comment Application
```bash
# 1. Fetch all comments
fetch_pr_comments_tool("https://github.com/owner/repo/pull/123")

# 2. Apply specific high-priority comment
apply_single_comment("https://github.com/owner/repo/pull/123", "comment_id", false)
```

## šŸ”’ Safety Features

### File Safety
- **Automatic Backups**: Creates timestamped backups before modifications
- **Dry Run Mode**: Test changes without modifying files
- **Error Recovery**: Graceful handling of file operation errors
- **Encoding Detection**: Handles multiple file encodings safely

### Change Validation
- **Syntax Preservation**: Maintains code syntax and structure
- **Incremental Changes**: Makes focused, atomic modifications
- **Change Tracking**: Adds metadata comments for audit trails
- **Rollback Support**: Easy restoration from backups

## šŸŽØ Enhanced Cursor Integration

The generated prompts are specifically optimized for Cursor IDE with:

- **Visual Hierarchy**: Enhanced formatting with emojis and structure
- **Code Context**: Syntax-highlighted code blocks with line numbers
- **Action Guidance**: Step-by-step implementation instructions
- **Priority Indicators**: Clear visual priority and action type indicators
- **File Navigation**: Direct file paths and line number references

## šŸ“ˆ Response Format

All tools return comprehensive JSON responses with:

```json
{
  "success": true,
  "workspace_path": "/path/to/workspace",
  "pr_info": {
    "owner": "username",
    "repo": "repository",
    "pr_number": 123,
    "url": "https://github.com/username/repository/pull/123"
  },
  "results": {
    "total_comments": 15,
    "actionable_comments": 8,
    "successful": 6,
    "failed": 0,
    "skipped": 2
  },
  "details": [...]
}
```

## šŸ›  Development

### Project Structure
```
pr-comments-resolver/
ā”œā”€ā”€ main.py                    # Enhanced MCP server with all tools
ā”œā”€ā”€ modules/
│   ā”œā”€ā”€ __init__.py           # Module initialization
│   ā”œā”€ā”€ prompt_generator.py   # Enhanced prompt generation
│   └── file_manager.py       # Workspace and file operations
ā”œā”€ā”€ pyproject.toml            # Dependencies and project config
ā”œā”€ā”€ README.md                 # This file
└── uv.lock                   # Dependency lock file
```

### Dependencies
- `httpx` - Async HTTP client for GitHub API
- `mcp[cli]` - Model Context Protocol framework
- `aiofiles` - Async file operations
- `pathlib2` - Enhanced path handling (Python < 3.11)

### Development Setup
```bash
# Install development dependencies
uv sync --dev

# Run linting
black .
flake8 .
mypy .

# Run tests
pytest
```

## šŸ”„ Migration from v1.0

If you're upgrading from the basic version:

1. **Backup your current setup**
2. **Update dependencies**: `uv sync`
3. **New tools available**: All file modification and prompt generation tools
4. **Enhanced responses**: More detailed JSON responses with workspace context
5. **Workspace detection**: Automatic detection replaces manual path setting

## šŸ¤ Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes with tests
4. Ensure code quality (black, flake8, mypy)
5. Submit a pull request

## šŸ“„ License

This project is open source. Please check the license file for details.

## šŸ†˜ Troubleshooting

### Common Issues

**Workspace not detected**
```bash
# Manually set workspace path
set_workspace_path("/path/to/your/project")
```

**File not found errors**
- Ensure you're running from the correct directory
- Check file paths are relative to workspace root
- Verify files exist in the detected workspace

**Permission errors**
- Ensure write permissions in workspace directory
- Check GitHub token has appropriate repository permissions

**Rate limiting**
- Set up GitHub token for higher limits
- Implement delays between batch operations

### Debug Mode
Enable detailed logging by setting environment variable:
```bash
export LOG_LEVEL=DEBUG
python main.py
```

## šŸš€ What's New in v2.0

- āœ… **Direct file modification** with intelligent change application
- āœ… **Enhanced Cursor prompts** with visual formatting and context
- āœ… **Workspace intelligence** with automatic detection
- āœ… **Comment embedding** in source files for reference
- āœ… **Batch processing** with progress tracking
- āœ… **Safety features** including backups and dry-run mode
- āœ… **Modular architecture** for easier maintenance
- āœ… **Comprehensive error handling** and validation
- āœ… **Multiple prompt formats** for different use cases
- āœ… **Enhanced metadata** and tracking capabilities

Transform your PR review workflow with intelligent automation! šŸŽ‰