π Build AI-powered code review bots that integrate with your Bitbucket workflow!
A comprehensive tutorial for building a Model Context Protocol (MCP) server that connects AI assistants like Claude Desktop and Cursor to Bitbucket repositories for intelligent code review and repository management.
- π― Production-Ready: Complete server with 11 tools and 4 resources
- π Beginner-Friendly: Step-by-step guide with copy-paste code snippets
- π€ AI Integration: Works with Claude Desktop, Cursor, and any MCP-compatible AI
- π§ Real-World Usage: Actual PR review automation, not just API demos
- β‘ Fast Setup: Get running in under 10 minutes
- MCP Fundamentals: Understand the Model Context Protocol and how it connects AI assistants to external tools
- Server Development: Build a production-ready MCP server using FastMCP framework
- API Integration: Connect to Bitbucket's REST API for repository operations
- AI Assistant Integration: Configure Claude Desktop and Cursor to use your MCP server
Transform your AI assistant into a powerful development companion that can:
- π List and explore Bitbucket repositories with intelligent filtering
- π Get detailed repository analytics and metadata
- π Access repository data through MCP resources for complex queries
- π List, review, and analyze pull requests automatically
- π» Get detailed PR information and complete code diffs
- β‘ Manage PR workflows (approve, merge, decline) with AI reasoning
- π¬ Add intelligent comments and participate in collaborative reviews
- π Analyze code changes with context-aware suggestions
- π Identify potential issues, optimizations, and best practices
- π― Generate meaningful code review comments automatically
- π Streamline your entire review process with AI assistance
Real Example: "Hey Claude, review the latest PR in my-repo and suggest improvements" β Your AI assistant fetches the PR, analyzes the diff, and provides detailed code review feedback!
- Python 3.8+ (Python 3.9+ recommended)
- Bitbucket Account with API access
- Basic Python Knowledge (variables, functions, async/await)
- Code Editor (VS Code, Cursor, or similar)
bitbucket-mcp-tutorial/
βββ README.md # This comprehensive guide
βββ LICENSE # MIT license
βββ mcp_server.py # Main MCP server (simplified & commented)
βββ bitbucket_client.py # Bitbucket API client
βββ test_mcp_server.py # Test script to verify functionality
βββ config_helper.py # Helper for generating configurations
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variables template
βββ docs/
βββ ARCHITECTURE.md # System design and data flow
git clone https://github.com/shibyan-ai-engineer/bitbucket-mcp-tutorial
cd bitbucket-mcp-tutorial
pip install -r requirements.txt
cp .env.example .env
# Edit .env with your Bitbucket credentials
python test_mcp_server.py --quick
python config_helper.py
Option A: Using pip (Recommended for beginners)
# Create project directory
mkdir bitbucket-mcp-tutorial
cd bitbucket-mcp-tutorial
# Install dependencies
pip install -r requirements.txt
Option B: Using virtual environment (Recommended for production)
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\\Scripts\\activate
# Install dependencies
pip install -r requirements.txt
-
Create App Password:
- Go to Bitbucket β Settings β Personal settings β App passwords
- Create new app password with: Repositories (Read, Write), Pull requests (Read, Write)
- Save the generated password securely
-
Configure Environment Variables:
cp .env.example .env
Edit
.env
file:BITBUCKET_WORKSPACE=your-workspace-name BITBUCKET_USERNAME=your-username BITBUCKET_APP_PASSWORD=your-app-password
Quick Test (30 seconds):
python test_mcp_server.py --quick
Full Test (2 minutes):
python test_mcp_server.py
Expected output:
β
Successfully imported Bitbucket MCP server
β
Connected successfully!
π§ Available Tools (11): [list of all tools]
π Available Resources (4): [list of all resources]
β
All tests completed successfully!
For Claude Desktop:
python config_helper.py --claude
For Cursor:
python config_helper.py --cursor
Manual Configuration: The config helper will show you exactly what to add to your AI assistant's configuration files.
1. MCP Server (mcp_server.py
)
- FastMCP framework setup
- 11 tools for Bitbucket operations
- 4 resources for data access
- Error handling and logging
2. Bitbucket Client (bitbucket_client.py
)
- HTTP client for Bitbucket API
- Authentication handling
- Request/response processing
3. Test Script (test_mcp_server.py
)
- Comprehensive functionality testing
- Performance benchmarking
- Integration verification
# Tool 1: List Repositories
@mcp.tool
async def list_repositories(role: str = "member"):
"""List repositories by user role"""
# Implementation details...
# Tool 2: Get Repository Info
@mcp.tool
async def get_repository_info(repo_slug: str):
"""Get detailed repository information"""
# Implementation details...
# Tool 3: List Pull Requests
@mcp.tool
async def list_pull_requests(repo_slug: str, state: str = "OPEN"):
"""List pull requests with filtering"""
# Implementation details...
# Resource 1: Repositories List
@mcp.resource("bitbucket://repositories")
async def get_repositories_resource():
"""Provide access to repositories data"""
# Implementation details...
# Resource 2: Specific Repository
@mcp.resource("bitbucket://repo/{repo_slug}")
async def get_repository_resource(repo_slug: str):
"""Provide access to specific repository data"""
# Implementation details...
After running python config_helper.py --claude
, add the generated configuration to:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\\Claude\\claude_desktop_config.json
Example configuration:
{
"mcpServers": {
"bitbucket": {
"command": "python",
"args": ["/absolute/path/to/mcp_server.py"],
"env": {
"BITBUCKET_WORKSPACE": "your-workspace",
"BITBUCKET_USERNAME": "your-username",
"BITBUCKET_APP_PASSWORD": "your-app-password"
}
}
}
}
After running python config_helper.py --cursor
, add the generated configuration to Cursor settings.
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β AI Assistant β β MCP Server β β Bitbucket β
β β β β β β
β Claude Desktop βββββΊβ 11 Tools βββββΊβ REST API β
β Cursor β β 4 Resources β β Repositories β
β β β FastMCP β β Pull Requests β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
- User Request: "Review the latest PR in my repository"
- AI Assistant: Parses request and calls MCP tools
- MCP Server: Processes tool calls using Bitbucket API
- Bitbucket API: Returns repository and PR data
- MCP Server: Formats response for AI assistant
- AI Assistant: Presents intelligent analysis to user
Tool | Purpose | Parameters |
---|---|---|
list_repositories |
List user repositories | role (admin/member/contributor) |
get_repository_info |
Get repo details | repo_slug |
list_pull_requests |
List PRs | repo_slug , state |
get_pull_request_info |
Get PR details | repo_slug , pr_id |
get_pull_request_diff |
Get PR code diff | repo_slug , pr_id |
add_pr_comment |
Add PR comment | repo_slug , pr_id , content |
approve_pr |
Approve PR | repo_slug , pr_id |
unapprove_pr |
Remove approval | repo_slug , pr_id |
merge_pr |
Merge PR | repo_slug , pr_id , merge_strategy |
decline_pr |
Decline PR | repo_slug , pr_id , reason |
get_pr_comments |
Get PR comments | repo_slug , pr_id |
Resource | URI Pattern | Purpose |
---|---|---|
Repositories | bitbucket://repositories |
List all repositories |
Repository | bitbucket://repo/{repo_slug} |
Specific repository data |
Pull Requests | bitbucket://repo/{repo_slug}/pullrequests |
Repository's PRs |
PR Comments | bitbucket://pr/{repo_slug}/{pr_id}/comments |
PR comments |
π€ You: "Review the latest PR in my-webapp-project"
π€ AI Assistant:
β
Found PR #42: "Add user authentication system"
π Analyzing 15 changed files, 342 additions, 89 deletions...
π Code Review Summary:
β’ Strong implementation of JWT authentication
β’ Potential security issue: password validation needs strengthening
β’ Suggest adding rate limiting to login endpoint
β’ Missing unit tests for auth middleware
β’ Database migration looks good
π¬ Posted detailed review comment with specific line suggestions!
π€ You: "What repositories need urgent attention?"
π€ AI Assistant:
π Analyzed 12 repositories across your workspace:
π¨ High Priority:
β’ "mobile-app" - 3 open PRs over 2 weeks old
β’ "api-service" - Security vulnerability in dependencies
β οΈ Medium Priority:
β’ "frontend-dashboard" - 1 large PR awaiting review
β’ "data-pipeline" - No recent activity, stale issues
β
All Good:
β’ "docs-site", "config-service", "monitoring-tools"
π€ You: "What repositories do I have access to in the mobile team workspace?"
π€ AI Assistant: Found 8 repositories with 'mobile' relevance:
π± "ios-app" (Swift) - 2.3MB, updated 2 days ago
π€ "android-app" (Kotlin) - 5.1MB, updated yesterday
π§ "mobile-api" (Python) - 1.8MB, updated 3 hours ago
...
1. Import Errors
# Error: ModuleNotFoundError: No module named 'fastmcp'
# Solution: Install dependencies
pip install -r requirements.txt
2. Authentication Errors
# Error: Unauthorized (401)
# Solution: Check .env file configuration
python config_helper.py --test-auth
3. Server Connection Issues
# Error: Connection refused
# Solution: Test server locally first
python test_mcp_server.py --quick
Run with debug logging:
FASTMCP_DEBUG=1 python mcp_server.py
Run tests with verbose output:
python test_mcp_server.py --verbose
- Explore the Code: Read through
mcp_server.py
with educational comments - Try Live Examples: Use your configured AI assistant to interact with repositories
- Extend Functionality: Add new tools for issues, branches, or commits
- Build Your Own: Create MCP servers for other APIs (GitHub, GitLab, etc.)
docs/ARCHITECTURE.md
- Detailed system design and technical overview
This tutorial project welcomes improvements! Star β this repo if it helped you build amazing AI-powered development tools!
- π§ Additional Bitbucket API integrations (Issues, Deployments, Pipelines)
- π‘οΈ Enhanced error handling and retry mechanisms
- π§ͺ More comprehensive test coverage
- π Documentation improvements and translations
- π‘ Example use cases and AI prompting strategies
- π Integration guides for other AI assistants
Join our community of AI-powered developers! π
MIT License - Feel free to use this tutorial for learning, teaching, and building awesome AI tools!
π― Ready to revolutionize your code review process? Run python test_mcp_server.py --quick
to get started!
Built with β€οΈ for the AI-powered development community
β Star this repo β’ π Report Issues β’ π‘ Request Features