Skip to main content
Glama
bitbucket-mcp

bitbucket-mcp

by adarshba
README.md
# Bitbucket MCP

> Talk is cheap. Show me the code.

[![npm version](https://img.shields.io/npm/v/@adarsh.ba/bitbucket-mcp)](https://www.npmjs.com/package/@adarsh.ba/bitbucket-mcp)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-7.0-blue.svg)](https://www.typescriptlang.org/)

[Model Context Protocol](https://modelcontextprotocol.io) server for reviewing and shipping pull requests on self-hosted Bitbucket Data Center from AI agents (Claude, Cursor, OpenCode, etc.).

## Features

- **Pull request review loop**: read a PR with merge checks, tasks, threads and your draft review in one call, then comment, resolve and approve
- **Multi-line comments**: anchor a comment to a line range (Data Center 9.2+)
- **Draft reviews**: queue pending comments and publish them with your status in one call
- **Suggestions, tasks and reactions**: suggestion blocks, BLOCKER tasks, apply-suggestion, emoji reactions
- **Draft PRs and auto-merge**: create drafts (8.18+) and merge once checks pass (8.15+)
- **Code Mode**: `search` and `execute` reach the whole Data Center REST API in about 1k tokens of tool definitions
- **Sandboxed**: agent code runs in QuickJS with memory, time and request limits; the token never enters the sandbox
- **Read-only mode**: hide write tools and refuse non-GET requests
- **Typed results**: pull request and comment tools declare an output schema and return `structuredContent`
- **Current protocol**: serves MCP 2026-07-28 clients and 2025-era clients over stdio

## Installation

```bash
npx @adarsh.ba/bitbucket-mcp
# or with Bun:
bunx --bun @adarsh.ba/bitbucket-mcp
```

## Configuration

Configure with environment variables:

| Variable                    | Required | Default                                | Description                                                                                 |
| --------------------------- | -------- | -------------------------------------- | ------------------------------------------------------------------------------------------- |
| `BITBUCKET_BASE_URL`        | yes      |                                        | Instance URL, e.g. `https://bitbucket.example.com` (include a context path if you have one) |
| `BITBUCKET_TOKEN`           | yes      |                                        | HTTP access token, sent as `Authorization: Bearer`                                          |
| `BITBUCKET_USERNAME`        | no       | from the `X-AUSERNAME` response header | Your username; used to report your review status                                            |
| `BITBUCKET_TOOLS`           | no       | `all`                                  | `all`, `curated` (PR tools only) or `code` (`search` and `execute` only)                    |
| `BITBUCKET_READ_ONLY`       | no       | `false`                                | `true` hides write tools and refuses non-GET requests from `execute`                        |
| `BITBUCKET_TIMEOUT_MS`      | no       | `30000`                                | Timeout per Bitbucket request                                                               |
| `BITBUCKET_CODE_TIMEOUT_MS` | no       | `30000`                                | Time limit per `search` or `execute` call                                                   |

Create the token under **Profile > Manage account > HTTP access tokens**. Read permission is enough for read-only mode; reviewing and merging needs repository write.

## MCP Client Setup

**Claude Code**:

```bash
claude mcp add bitbucket-mcp \
  -e BITBUCKET_BASE_URL=https://bitbucket.example.com \
  -e BITBUCKET_TOKEN=your-token \
  -- npx -y @adarsh.ba/bitbucket-mcp

# or with Bun:
claude mcp add bitbucket-mcp \
  -e BITBUCKET_BASE_URL=https://bitbucket.example.com \
  -e BITBUCKET_TOKEN=your-token \
  -- bunx --bun @adarsh.ba/bitbucket-mcp
```

**Claude Desktop / Cursor**: add to your MCP config:

```json
{
  "mcpServers": {
    "bitbucket-mcp": {
      "command": "npx",
      "args": ["-y", "@adarsh.ba/bitbucket-mcp"],
      "env": {
        "BITBUCKET_BASE_URL": "https://bitbucket.example.com",
        "BITBUCKET_TOKEN": "your-token"
      }
    }
  }
}
```

**OpenCode**: add to `.opencode/config.json`:

```json
{
  "mcp": {
    "bitbucket-mcp": {
      "type": "local",
      "command": ["npx", "-y", "@adarsh.ba/bitbucket-mcp"],
      "environment": {
        "BITBUCKET_BASE_URL": "https://bitbucket.example.com",
        "BITBUCKET_TOKEN": "your-token"
      },
      "enabled": true
    }
  }
}
```

To run on Bun, use `"command": "bunx", "args": ["--bun", "@adarsh.ba/bitbucket-mcp"]` in Claude Desktop and Cursor, or `"command": ["bunx", "--bun", "@adarsh.ba/bitbucket-mcp"]` in OpenCode. Without `--bun`, `bunx` follows the package's `node` shebang.

## Tools

| Tool                    | Description                                                                                                                                                   |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get_pull_request`      | PR details with reviewers, merge checks, auto-merge state, open tasks, comment threads and your pending review comments.                                      |
| `list_pull_requests`    | PRs in a repository (`state`, `draft`, `filter_text`), or your dashboard across repositories (`role`).                                                        |
| `get_pull_request_diff` | Unified diff as raw text, optionally for one file. A diff over ~6,000 tokens returns a per-file summary (path, lines added and removed) unless `full` is set. |
| `create_pull_request`   | Create a PR, optionally as a draft or from a fork.                                                                                                            |
| `update_pull_request`   | Change title, description, target branch, reviewers or draft state; omitted fields are kept.                                                                  |
| `merge_pull_request`    | Merge now, or set `auto_merge` to merge once checks pass.                                                                                                     |
| `add_comment`           | General, reply, file, inline or multi-line comment; optional suggestion, BLOCKER task or pending draft comment.                                               |
| `manage_comment`        | `edit`, `delete`, `resolve_thread`, `reopen_thread`, `resolve_task`, `reopen_task`, `apply_suggestion`, `react`, `unreact`.                                   |
| `submit_review`         | Publish pending comments with `approved`, `needs_work` or `unapproved`, or discard them.                                                                      |
| `search`                | Run JavaScript against the Data Center REST API spec to find endpoints.                                                                                       |
| `execute`               | Run JavaScript that calls any Data Center REST endpoint.                                                                                                      |

Writes that need the current `version` fetch it first. If Bitbucket answers 409 because someone else changed the PR or comment in between, the tool re-reads and retries once.

### Comment anchors

| Comment         | Arguments                                                                                    |
| --------------- | -------------------------------------------------------------------------------------------- |
| General         | `text`                                                                                       |
| Reply           | `text`, `parent_id`                                                                          |
| File            | `text`, `path`                                                                               |
| Inline          | `text`, `path`, `line`, `line_type` (`ADDED`, `REMOVED`, `CONTEXT`)                          |
| Range (DC 9.2+) | inline arguments plus `start_line` and optionally `start_line_type`; `line` is the last line |
| Suggestion      | inline or range arguments plus `suggestion` (the replacement code)                           |

`REMOVED` lines anchor to the old file; `ADDED` and `CONTEXT` lines anchor to the new one. For a range, the tool reads the file's diff once and computes the `multilineSpan` Data Center requires, so you only pass line numbers. Both ends must be lines shown in the diff. Range comments need Data Center 9.2+; older servers get a clear error instead of a silent single-line comment.

## Code Mode

`search` and `execute` take an `async () => { ... }` arrow function. It runs in a fresh QuickJS sandbox with no network, filesystem, process or timers. `console.log` output comes back in `logs`. Results over about 6,000 tokens are cut to valid JSON with a `--- TRUNCATED ---` marker; pass `truncate: false` to opt out (still capped at 1 MB).

`search` gets a global `spec`: the Bitbucket Data Center 10.5 OpenAPI spec with `$ref`s resolved and examples removed. Paths start with `/rest/`.

```js
async () => {
  const results = [];
  for (const [path, methods] of Object.entries(spec.paths)) {
    for (const [method, op] of Object.entries(methods)) {
      if (op.tags?.includes("Builds and Deployments")) results.push(`${method.toUpperCase()} ${path}`);
    }
  }
  return results;
};
```

`execute` gets `bitbucket.request({ method, path, query, body, accept })`, which returns parsed JSON, or text for `accept: "text/plain"`. A failed request throws with the method, path, status, Bitbucket's message and request id.

```js
async () => {
  const repos = await bitbucket.request({
    method: "GET",
    path: "/rest/api/latest/projects/PROJ/repos",
    query: { limit: 100 },
  });
  const open = await Promise.all(
    repos.values.map(async (repo) => {
      const prs = await bitbucket.request({
        method: "GET",
        path: `/rest/api/latest/projects/PROJ/repos/${repo.slug}/pull-requests`,
        query: { state: "OPEN", limit: 25 },
      });
      return { repo: repo.slug, titles: prs.values.map((pr) => pr.title) };
    }),
  );
  return open.filter((entry) => entry.titles.length > 0);
};
```

Limits per call: `BITBUCKET_CODE_TIMEOUT_MS`, 64 MB of memory and 50 requests.

## Security

- The token stays in the server process. Sandbox code calls `bitbucket.request`, and the host adds `Authorization`; requests cannot carry their own headers.
- `execute` paths must start with `/rest/` and resolve under `BITBUCKET_BASE_URL`; absolute URLs and `..` traversal are refused.
- Path segments in curated tools are percent-encoded; `..`, `/` and control characters are refused.
- `BITBUCKET_READ_ONLY=true` hides write tools and refuses every non-GET request from `execute`.
- Errors never include the token. A plain-HTTP base URL to a non-local host prints a warning at startup.
- GET requests retry on 429, 502, 503 and 504 with jittered backoff; other methods retry only on 429.

## Development

```bash
bun install
bun run check   # every gate CI runs: format, lint, typecheck, knip, tests with coverage, audit
bun run format  # oxfmt
bun run spec    # regenerate spec/bitbucket-dc.json from Atlassian's published spec
```

## Requirements

- Node.js ≥ 22 or Bun ≥ 1.4
- Bitbucket Data Center 8.0 or later; resolving threads needs 8.9+, auto-merge 8.15+, draft PRs 8.18+ and multi-line comments 9.2+

## License

MIT © [Adarsh B A](https://github.com/adarshba)