Skip to content

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.

License

Notifications You must be signed in to change notification settings

shibyan-ai-engineer/bitbucket-mcp-tutorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– Bitbucket MCP Server Tutorial

License: MIT Python 3.8+ FastMCP PRs Welcome

πŸš€ 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 https://github.com/shibyan-ai-engineer/bitbucket-mcp-tutorial
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)

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

  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

⭐ Star this repo β€’ πŸ› Report Issues β€’ πŸ’‘ Request Features

About

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.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages