npm package: @gohcltech/bitbucket-mcp
Description: Bitbucket integration for Claude via Model Context Protocol
Author: Health Care Logistics, Inc.
Latest version: 2.1.3

# Bitbucket MCP Server

A comprehensive Model Context Protocol (MCP) server that enables Claude to interact with Bitbucket Cloud repositories through simple token-based authentication. Provides full repository management, pull request workflows, branch operations, commit analysis, and issue tracking capabilities.

## ✨ v2.1 Key Features

- 🔑 **Simple Token Authentication** - API Token or Repository Access Token (no OAuth complexity)
- 🛠️ **6 Consolidated MCP Tools** - Complete Bitbucket API integration with action-based routing (46 total actions)
- 📁 **Repository Management** - Full CRUD operations for repositories
- 🌿 **Branch Operations** - Git Flow support with branching model integration
- 🔄 **Pull Request Workflows** - Complete code review lifecycle with approvals and comments
- 📊 **Commit Analysis** - History tracking, diffs, and patch generation
- 🐛 **Issue Tracking** - Comprehensive issue management with project organization
- 📝 **Type-Safe** - Full TypeScript implementation with Zod validation
- 🚀 **High Performance** - Rate limiting and optimized connection pooling
- 📄 **File-Based Logging** - Structured logging to files (no web server overhead)
- 🎯 **Action-Based Routing** - Single tool per category with action parameter for cleaner API

## 🚀 Quick Start

### Prerequisites

- Node.js 18+
- Bitbucket Cloud account
- Claude Desktop, Web, or API access

### Installation

```bash
# Clone the repository
git clone https://bitbucket.org/gohcl/bitbucket-mcp.git
cd bitbucket-mcp

# Install dependencies
npm install

# Build the project
npm run build
```

### Authentication Setup

**Choose ONE of the following authentication methods:**

#### Method 1: API Token (Recommended - Full Access)

1. **Generate API Token**:
   - Go to [Bitbucket Personal Settings → API tokens](https://bitbucket.org/account/settings/api-tokens/)
   - Click "Create API token"
   - Give it a descriptive label (e.g., "Claude MCP Server")
   - Select permissions: **Repositories (Read/Write)**, **Pull requests (Read/Write)**
   - Copy the token immediately (cannot retrieve later)

2. **Configure Environment**:
   ```bash
   # Copy environment template
   cp .env.example .env

   # Edit .env and add:
   BITBUCKET_USERNAME=your_bitbucket_username
   BITBUCKET_API_TOKEN=your_api_token_here
   BITBUCKET_WORKSPACE=your_workspace_slug  # Optional default workspace
   ```

#### Method 2: Repository Access Token (Single Repository Access)

1. **Generate Repository Token**:
   - Go to Repository → Settings → Access tokens
   - Click "Create repository access token"
   - Give it a label and select permissions
   - Copy the token immediately

2. **Configure Environment**:
   ```bash
   # Edit .env and add:
   BITBUCKET_REPOSITORY_ACCESS_TOKEN=your_repo_token_here
   BITBUCKET_WORKSPACE=your_workspace_slug  # Optional
   ```

### Claude Desktop Integration

Add to your Claude Desktop configuration file:

**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "bitbucket": {
      "command": "node",
      "args": ["/absolute/path/to/bitbucket-mcp/dist/index.js"],
      "env": {
        "BITBUCKET_USERNAME": "your_username",
        "BITBUCKET_API_TOKEN": "your_token",
        "BITBUCKET_WORKSPACE": "your_workspace"
      }
    }
  }
}
```

### Start Using

```bash
# Start the server (if running standalone)
npm start

