Bitbucket MCP Server
Bitbucket MCP Server
Сервер Model Context Protocol, ориентированный на продакшн, для получения метаданных и диффов пул-реквестов из Bitbucket Cloud и Bitbucket Server/Data Center, с опциональными комментариями к пул-реквестам.
Возможности
Поддерживает Bitbucket Cloud и самостоятельный Bitbucket Server/Data Center.
Предоставляет специализированные инструменты для метаданных пул-реквестов, диффов, обсуждения ревью и общих или инлайновых комментариев.
Поддерживает bearer-токены и базовую аутентификацию.
Возвращает сырые диффы и структурированные данные об изменённых файлах, когда Bitbucket их предоставляет.
Исключает сгенерированные файлы, папки или типы файлов с помощью настраиваемых glob-шаблонов.
Ограничивает большие диффы, не нарушая UTF-8 символы.
Использует stdio, не записывая в stdout логи, нарушающие протокол.
По умолчанию создание комментариев отключено, и сервер не одобряет, не сливает и иным образом не изменяет пул-реквесты.
Related MCP server: Atlassian Bitbucket MCP Server
Быстрый старт
Требуется поддерживаемый LTS-релиз Node.js (Node.js 22 или новее).
git clone https://github.com/inceon/bitbucket-mcp.git
cd bitbucket-mcp
npm install
npm run build
cp .env.example .envУстановите BITBUCKET_URL и BITBUCKET_TOKEN в конфигурации вашего MCP-клиента, затем запустите скомпилированный сервер с помощью node dist/index.js. Сервер намеренно не загружает файлы .env самостоятельно; MCP-клиенты должны передавать переменные окружения напрямую.
Аутентификация
Bearer-аутентификация используется по умолчанию и рекомендуется для персональных токенов доступа Bitbucket Server/Data Center:
BITBUCKET_URL=https://bitbucket.example.com/bitbucket
BITBUCKET_TOKEN=your-personal-access-token
BITBUCKET_AUTH_TYPE=bearerДля API-токенов Bitbucket Cloud или паролей приложений, требующих базовой аутентификации:
BITBUCKET_URL=https://api.bitbucket.org
BITBUCKET_TOKEN=your-api-token-or-app-password
BITBUCKET_AUTH_TYPE=basic
BITBUCKET_USERNAME=your-bitbucket-usernameПредоставьте учётным данным только те разрешения, которые нужны для включённых вами инструментов. Создание комментариев требует разрешения на создание комментариев к пул-реквестам. Никогда не коммитьте учётные данные и не указывайте реальные токены в отчётах об ошибках.
Переменные окружения
Переменная | Обязательная | По умолчанию | Описание |
| Да | - | Базовый URL Bitbucket, например |
| Да | - | API-токен, пароль приложения или персональный токен доступа |
| Нет |
|
|
| Для базовой аутентификации | - | Имя пользователя, используемое вместе с токеном для базовой аутентификации |
| Нет |
| Максимальный размер в байтах UTF-8, возвращаемый в |
| Нет |
| Максимальное количество байт, читаемых из вышестоящего сырого диффа перед остановкой |
| Нет |
| Максимальное количество байт, читаемых из любого JSON-ответа Bitbucket |
| Нет |
| Максимальное количество комментариев к пул-реквесту, собираемых по страницам |
| Нет |
| Максимальное количество страниц комментариев к пул-реквесту, за которыми следует сервер |
| Нет |
| Максимальное количество коммитов пул-реквеста, собираемых по страницам |
| Нет |
| Максимальное количество страниц коммитов пул-реквеста, за которыми следует сервер |
| Нет |
| Максимальное количество структурированных записей об изменённых файлах, собираемых по страницам |
| Нет |
| Максимальное количество страниц структурированных изменённых файлов, за которыми следует сервер |
| Нет |
| Крайний срок в миллисекундах для каждого HTTP-запроса к Bitbucket |
| Нет | - | Разделённые запятыми glob-шаблоны файлов, исключаемые из каждого диффа PR |
| Нет |
| Установите |
Сервер записывает ошибки запуска только в stderr и скрывает настроенные учётные данные из фрагментов ошибок HTTP Bitbucket.
Конфигурация MCP
Конфигурация Claude Desktop:
{
"mcpServers": {
"bitbucket": {
"command": "node",
"args": ["/absolute/path/to/my-bitbucket-mcp/dist/index.js"],
"env": {
"BITBUCKET_URL": "https://api.bitbucket.org",
"BITBUCKET_TOKEN": "your-token"
}
}
}
}Конфигурация Codex config.toml:
[mcp_servers.bitbucket]
command = "node"
args = ["/absolute/path/to/my-bitbucket-mcp/dist/index.js"]
[mcp_servers.bitbucket.env]
BITBUCKET_URL = "https://api.bitbucket.org"
BITBUCKET_TOKEN = "your-token"Доступные инструменты
get_pull_request
Возвращает метаданные пул-реквеста, включая его описание, состояние, автора, ревьюеров, ветки, временные метки и ссылки.
{
"name": "get_pull_request",
"arguments": {
"workspace": "my-workspace",
"repository": "my-repository",
"pull_request_id": 123
}
}get_pull_request_comments
Возвращает существующие общие и инлайновые обсуждения в виде нативных для провайдера объектов комментариев. Используйте его перед публикацией замечания ревью, чтобы учесть существующие отзывы. commentsStatus.complete равен false с причиной max_comments или max_pages, когда достигнуты настроенные пределы получения.
get_pull_request_commits
Возвращает нативные для провайдера коммиты, находящиеся в настоящее время в пул-реквесте. Используйте его, чтобы проследить замечание до исходного коммита или проверить, устраняется ли оно последующей работой. commitsStatus.complete равен false с причиной max_commits или max_pages, когда достигнуты настроенные пределы получения.
get_pull_request_diff
Возвращает дифф ревью в стиле git и структурированные изменённые файлы, когда они доступны.
{
"name": "get_pull_request_diff",
"arguments": {
"workspace": "PROJECT_KEY",
"repository": "my-repository",
"pull_request_id": 123,
"ignore_patterns": ["dist/**", "**/*.generated.ts", "package-lock.json"],
"path": "src/service.ts",
"context": 5,
"ignore_whitespace": true,
"renames": true
}
}Вывод диффа доступен как в виде обратно совместимого JSON-текста, так и в виде MCP structuredContent, с объявленной схемой вывода. Он включает:
provider,pull_request_id,rawDiff,rawDiffBytesиrawDiffSource.rawDiffSourceравенprovider_rawдля Cloud илиserver_structuredдля локально нормализованного ответа Server/Data Center.truncatedиtruncationReason:input_limit, когда достигнут предел чтения вышестоящего Cloud,output_limit, когда отфильтрованный результат превысилBITBUCKET_MAX_DIFF_BYTES, илиprovider_limit, когда Server/Data Center пометил свой структурированный дифф как усечённый.Необязательные компактные записи
filesсодержат толькоpath, нормализованныйstatusиoldPathдля переименований или копий. ОбязательныйfilesStatusсообщает о полноте;completeравенfalseс причинойmax_files,max_pagesилиunsupported, аreturnedотражает фактически возвращённые отфильтрованные записи.Необязательные метаданные
ignored, когда активны исключения.
Полный результат:
{
"provider": "cloud",
"pull_request_id": 123,
"rawDiff": "diff --git ...",
"rawDiffBytes": 128,
"rawDiffSource": "provider_raw",
"files": [],
"filesStatus": { "available": true, "complete": true, "returned": 0 },
"truncated": false
}Ограниченный частичный результат:
{
"provider": "cloud",
"pull_request_id": 123,
"rawDiff": "diff --git ...",
"rawDiffBytes": 200000,
"rawDiffSource": "provider_raw",
"files": [{ "path": "src/service.ts", "status": "modified" }],
"filesStatus": {
"available": true,
"complete": false,
"returned": 1,
"reason": "max_pages"
},
"truncated": true,
"truncationReason": "output_limit"
}Усечённый rawDiff — это безопасный для UTF-8 префикс ревью, не обязательно полная строка, хунк или применимый патч.
Страницы структурированных файлов обрабатываются до завершения или до достижения настроенного предела файлов/страниц, затем нормализуются в компактные метаданные ревью, а не возвращают хэши, ссылки и дублирующиеся структуры путей провайдера. Недоступная конечная точка diffstat или changes сообщается только после HTTP 404. Ошибки авторизации, ограничения скорости, сервера, некорректного ответа, тайм-аута и транспорта приводят к сбою вызова инструмента, а не к молчаливому пропуску метаданных.
Cloud rawDiff сохраняет исходный ответ провайдера. Server/Data Center использует структурированный ответ /diff и нормализует его файлы, хунки, сегменты и строки в текст ревью в стиле git; это позволяет избежать ошибок, зависящих от версии, при использовании отдельного маршрута экспорта .diff. rawDiffSource делает это различие явным.
path поддерживается обоими провайдерами и является предпочтительным способом просмотра больших пул-реквестов пофайлово; возвращаемые метаданные files ограничены тем же путём. renames доступен только в Cloud. context соответствует context в Cloud и contextLines в Server/Data Center. ignore_whitespace соответствует ignore_whitespace в Cloud и whitespace=ignore-all в Server/Data Center. При отсутствии эти параметры не изменяют значения по умолчанию провайдера.
Шаблоны используют пути относительно репозитория и поддерживают *, ** и ?. Шаблон без /, например package-lock.json или *.png, соответствует этому имени файла в любом месте. Завершающий слэш исключает каталог рекурсивно. Когда активны исключения, ответ включает ignored.patterns, ignored.files и ignored.rawDiffFiltered. Значение false в rawDiffFiltered означает, что провайдер Cloud вернул не-git формат диффа, который нельзя безопасно отфильтровать; ответ сохраняется, а не молча отбрасывается содержимое.
add_pull_request_comment
Создаёт общий, файловый или инлайновый комментарий к строке в пул-реквесте. Эта операция записи доступна только когда в окружении MCP-сервера установлено BITBUCKET_ENABLE_WRITE_TOOLS=true.
Общий комментарий:
{
"name": "add_pull_request_comment",
"arguments": {
"workspace": "my-workspace",
"repository": "my-repository",
"pull_request_id": 123,
"comment": "The implementation looks good. Please add a regression test for the empty input case."
}
}Инлайновый комментарий к добавленной строке:
{
"name": "add_pull_request_comment",
"arguments": {
"workspace": "my-workspace",
"repository": "my-repository",
"pull_request_id": 123,
"comment": "Please handle an empty value here.",
"file_path": "src/service.ts",
"line": 42,
"line_type": "added"
}
}Используйте значения line_type: added, removed или context. Добавленные строки по умолчанию относятся к стороне new, удалённые — к стороне old, а контекстные — к new; установите line_side явно, чтобы разместить контекстный комментарий на old. Укажите file_path без полей строк для файлового комментария. Для переименованных файлов в Server/Data Center source_file_path может идентифицировать предыдущий путь.
Аутентифицированный пользователь Bitbucket становится автором комментария. Проверьте целевое рабочее пространство, репозиторий, ID пул-реквеста и текст комментария перед одобрением вызова инструмента в вашем MCP-клиенте.
Поведение провайдера
Хост URL определяет провайдера. bitbucket.org и api.bitbucket.org используют Bitbucket Cloud; все остальные хосты используют Server/Data Center.
URL Cloud нормализуются до одного префикса API /2.0 и используют:
/repositories/{workspace}/{repository}/pullrequests/{id}/repositories/{workspace}/{repository}/pullrequests/{id}/diff/repositories/{workspace}/{repository}/pullrequests/{id}/diffstat/repositories/{workspace}/{repository}/pullrequests/{id}/comments(GET;POSTwhen enabled)/repositories/{workspace}/{repository}/pullrequests/{id}/commits(GET)
URL Server/Data Center сохраняют контекстный путь, например /bitbucket, нормализуются до одного префикса /rest/api/1.0 и используют:
/projects/{project}/repos/{repository}/pull-requests/{id}/projects/{project}/repos/{repository}/pull-requests/{id}/diff(структурированный дифф, нормализованный в текст ревью в стиле git)/projects/{project}/repos/{repository}/pull-requests/{id}/diff/{path}(структурированный дифф, ограниченный путём)/projects/{project}/repos/{repository}/pull-requests/{id}/changes/projects/{project}/repos/{repository}/pull-requests/{id}/comments(GET;POSTwhen enabled)/projects/{project}/repos/{repository}/pull-requests/{id}/commits(GET)
Необязательный запрос diffstat или changes сообщает filesStatus.reason: "unsupported" после HTTP 404. Другие ошибки HTTP, тайм-аута, транспорта и разбора приводят к сбою вызова инструмента, чтобы неполные метаданные не были приняты за полный ответ.
Atlassian Rovo MCP
Atlassian документирует действие bitbucketPullRequest.diff, доступное только в Cloud, но не публикует его схему аргументов, форму вывода, контракт пагинации, фильтрации или усечения. Поэтому этот сервер считает прямые Bitbucket API авторитетным источником. Адаптер Rovo следует добавлять только после проверки живой схемы tools/list и контролируемого ответа diff; он должен оставаться явно настроенным и не может заменить поддержку Server/Data Center. См. страницу Atlassian о поддерживаемых инструментах.
Дорожная карта
Запланированные направления для будущих релизов включают:
Добавить обработку повторных попыток и более понятную диагностику ограничений частоты запросов.
Предоставлять нормализованный вывод pull request, сохраняя доступ к полям, специфичным для провайдера.
Добавить инструменты только для чтения для вывода списка pull request и получения статуса сборки.
Предложить опциональный транспорт Streamable HTTP, оставив stdio по умолчанию.
Публиковать версионированные релизы с более простыми путями установки и обновления.
Операции записи останутся отключенными по умолчанию. Одобрение, слияние и другие значимые операции Bitbucket не запланированы. Идеи и предложения по реализации приветствуются через GitHub issues.
Разработка
npm run dev # Run directly from TypeScript
npm run build # Compile to dist/
npm test # Run the test suite once
npm run test:watch # Run tests in watch mode
npm run check # Build and test, matching CIРеестр команд хранит каждый MCP-инструмент изолированно в src/tools. Перед открытием pull request ознакомьтесь с CONTRIBUTING.md.
Безопасность
Этот сервер обрабатывает учетные данные в памяти и отправляет их только на настроенный BITBUCKET_URL. Внимательно проверьте этот URL перед запуском сервера. Включение инструментов записи позволяет подключенным MCP-клиентам публиковать комментарии к PR от имени аутентифицированного пользователя Bitbucket. Чтобы сообщить об уязвимости конфиденциально, следуйте SECURITY.md.
Лицензия
Выпущено под лицензией MIT.
Available Tools
3 toolsadd_pull_request_commentA
Creates a general, file, or inline line comment on a Bitbucket pull request. This is a write operation and requires BITBUCKET_ENABLE_WRITE_TOOLS=true.
| Name | Required | Description | Default |
|---|---|---|---|
| workspace | Yes | Bitbucket Cloud workspace ID or Bitbucket Server/Data Center project key | |
| repository | Yes | Repository slug or repository name | |
| pull_request_id | Yes | Pull request ID | |
| comment | Yes | Comment text. Bitbucket Cloud renders supported Markdown. | |
| file_path | No | Optional destination-side repository path for a file or line comment. | |
| source_file_path | No | Optional previous path for a renamed or copied file. Used by Server/Data Center. | |
| line | No | Optional 1-based diff line number. Requires file_path and line_type. | |
| line_type | No | Kind of diff line. Requires file_path and line. | |
| line_side | No | Diff side. Defaults to old for removed lines and new otherwise. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided. Description declares write operation and environment variable requirement, but omits details on side effects, permissions, rate limits, or comment management (editing/deletion).
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Extremely concise: one sentence plus a note on prerequisites. No unnecessary information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Missing explanation of return values (no output schema), no guidance on combining file_path, line, line_type, line_side for inline comments. Given 9 parameters and write nature, more context needed.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%; each parameter is documented in the schema. The description adds no extra semantic value beyond summarizing the tool's purpose.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Clearly states it creates a comment on a Bitbucket pull request, specifying three types: general, file, or inline line comment. Different from sibling read-only tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly identifies it as a write operation requiring BITBUCKET_ENABLE_WRITE_TOOLS=true. Does not explicitly state when to use versus siblings, but the read-only nature of siblings implies the writing use case.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_pull_requestA
Retrieves metadata, description, state/status, author, reviewers, source branch, destination branch, timestamps, and links for a specific Bitbucket pull request.
| Name | Required | Description | Default |
|---|---|---|---|
| workspace | Yes | Bitbucket Cloud workspace ID or Bitbucket Server/Data Center project key | |
| repository | Yes | Repository slug or repository name | |
| pull_request_id | Yes | Pull request ID |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It describes what data is retrieved but does not mention any behavioral traits such as authentication requirements, rate limits, or potential performance implications. For a simple read operation, this is adequate but not rich.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single sentence that efficiently lists the retrieved data without any fluff. Every phrase adds value, and the structure is front-loaded with the verb and resource.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given no output schema, the description does a good job of listing the expected return fields (metadata, description, state, author, reviewers, branches, timestamps, links). It is fairly comprehensive, though it could be improved by noting if any fields are nested or if there are pagination details.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, meaning all parameters are described in the schema. The description adds no extra meaning beyond the schema; it simply restates that the tool retrieves for a specific pull request. Baseline score of 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses the specific verb 'Retrieves' and clearly lists the resource ('metadata, description, state/status, author, reviewers, source branch, destination branch, timestamps, and links for a specific Bitbucket pull request'). It distinguishes from sibling tools (add_pull_request_comment and get_pull_request_diff) by focusing on retrieval of metadata, not adding comments or getting diffs.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description does not explicitly state when to use this tool vs alternatives. While the purpose is clear, there is no guidance on when not to use it or which sibling tool to choose for other tasks. The agent must rely on tool names and context, which is adequate but not explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_pull_request_diffA
Retrieves the raw diff and, when available, a structured list of changed files for a specific Bitbucket pull request.
| Name | Required | Description | Default |
|---|---|---|---|
| workspace | Yes | Bitbucket Cloud workspace ID or Bitbucket Server/Data Center project key | |
| repository | Yes | Repository slug or repository name | |
| pull_request_id | Yes | Pull request ID |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided. Description mentions return content (raw diff and structured files) but does not discuss side effects, authentication needs, or limitations such as file size constraints.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Single sentence that is direct and waste-free, conveying the essential information efficiently.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a retrieval tool with three fully described parameters and no output schema, the description adequately states what is returned. Slightly incomplete in not mentioning that diff may be large or truncated.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema covers all three parameters with descriptions (100% coverage). The tool description adds no extra meaning beyond the schema fields.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Description clearly states verb 'retrieves' and resources 'raw diff' and 'structured list of changed files' for a specific Bitbucket pull request, distinguishing it from sibling tools like add_pull_request_comment and get_pull_request.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No explicit guidance on when to use this tool vs siblings; usage is implied by the name and description but not directly stated.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v1.0.0- First observed
add_pull_request_comment - First observed
get_pull_request - First observed
get_pull_request_diff
TDQS
Scored across 3 tools
Each tool targets a distinct aspect of pull requests: commenting, metadata retrieval, and diff retrieval. No functional overlap, making selection clear.
All tool names follow a consistent verb_noun snake_case pattern (add_*, get_*, get_*), which is predictable and easy to follow.
Three tools is minimal for a Bitbucket server; it covers only basic pull request read operations and commenting, missing core CRUD operations, but it is not extreme.
The toolset lacks essential operations like listing, creating, updating, or merging pull requests. Agents cannot perform a full workflow, leaving significant gaps.
Maintenance
Related MCP Connectors
Human-authenticated setup for routing GitHub pull requests into the right Slack channel.
Human-authenticated setup for routing GitHub pull requests into the right Slack channel.
A Model Context Protocol (MCP) application for automated GitHub PR analysis and issue management.…
Screens public GitHub repos and PRs to generate risk maps, findings, and merge-readiness signals.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables management of Bitbucket Cloud pull requests through natural language, including creating, reviewing, approving, and commenting on PRs with automatic default reviewer support.791MIT
- AlicenseBqualityBmaintenanceEnables AI assistants to interact with Bitbucket Cloud and self-hosted instances for pull request reviews, code search, repository operations, and managing PR comments and approvals.19GPL 3.0
- AlicenseAqualityDmaintenanceEnables LLMs to review Bitbucket pull requests with custom checklists and API token authentication.51MIT
- AlicenseBqualityDmaintenanceEnables AI assistants to read Bitbucket Cloud pull requests and diffs through natural conversation.220 npmMIT