shibyan-ai-engineer/bitbucket-mcp-tutorial
If you are the rightful owner of bitbucket-mcp-tutorial and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
The Bitbucket MCP Server is a comprehensive solution for integrating AI-powered code review bots with Bitbucket repositories, leveraging the Model Context Protocol (MCP) to enhance development workflows.
๐ค Bitbucket MCP Server Tutorial
๐ 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.
โญ Why This Tutorial?
- ๐ฏ 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
๐ฏ What You'll Learn
- 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
๐ What This Server Does
Transform your AI assistant into a powerful development companion that can:
๐ง Repository Management
- ๐ List and explore Bitbucket repositories with intelligent filtering
- ๐ Get detailed repository analytics and metadata
- ๐ Access repository data through MCP resources for complex queries
๐ Pull Request Automation
- ๐ 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
๐ค AI-Powered Code Review
- ๐ 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!
๐ Prerequisites
- 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)
๐๏ธ Project Structure (Tutorial-Ready)
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
โก Quick Start (5 Minutes)
1. Clone and Setup
git clone <your-repo-url>
cd bitbucket-mcp-tutorial
pip install -r requirements.txt
2. Configure Environment
cp .env.example .env
# Edit .env with your Bitbucket credentials
3. Test the Server
python test_mcp_server.py --quick
4. Configure AI Assistants
python config_helper.py
๐ง Detailed Setup Guide
Step 1: Python Environment Setup
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
Step 2: Bitbucket API Configuration
-
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
Step 3: Test Your Setup
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!
Step 4: Configure AI Assistants
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.
๐ Understanding the Code
Core Components
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
Key Tools Explained
# 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...
Resources Explained
# 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...
๐ Integration with AI Assistants
Claude Desktop Integration
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"
}
}
}
}
Cursor Integration
After running python config_helper.py --cursor
, add the generated configuration to Cursor settings.
๐ Architectural Overview
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ AI Assistant โ โ MCP Server โ โ Bitbucket โ
โ โ โ โ โ โ
โ Claude Desktop โโโโโบโ 11 Tools โโโโโบโ REST API โ
โ Cursor โ โ 4 Resources โ โ Repositories โ
โ โ โ FastMCP โ โ Pull Requests โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
Data Flow
- 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
๐ ๏ธ Available Tools & Resources
๐ง Tools (11 total)
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 |
๐ Resources (4 total)
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 |
๐ช Live Demo Usage Examples
๐ฅ AI-Powered Code Review in Action
๐ค 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"
๐ฏ Repository Exploration
๐ค 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
...
๐ Troubleshooting
Common Issues
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
Debug Mode
Run with debug logging:
FASTMCP_DEBUG=1 python mcp_server.py
Run tests with verbose output:
python test_mcp_server.py --verbose
๐ Learning Resources
Next Steps
- 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.)
Additional Documentation
docs/ARCHITECTURE.md
- Detailed system design and technical overview
External Resources
๐ค Contributing
This tutorial project welcomes improvements! Star โญ this repo if it helped you build amazing AI-powered development tools!
๐ฏ Areas for Contribution:
- ๐ง 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! ๐
๐ License
MIT License - Feel free to use this tutorial for learning, teaching, and building awesome AI tools!
โญ Love this project? Give it a star!
๐ฏ 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
โข โข