# Or restart Claude Desktop to load the MCP server
```

## 🛠️ Available Tools (6 Consolidated Tools with 46 Actions)

**v2.1 introduces action-based routing**: Each category now has a single consolidated tool that accepts an `action` parameter to determine the specific operation. This simplifies the tool interface while maintaining all functionality.

| Category | Actions | Consolidated Tool |
|----------|---------|-------------------|
| **Workspace** | 2 | `manage_workspaces` (list, get) |
| **Repository** | 5 | `manage_repositories` (list, get, create, update, delete) |
| **Branch** | 7 | `manage_branches` (list, get, create, delete, get_model, get_permissions, get_reviewers) |
| **Pull Request** | 9 | `manage_pull_requests` (list, get, create, approve, unapprove, merge, decline, add_comment, get_comments) |
| **Commit** | 4 | `manage_commits` (list, get, get_diff, get_patch) |
| **Issue** | 19 | `manage_issues` (19 actions for CRUD, comments, metadata, and workflow operations) |

### Workspace Management

**Tool**: `manage_workspaces` with actions: `list`, `get`

```
"List all my Bitbucket workspaces"
→ manage_workspaces({ action: 'list' })

"Show details for workspace my-org"
→ manage_workspaces({ action: 'get', workspace: 'my-org' })
```

### Repository Operations

**Tool**: `manage_repositories` with actions: `list`, `get`, `create`, `update`, `delete`

```
"List all repositories in my-workspace"
→ manage_repositories({ action: 'list', workspaceSlug: 'my-workspace' })

"Create a new private repository called 'awesome-project'"
→ manage_repositories({ action: 'create', workspaceSlug: 'my-workspace', name: 'awesome-project', isPrivate: true })

