MCP tool to guide Python code refactoring without automatic changes
Project description
MCP Python Refactoring
A Model Context Protocol (MCP) server that analyzes Python code and provides guided refactoring suggestions without automatically modifying your code.
This tool integrates with AI coding assistants (Claude, ChatGPT, Cursor, etc.) to provide intelligent refactoring guidance. Instead of making automatic code changes, it gives you precise instructions on how to improve your Python code, acting as your refactoring mentor.
What This Tool Does
For AI Coding Assistants:
- Provides structured JSON responses with refactoring opportunities
- Identifies long functions, high complexity code, and dead code
- Gives precise line numbers for extract method refactoring
- Uses professional tools for comprehensive analysis
For Developers:
- Get step-by-step refactoring instructions
- Maintain full control over code changes
- Learn refactoring patterns through guided practice
- Improve code quality systematically
How It Differs
| Approach | This Tool | Traditional Refactoring Tools |
|---|---|---|
| Integration | Works with any LLM/AI assistant | IDE-specific or standalone |
| Guidance | Step-by-step instructions with line numbers | Automatic changes only |
| Learning | Educational approach teaches patterns | No learning component |
| Control | Developer maintains full control | Tool makes all decisions |
Installation
Quick Start with uvx (Recommended)
# Install and run directly from GitHub
uvx --from git+https://github.com/slamer59/mcp-python-refactoring.git mcp-python-refactoring
Development Installation
# Clone and setup for development
git clone https://github.com/slamer59/mcp-python-refactoring.git
cd mcp-python-refactoring
uv sync
Manual Installation
# Core dependencies
uv add rope radon vulture jedi libcst mccabe mcp
# SSE support (optional)
uv add fastapi uvicorn
Available MCP Tools
Unified Server
Single Server (mcp_server.py): Both guide-only and apply-changes modes in one server
Connection Options:
- stdin/stdout:
python mcp_server.py(default) - SSE (Server-Sent Events):
python mcp_server.py --sse [port](web-based)
Tools
1. analyze_python_code
Comprehensive analysis with optional automatic refactoring.
Parameters:
content(required): Python file content as stringmode(optional): "guide_only" (default) or "apply_changes"file_path(optional): Path to the file for contextline_threshold(optional): Minimum lines for long functions (default: 20)
Mode: guide_only - Returns instructions only Mode: apply_changes - Returns modified code
2. extract_function
Extract specific functions with guide or apply mode.
Parameters:
content(required): Python file contentmode(optional): "guide_only" or "apply_changes"function_name(optional): Specific function to targetstart_line,end_line(for apply_changes): Exact extraction rangenew_function_name(for apply_changes): Name for extracted function
3. quick_analyze
Fast analysis for immediate refactoring opportunities.
Parameters:
content(required): Python file content
Returns: Quick summary of long functions and parameter issues
Analysis Capabilities
Code Quality Issues Detected:
- Functions over 20 lines (extract method opportunities)
- High cyclomatic complexity (>10)
- Functions with too many parameters (>5)
- Dead/unused code (consolidated suggestions)
- Low maintainability index (<20)
Additional Analysis Tools:
- Security Analysis: Vulnerability detection and security best practices
- Performance Analysis: Bottleneck identification and optimization suggestions
- Type Hints: Missing type annotation detection
- Documentation: Docstring coverage and quality assessment
Professional Tools Used:
- Rope: Professional refactoring analysis
- Radon: Code complexity metrics
- Vulture: Dead code detection
- Jedi: Semantic code analysis
- LibCST: Syntax tree manipulation
Testing and Debugging
Test with MCP Inspector
# Launch MCP Inspector
bunx @modelcontextprotocol/inspector
# In the web interface:
# Command: python
# Args: mcp_server.py
# Working Directory: /path/to/your/project
Test Both Modes in Inspector:
Guide Mode Test:
{
"content": "def long_function():\n print('line1')\n # ... 20+ lines",
"mode": "guide_only"
}
Apply Mode Test:
{
"content": "def long_function():\n print('line1')\n # ... 20+ lines",
"mode": "apply_changes"
}
Test with Bun (Fastest)
# Install Bun if not available
curl -fsSL https://bun.sh/install | bash
# Install MCP SDK
bun install -g @modelcontextprotocol/sdk
# Run tests
export PATH=.venv/bin:$PATH && bun run test_unified.js
Test Standalone (No MCP)
# Simple Python test
python test_tool.py
# Test with example file
python mcp_server.py examples/example_code.py
Debug Server Issues
# Check dependencies
uv sync
# Verify MCP imports
python -c "import mcp; print('MCP available')"
# Test individual tools
python -c "
from src.mcp_refactoring_assistant.server import EnhancedRefactoringAnalyzer
analyzer = EnhancedRefactoringAnalyzer()
print('Analyzer working')
"
Example Usage
Educational Workflow
- AI assistant calls
analyze_python_codewithguide_onlymode - Tool returns structured suggestions with precise steps
- Developer follows step-by-step instructions
- Developer learns refactoring patterns through practice
Productivity Workflow
- AI assistant calls
analyze_python_codewithapply_changesmode - Tool returns modified code with applied refactorings
- Developer reviews changes and applies as needed
- Faster refactoring for experienced developers
Sample MCP Response (Guide Mode)
{
"analysis_summary": {
"total_issues_found": 2,
"medium_priority": 1,
"low_priority": 1
},
"refactoring_guidance": [
{
"issue_type": "extract_function",
"location": "Function 'process_data' lines 45-78",
"description": "Long function (34 lines) with extractable blocks",
"precise_steps": [
"SELECT lines 45-52 (validation block)",
"CREATE function: validate_input(data)",
"REPLACE with: is_valid = validate_input(data)"
]
},
{
"issue_type": "dead_code",
"location": "Multiple locations (6 items)",
"description": "6 unused items found",
"precise_steps": [
"Review all unused items listed below:",
"• Line 11: Unused import 're'",
"• Line 12: Unused import 'Optional'",
"Verify each item is truly unused",
"Remove confirmed unused code"
]
}
]
}
Integration with Coding Assistants
Claude Code/CLI
Add to your MCP configuration:
{
"servers": {
"python-refactoring": {
"command": "python",
"args": ["path/to/mcp_server.py"]
}
}
}
Claude Desktop
Add to claude_desktop_config.json:
{
"mcpServers": {
"python-refactoring": {
"command": "python",
"args": ["path/to/mcp_server.py"]
}
}
}
Cline (VSCode Extension)
In VSCode settings or .vscode/settings.json:
{
"cline.mcpServers": {
"python-refactoring": {
"command": "python",
"args": ["path/to/mcp_server.py"]
}
}
}
Cursor
Add to Cursor's MCP configuration:
{
"mcpServers": {
"python-refactoring": {
"command": "python",
"args": ["path/to/mcp_server.py"]
}
}
}
Continue (VSCode Extension)
In ~/.continue/config.json:
{
"mcpServers": [
{
"name": "python-refactoring",
"command": "python",
"args": ["path/to/mcp_server.py"]
}
]
}
Windsurf
Add to Windsurf MCP configuration:
{
"servers": {
"python-refactoring": {
"command": "python",
"args": ["path/to/mcp_server.py"]
}
}
}
Aider
Use with MCP bridge or direct integration:
aider --mcp-server "python path/to/mcp_server.py"
OpenHands (formerly OpenDevin)
In OpenHands configuration:
mcp_servers:
python-refactoring:
command: python
args: ["path/to/mcp_server.py"]
Roo-Code
Add to Roo-Code's MCP settings:
{
"mcpServers": {
"python-refactoring": {
"command": "python",
"args": ["path/to/mcp_server.py"]
}
}
}
Codex CLI
Add to ~/.codex/config.toml:
[mcp_servers.python-refactoring]
command = "python"
args = ["path/to/mcp_server.py"]
Terminal-based clients
For most terminal-based MCP clients:
# With uvx
client-name --mcp-server "uvx --from git+https://github.com/slamer59/mcp-python-refactoring.git mcp-python-refactoring"
# With local installation
client-name --mcp-server "python /path/to/mcp_server.py"
SSE Mode (Web-based clients)
For web-based clients that support SSE connections:
- Start the server in SSE mode:
python mcp_server.py --sse 3001
- Configure your client to connect to:
http://localhost:3001/sse
Using with mcpo (ChatGPT and others)
For clients without native MCP support:
# Install mcpo
pip install mcpo
# Bridge MCP to OpenAI-compatible API
mcpo --mcp-server "python path/to/mcp_server.py" --port 8080
Then configure your client to use http://localhost:8080 as API endpoint.
Notes
- Replace
path/to/mcp_server.pywith the actual absolute path to your server - For uvx installation, use the full uvx command instead of local paths
- Some clients may require additional configuration or have different syntax
- Always use absolute paths to avoid configuration issues
- Test the connection with the client's MCP debugging tools if available
How It Works
- Analysis: Server analyzes Python code using multiple professional tools
- Detection: Identifies specific refactoring opportunities with metrics
- Guidance: Provides precise line numbers and step-by-step instructions
- Integration: AI assistant interprets results and guides developer
- Control: Developer maintains full control over all code changes
User Feedback
Users report significant improvements in code quality understanding and refactoring skills when using this tool with AI assistants. The guided approach helps developers learn refactoring patterns while maintaining control over code changes.
"Finally, a tool that teaches me refactoring instead of doing it for me"
"The precise line numbers make it easy to follow the suggestions"
"Game changer for working with legacy code"
Troubleshooting
MCP Connection Issues:
- Ensure all dependencies installed:
uv sync - Check Python path:
which python - Verify MCP import:
python -c "import mcp"
Analysis Not Working:
- Test analyzer directly:
python test_tool.py - Check file permissions
- Verify example file exists:
ls examples/
Tool Responses Empty:
- Check if code has functions to analyze (minimum complexity threshold)
- Increase line threshold for testing:
"line_threshold": 10 - Verify file syntax is valid Python
- Ensure virtual environment is activated
SSE Connection Issues:
- Verify port is not in use:
netstat -an | grep 3001 - Check firewall settings for local connections
- Ensure FastAPI and Uvicorn are installed:
uv add fastapi uvicorn
Performance Issues:
- For large codebases (>100 files), consider using file-specific analysis
- Increase timeout settings in MCP client configuration
- Use
quick_analyzefor immediate feedback on specific functions
License
MIT License - Free for personal and commercial use.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mcp_python_refactoring-0.1.0.tar.gz.
File metadata
- Download URL: mcp_python_refactoring-0.1.0.tar.gz
- Upload date:
- Size: 22.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d9b2bd4c68b59d657492b9663476803127f4c1267b87aab28cb93c4c2d2ceaa0
|
|
| MD5 |
0130226a659c71338004c9c617e1040f
|
|
| BLAKE2b-256 |
25da80fc573923e28ce1789b356c5523d6948e5e444b2a137d8a827928eb6bff
|
Provenance
The following attestation bundles were made for mcp_python_refactoring-0.1.0.tar.gz:
Publisher:
publish.yml on slamer59/mcp-python-refactoring
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mcp_python_refactoring-0.1.0.tar.gz -
Subject digest:
d9b2bd4c68b59d657492b9663476803127f4c1267b87aab28cb93c4c2d2ceaa0 - Sigstore transparency entry: 453826019
- Sigstore integration time:
-
Permalink:
slamer59/mcp-python-refactoring@07ce0921dd9ce0e7bfe5e8ae041dbef04ebfa2e6 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/slamer59
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@07ce0921dd9ce0e7bfe5e8ae041dbef04ebfa2e6 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file mcp_python_refactoring-0.1.0-py3-none-any.whl.
File metadata
- Download URL: mcp_python_refactoring-0.1.0-py3-none-any.whl
- Upload date:
- Size: 14.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5ca0ef4300eb520a66e83e988c0f9edf3fd177a5a37555abf2d4f9464fe29ca8
|
|
| MD5 |
d83750ffc53fa1b42ba0917a904a4725
|
|
| BLAKE2b-256 |
8936761cd5a30899c33d8e73ff1338f74af12af1a7c45d29d71d37114fc2d2f6
|
Provenance
The following attestation bundles were made for mcp_python_refactoring-0.1.0-py3-none-any.whl:
Publisher:
publish.yml on slamer59/mcp-python-refactoring
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mcp_python_refactoring-0.1.0-py3-none-any.whl -
Subject digest:
5ca0ef4300eb520a66e83e988c0f9edf3fd177a5a37555abf2d4f9464fe29ca8 - Sigstore transparency entry: 453826021
- Sigstore integration time:
-
Permalink:
slamer59/mcp-python-refactoring@07ce0921dd9ce0e7bfe5e8ae041dbef04ebfa2e6 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/slamer59
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@07ce0921dd9ce0e7bfe5e8ae041dbef04ebfa2e6 -
Trigger Event:
workflow_dispatch
-
Statement type: