bitbucket-mcp-tutorial

shibyan-ai-engineer/bitbucket-mcp-tutorial

3.3

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

  1. 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
  2. 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

  1. User Request: "Review the latest PR in my repository"
  2. AI Assistant: Parses request and calls MCP tools
  3. MCP Server: Processes tool calls using Bitbucket API
  4. Bitbucket API: Returns repository and PR data
  5. MCP Server: Formats response for AI assistant
  6. AI Assistant: Presents intelligent analysis to user

๐Ÿ› ๏ธ Available Tools & Resources

๐Ÿ”ง Tools (11 total)

ToolPurposeParameters
list_repositoriesList user repositoriesrole (admin/member/contributor)
get_repository_infoGet repo detailsrepo_slug
list_pull_requestsList PRsrepo_slug, state
get_pull_request_infoGet PR detailsrepo_slug, pr_id
get_pull_request_diffGet PR code diffrepo_slug, pr_id
add_pr_commentAdd PR commentrepo_slug, pr_id, content
approve_prApprove PRrepo_slug, pr_id
unapprove_prRemove approvalrepo_slug, pr_id
merge_prMerge PRrepo_slug, pr_id, merge_strategy
decline_prDecline PRrepo_slug, pr_id, reason
get_pr_commentsGet PR commentsrepo_slug, pr_id

๐Ÿ“‚ Resources (4 total)

ResourceURI PatternPurpose
Repositoriesbitbucket://repositoriesList all repositories
Repositorybitbucket://repo/{repo_slug}Specific repository data
Pull Requestsbitbucket://repo/{repo_slug}/pullrequestsRepository's PRs
PR Commentsbitbucket://pr/{repo_slug}/{pr_id}/commentsPR 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

  1. Explore the Code: Read through mcp_server.py with educational comments
  2. Try Live Examples: Use your configured AI assistant to interact with repositories
  3. Extend Functionality: Add new tools for issues, branches, or commits
  4. 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

โ€ข โ€ข