"Update the description for my-workspace/my-repo"
→ manage_repositories({ action: 'update', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', description: 'New description' })

"Delete repository my-workspace/old-project"
→ manage_repositories({ action: 'delete', workspaceSlug: 'my-workspace', repoSlug: 'old-project' })
```

### Branch Management

**Tool**: `manage_branches` with actions: `list`, `get`, `create`, `delete`, `get_model`, `get_permissions`, `get_reviewers`

```
"List all branches in my-workspace/my-repo"
→ manage_branches({ action: 'list', workspaceSlug: 'my-workspace', repoSlug: 'my-repo' })

"Create a new branch called 'feature/auth' from develop"
→ manage_branches({ action: 'create', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', branchName: 'feature/auth', sourceBranch: 'develop' })

"Show the branching model for my-workspace/my-repo"
→ manage_branches({ action: 'get_model', workspaceSlug: 'my-workspace', repoSlug: 'my-repo' })

"Delete the old-feature branch"
→ manage_branches({ action: 'delete', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', branchName: 'old-feature' })
```

### Pull Request Workflows

**Tool**: `manage_pull_requests` with actions: `list`, `get`, `create`, `approve`, `unapprove`, `merge`, `decline`, `add_comment`, `get_comments`

```
"List open pull requests in my-workspace/my-repo"
→ manage_pull_requests({ action: 'list', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', state: 'OPEN' })

"Create a pull request from feature/auth to main titled 'Add authentication'"
→ manage_pull_requests({ action: 'create', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', title: 'Add authentication', sourceBranch: 'feature/auth', destinationBranch: 'main' })

"Approve pull request #42"
→ manage_pull_requests({ action: 'approve', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', pullRequestId: 42 })

"Add a comment to PR #15: 'Great work! Just one suggestion...'"
→ manage_pull_requests({ action: 'add_comment', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', pullRequestId: 15, content: 'Great work! Just one suggestion...' })

"Merge pull request #42"
→ manage_pull_requests({ action: 'merge', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', pullRequestId: 42 })
```

### Commit Analysis

**Tool**: `manage_commits` with actions: `list`, `get`, `get_diff`, `get_patch`

```
"List recent commits on the main branch"
→ manage_commits({ action: 'list', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', branch: 'main' })

"Show me the diff for commit abc123"
→ manage_commits({ action: 'get_diff', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', commitHash: 'abc123' })

"Get details for commit abc123def456"
→ manage_commits({ action: 'get', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', commitHash: 'abc123def456' })

"Generate a patch for commit abc123"
→ manage_commits({ action: 'get_patch', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', commitHash: 'abc123' })
```

### Issue Tracking

**Tool**: `manage_issues` with 19 actions for comprehensive issue management including CRUD operations, comments, components, milestones, versions, assignment, voting, and watching

```
"Create a bug report titled 'Login page crashes on mobile'"
→ manage_issues({ action: 'create', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', title: 'Login page crashes on mobile', kind: 'bug' })

"List all open issues assigned to john-doe"
→ manage_issues({ action: 'list', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', state: 'open', assignee: 'john-doe' })

"Add a comment to issue #123: 'Fixed in latest commit'"
→ manage_issues({ action: 'add_comment', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', issueId: 123, content: 'Fixed in latest commit' })

"Assign issue #45 to jane-smith"
→ manage_issues({ action: 'assign', workspaceSlug: 'my-workspace', repoSlug: 'my-repo', issueId: 45, assignee: 'jane-smith' })
```

## ⚙️ Configuration

### Environment Variables

#### Authentication (Required)

```bash
# Method 1: API Token (Recommended - Full Access)
BITBUCKET_USERNAME=your_username
BITBUCKET_API_TOKEN=your_api_token

# Method 2: Repository Access Token (Alternative - Single Repo)
BITBUCKET_REPOSITORY_ACCESS_TOKEN=your_repo_token

# Optional Default Workspace
BITBUCKET_WORKSPACE=your_workspace_slug
```

#### Logging Configuration (Optional)

```bash
# Log level: debug, info, warn, error
LOG_LEVEL=info

# Enable console logging
ENABLE_CONSOLE_LOGGING=true

# Enable file logging
ENABLE_FILE_LOGGING=false

# Log file path (if file logging enabled)
LOG_FILE_PATH=./logs/bitbucket-mcp.log

# Enable structured logging with metadata
ENABLE_STRUCTURED_LOGGING=true
```

#### Rate Limiting Configuration (Optional)

```bash
# Maximum concurrent requests
RATE_LIMIT_MAX_CONCURRENT=10

# Minimum time between requests (ms)
RATE_LIMIT_MIN_TIME=100

# Request reservoir size (burst capacity)
RATE_LIMIT_RESERVOIR=100

# Amount to refill reservoir
RATE_LIMIT_RESERVOIR_REFRESH_AMOUNT=100

# Refresh interval (ms) - 1 minute default
RATE_LIMIT_RESERVOIR_REFRESH_INTERVAL=60000
```

### Authentication Methods Compared

| Feature | API Token | Repository Token |
|---------|-----------|------------------|
| **Username Required** | ✅ Yes | ❌ No |
| **Access Scope** | All repositories user can access | Single repository only |
| **Use Case** | General development, multiple repos | CI/CD, single repo automation |
| **Token Format** | Starts with `ATBBT` | Repository-specific |
| **Atlassian Recommendation** | ✅ Official recommendation | Specialized use cases |
| **Generate At** | Personal Settings → API tokens | Repository → Settings → Access tokens |

## 🏗️ Architecture Overview

### v2.0 Simplified Design

The v2.0 architecture removes OAuth complexity and persistent web services in favor of simple token-based authentication:

**Removed in v2.0**:
- ❌ OAuth 2.0 authorization flow and token refresh logic
- ❌ Persistent Express web server
- ❌ Web-based log viewer with WebSockets
- ❌ Encrypted token storage infrastructure
- ❌ OAuth callback handling

**Simplified in v2.0**:
- ✅ Direct API Token or Repository Token authentication
- ✅ File-based logging only (no web viewer)
- ✅ ~40% code reduction (~1,900 lines removed)
- ✅ 7 fewer npm dependencies
- ✅ Faster startup time
- ✅ Easier multi-instance support

### Project Structure

```
bitbucket-mcp/
├── src/
│   ├── tools/              # MCP tool implementations (6 categories)
│   │   ├── base-tool.ts    # Base tool infrastructure
│   │   ├── workspace-tools.ts
│   │   ├── repository-tools.ts
│   │   ├── branch-tools.ts
│   │   ├── pull-request-tools.ts
│   │   ├── commit-tools.ts
│   │   ├── issue-tools.ts
│   │   └── index.ts        # Tool exports and documentation
│   ├── types.ts            # TypeScript types and Zod schemas
│   ├── config.ts           # Configuration management
│   ├── logger.ts           # Structured logging system
│   ├── bitbucket-client.ts # HTTP API client
│   ├── auth-service.ts     # Token authentication service
│   ├── rate-limiter.ts     # API rate limiting
│   ├── error-handler.ts    # Centralized error handling
│   └── index.ts            # Main MCP server
├── dist/                   # Compiled JavaScript
├── docs/                   # Documentation
├── .env.example            # Environment template
└── package.json
```

### Core Components

- **Tool System** - 6 consolidated MCP tools with action-based routing (46 total actions across Workspace, Repository, Branch, PR, Commit, Issue domains)
- **Authentication** - Simple token-based auth with dual method support
- **HTTP Client** - Axios-based Bitbucket API client with rate limiting
- **Type Safety** - Full TypeScript with Zod runtime validation
- **Error Handling** - Comprehensive error management and user-friendly messages
- **Logging** - Structured logging with multiple transports (console, file)

## 🔨 Development

### Available Scripts

```bash
npm run build      # Compile TypeScript to dist/
npm run dev        # Watch mode for development
npm run start      # Start the MCP server
npm run lint       # ESLint code checking
npm test           # Run Jest tests (if configured)
```

### Building from Source

```bash
# Clone the repository
git clone https://bitbucket.org/gohcl/bitbucket-mcp.git
cd bitbucket-mcp

# Install dependencies
npm install

# Compile TypeScript
npm run build

# Start the server
npm start
```

### Development Workflow

1. Make changes to TypeScript files in `src/`
2. Run `npm run build` to compile
3. Test with Claude Desktop or standalone
4. Run `npm run lint` before committing
5. Follow existing TypeScript patterns and conventions

## 🔒 Security

### v2.0 Security Model

- **Token-Based Authentication** - Simple, secure API token or repository token authentication
- **No Token Storage** - Tokens provided via environment variables (not stored on disk)
- **Input Validation** - Comprehensive sanitization and Zod schema validation
- **Rate Limiting** - Built-in throttling to respect Bitbucket API limits
- **Audit Logging** - Comprehensive logging with sensitive data redaction
- **Minimal Attack Surface** - No web server, no OAuth callbacks, no persistent storage

### Best Practices

1. **Never commit tokens** - Use `.env` file (excluded from git)
2. **Limit token permissions** - Only grant necessary repository and PR permissions
3. **Rotate tokens regularly** - Generate new tokens periodically
4. **Use workspace-scoped tokens** - Limit API tokens to specific workspaces when possible
5. **Repository tokens for CI/CD** - Use repository tokens for automated workflows (single repo only)
6. **Monitor token usage** - Review Bitbucket audit logs regularly

## 📚 Documentation

- **[API Reference](docs/API-Reference.md)** - Complete tool documentation with examples
- **[Configuration Guide](docs/Configuration.md)** - Advanced configuration options
- **[Architecture Guide](docs/Architecture.md)** - System design and patterns
- **[Getting Started](docs/Getting-Started.md)** - Detailed setup instructions
- **[Logging Guide](docs/Logging.md)** - Logging configuration and best practices

## 🔗 Project Links

### Repository Information

- **Repository**: [bitbucket.org/gohcl/bitbucket-mcp](https://bitbucket.org/gohcl/bitbucket-mcp)
- **Workspace**: `gohcl` (Health Care Logistics)
- **Project**: `SOLN` (Stat Solutions)
- **Type**: Private Repository
- **Language**: TypeScript
- **Version**: 2.1.0

### Related Resources

- **[Bitbucket Cloud API](https://developer.atlassian.com/cloud/bitbucket/rest/intro/)** - Official API documentation
- **[Model Context Protocol](https://modelcontextprotocol.io/)** - MCP specification
- **[Claude Documentation](https://docs.anthropic.com/)** - Claude AI documentation
- **[Bitbucket API Tokens](https://support.atlassian.com/bitbucket-cloud/docs/api-tokens/)** - API token setup guide

## 🔄 Migrating from v1.x

If you're upgrading from v1.x (OAuth-based):

### What Changed

- **Authentication**: OAuth 2.0 removed → Simple token-based auth added
- **Web Server**: Removed (no OAuth callbacks or log viewer)
- **Token Storage**: Removed (tokens now via environment variables only)
- **Tools**: 26 → 24 tools (removed `get_auth_url` and `exchange_code_for_token`)
- **v2.1 Tools**: 24 → 6 consolidated tools with action-based routing (46 actions total)

### Migration Steps

1. **Remove OAuth Environment Variables**:
   ```bash
   # Remove these from .env:
   BITBUCKET_CLIENT_ID
   BITBUCKET_CLIENT_SECRET
   BITBUCKET_REFRESH_TOKEN
   MCP_SERVER_PORT
   TOKEN_ENCRYPTION_KEY
   TOKEN_STORAGE_FILE_PATH
   ```

2. **Add Token Authentication**:
   ```bash
   # Add these to .env:
   BITBUCKET_USERNAME=your_username
   BITBUCKET_API_TOKEN=your_api_token
   ```

3. **Generate API Token** (see Quick Start above)

4. **Update Claude Desktop Config**:
   - Replace OAuth env vars with token env vars
   - Remove any OAuth-related configuration

5. **Test**: Restart Claude Desktop and verify tools work

See **[MIGRATION.md](MIGRATION.md)** for detailed migration guide.

## 💬 Usage Examples

### Repository Workflow

```
User: "List all repositories in my-workspace"
Claude: *uses manage_repositories with action: 'list'*

User: "Create a new private repository called 'api-service' in my-workspace with description 'Backend API service'"
Claude: *uses manage_repositories with action: 'create'*

User: "Show me details for my-workspace/api-service"
Claude: *uses manage_repositories with action: 'get'*
```

### Branch and Pull Request Workflow

```
User: "Create a feature branch called 'feature/user-auth' from develop in my-workspace/api-service"
Claude: *uses manage_branches with action: 'create'*

User: "Make some changes..."
User: "Create a pull request from feature/user-auth to develop titled 'Add user authentication system'"
Claude: *uses manage_pull_requests with action: 'create'*

User: "Add a comment to PR #5: 'Please review the error handling in auth.ts'"
Claude: *uses manage_pull_requests with action: 'add_comment'*

User: "Approve PR #5"
Claude: *uses manage_pull_requests with action: 'approve'*

User: "Merge PR #5"
Claude: *uses manage_pull_requests with action: 'merge'*
```

### Commit Analysis Workflow

```
User: "Show me the last 10 commits on the main branch of my-workspace/api-service"
Claude: *uses manage_commits with action: 'list'*

User: "Get the diff for commit abc123"
Claude: *uses manage_commits with action: 'get_diff'*

User: "Generate a patch file for commit abc123"
Claude: *uses manage_commits with action: 'get_patch'*
```

### Issue Tracking Workflow

```
User: "Create a bug report in my-workspace/api-service titled 'Login endpoint returns 500 on invalid credentials'"
Claude: *uses manage_issues with action: 'create'*

User: "List all open bugs"
Claude: *uses manage_issues with action: 'list' and filters*

User: "Add a comment to issue #12: 'Fixed in commit abc123'"
Claude: *uses manage_issues with action: 'add_comment'*

User: "Assign issue #12 to john-doe"
Claude: *uses manage_issues with action: 'assign'*
```

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Make your changes and add documentation
4. Run tests: `npm test`
5. Lint your code: `npm run lint`
6. Commit: `git commit -m 'Add amazing feature'`
7. Push: `git push origin feature/amazing-feature`
8. Submit a pull request to the `develop` branch

### Development Guidelines

- Follow existing TypeScript patterns and conventions
- Add comprehensive JSDoc documentation for all public APIs
- Include input validation and error handling
- Update tests and documentation for all changes
- Follow the established architecture patterns
- Use semantic commit messages

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🆘 Support & Troubleshooting

### Common Issues

**Authentication Errors**:
- Verify token is copied correctly (no extra spaces)
- Ensure username matches your Bitbucket username exactly
- Check token permissions include Repository and Pull Request access
- Verify token hasn't expired or been revoked

**Tool Not Working**:
- Verify workspace and repository slugs are correct (case-sensitive)
- Check you have appropriate permissions for the operation
- Review logs for detailed error messages
- Ensure you're using the correct authentication method

**Rate Limiting**:
- Bitbucket has rate limits (default: 1000 requests/hour)
- Server includes built-in rate limiting to prevent quota exhaustion
- Adjust `RATE_LIMIT_*` environment variables if needed

### Getting Help

- **Setup Questions**: See [Getting Started Guide](docs/Getting-Started.md)
- **Configuration Issues**: Check [Configuration Guide](docs/Configuration.md)
- **API Questions**: Reference [API Documentation](docs/API-Reference.md)
- **Architecture Questions**: Review [Architecture Guide](docs/Architecture.md)
- **Bitbucket API**: [Official Bitbucket Cloud API Docs](https://developer.atlassian.com/cloud/bitbucket/rest/intro/)

## ⚡ What's New in v2.1

### v2.1 Tool Consolidation

- ✅ **Action-Based Routing** - 6 consolidated tools instead of 24 individual tools
- ✅ **Cleaner API** - Single tool per domain with `action` parameter
- ✅ **46 Total Actions** - All functionality preserved across workspace, repository, branch, PR, commit, and issue domains
- ✅ **Better Organization** - Logical grouping of related operations
- ✅ **Simplified Discovery** - Easier to find and use the right tool
- ✅ **Backward Compatible** - Maintains all existing capabilities

### v2.0 Major Changes

- ✅ **Simplified Authentication** - Removed OAuth, added simple token-based auth
- ✅ **No Web Server** - Removed persistent Express server and log viewer
- ✅ **Reduced Dependencies** - 7 fewer npm packages
- ✅ **40% Code Reduction** - ~1,900 lines of code removed
- ✅ **Faster Startup** - No OAuth initialization or web server startup
- ✅ **Easier Configuration** - Simple environment variables only
- ✅ **Better Multi-Instance Support** - No port conflicts or shared state

### Breaking Changes from v2.0

- 🔴 **OAuth Removed** - Must migrate to API Token or Repository Token
- 🔴 **Web Server Removed** - No log viewer or OAuth callbacks
- 🔴 **Tools Removed** - `get_auth_url` and `exchange_code_for_token` removed
- 🔴 **Configuration Changed** - New environment variables required

### Breaking Changes from v2.1

- 🟡 **Tool Consolidation** - 24 individual tools → 6 consolidated tools with actions
- 🟡 **Action Parameter Required** - All tools now require an `action` parameter to specify the operation
- 🟡 **Tool Name Changes** - Use `manage_*` tools instead of individual operation tools

See **[MIGRATION.md](MIGRATION.md)** for upgrade instructions.

---

**Ready to supercharge your Bitbucket workflows with Claude?**

Get started in minutes with simple token-based authentication - no OAuth complexity, no web servers, just powerful Bitbucket integration! 🚀