Bitbucket MCP Server
Servidor MCP de Bitbucket
Un servidor del Model Context Protocol orientado a producción para recuperar metadatos de solicitudes de extracción y diferencias de Bitbucket Cloud y Bitbucket Server/Data Center, con comentarios de solicitudes de extracción opcionales.
Funciones
Compatible con Bitbucket Cloud y Bitbucket Server/Data Center autoalojado.
Expone herramientas específicas para metadatos de solicitudes de extracción, diferencias, discusión de revisiones y comentarios generales o en línea.
Compatible con tokens de portador y autenticación básica.
Devuelve diferencias sin procesar y datos estructurados de archivos modificados cuando Bitbucket los proporciona.
Excluye archivos, carpetas o tipos de archivo generados mediante patrones globales configurables.
Limita las diferencias grandes sin romper los caracteres UTF-8.
Usa stdio sin escribir registros que rompan el protocolo en la salida estándar.
Mantiene la creación de comentarios deshabilitada de forma predeterminada y no aprueba, combina ni modifica solicitudes de extracción de ninguna otra manera.
Related MCP server: Atlassian Bitbucket MCP Server
Inicio rápido
Requiere una versión LTS compatible de Node.js (Node.js 22 o posterior).
git clone https://github.com/inceon/bitbucket-mcp.git
cd bitbucket-mcp
npm install
npm run build
cp .env.example .envEstablezca BITBUCKET_URL y BITBUCKET_TOKEN en la configuración de su cliente MCP y, a continuación, inicie el servidor compilado con node dist/index.js. El servidor no carga archivos .env por sí mismo a propósito; los clientes MCP deben pasar las variables de entorno directamente.
Autenticación
La autenticación de portador es la predeterminada y se recomienda para tokens de acceso personal de Bitbucket Server/Data Center:
BITBUCKET_URL=https://bitbucket.example.com/bitbucket
BITBUCKET_TOKEN=your-personal-access-token
BITBUCKET_AUTH_TYPE=bearerPara tokens de API de Bitbucket Cloud o contraseñas de aplicación que requieran autenticación básica:
BITBUCKET_URL=https://api.bitbucket.org
BITBUCKET_TOKEN=your-api-token-or-app-password
BITBUCKET_AUTH_TYPE=basic
BITBUCKET_USERNAME=your-bitbucket-usernameConceda a la credencial únicamente los permisos necesarios para las herramientas que habilite. La creación de comentarios requiere permiso para crear comentarios en solicitudes de extracción. Nunca confirme credenciales ni incluya tokens reales en informes de incidencias.
Variables de entorno
Variable | Obligatoria | Predeterminado | Descripción |
| Sí | - | URL base de Bitbucket, como |
| Sí | - | Token de API, contraseña de aplicación o token de acceso personal |
| No |
|
|
| Para autenticación básica | - | Nombre de usuario asociado al token para la autenticación básica |
| No |
| Tamaño máximo en bytes UTF-8 devuelto en |
| No |
| Bytes máximos leídos de una diferencia sin procesar ascendente antes de detenerse |
| No |
| Bytes máximos leídos de cualquier respuesta JSON de Bitbucket |
| No |
| Número máximo de comentarios de solicitudes de extracción recopilados en todas las páginas |
| No |
| Número máximo de páginas de comentarios de solicitudes de extracción seguidas |
| No |
| Número máximo de confirmaciones de solicitudes de extracción recopiladas en todas las páginas |
| No |
| Número máximo de páginas de confirmaciones de solicitudes de extracción seguidas |
| No |
| Número máximo de entradas estructuradas de archivos modificados recopiladas en todas las páginas |
| No |
| Número máximo de páginas estructuradas de archivos modificados seguidas |
| No |
| Plazo en milisegundos para cada solicitud HTTP de Bitbucket |
| No | - | Patrones globales de archivos separados por comas excluidos de cada diferencia de solicitud de extracción |
| No |
| Establézcalo en |
El servidor escribe errores de inicio solo en el error estándar y redacta las credenciales configuradas de los fragmentos de error HTTP de Bitbucket.
Configuración de MCP
Configuración de 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"
}
}
}
}Configuración de config.toml de Codex:
[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"Herramientas disponibles
get_pull_request
Devuelve metadatos de la solicitud de extracción, incluidos su descripción, estado, autor, revisores, ramas, marcas de tiempo y enlaces.
{
"name": "get_pull_request",
"arguments": {
"workspace": "my-workspace",
"repository": "my-repository",
"pull_request_id": 123
}
}get_pull_request_comments
Devuelve los debates generales y en línea existentes como objetos de comentario nativos del proveedor. Úselo antes de publicar un hallazgo de revisión para tener en cuenta los comentarios existentes. commentsStatus.complete es falso con el motivo max_comments o max_pages cuando se alcanzan los límites de recuperación configurados.
get_pull_request_commits
Devuelve las confirmaciones nativas del proveedor actualmente en la solicitud de extracción. Úselo para rastrear un hallazgo hasta su confirmación de origen o para verificar si un trabajo posterior lo aborda. commitsStatus.complete es falso con el motivo max_commits o max_pages cuando se alcanzan los límites de recuperación configurados.
get_pull_request_diff
Devuelve una diferencia de revisión de estilo git y archivos modificados estructurados cuando estén disponibles.
{
"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
}
}La salida de la diferencia está disponible tanto como texto JSON compatible con versiones anteriores como structuredContent de MCP, con un esquema de salida anunciado. Incluye:
provider,pull_request_id,rawDiff,rawDiffBytesyrawDiffSource.rawDiffSourceesprovider_rawpara Cloud oserver_structuredpara una respuesta de Server/Data Center normalizada localmente.truncatedmástruncationReason:input_limitcuando se alcanzó el límite de lectura de Cloud ascendente,output_limitcuando el resultado filtrado superóBITBUCKET_MAX_DIFF_BYTES, oprovider_limitcuando Server/Data Center marcó su diferencia estructurada como truncada.Las entradas opcionales de
filescontienen solopath,statusnormalizado yoldPathpara cambios de nombre o copias.filesStatusobligatorio informa la integridad;completees falso con el motivomax_files,max_pagesounsupported, yreturnedrefleja las entradas filtradas realmente devueltas.Metadatos opcionales de
ignoredcuando las exclusiones están activas.
Resultado completo:
{
"provider": "cloud",
"pull_request_id": 123,
"rawDiff": "diff --git ...",
"rawDiffBytes": 128,
"rawDiffSource": "provider_raw",
"files": [],
"filesStatus": { "available": true, "complete": true, "returned": 0 },
"truncated": false
}Resultado parcial acotado:
{
"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 truncado es un prefijo de revisión seguro para UTF-8, no necesariamente una línea, fragmento o parche aplicable completo.
Las páginas de archivos estructurados se siguen hasta que se completan o se alcanza un límite de archivos/páginas configurado, y luego se normalizan a metadatos de revisión compactos en lugar de devolver hashes, enlaces y estructuras de ruta duplicadas del proveedor. Un endpoint diffstat o changes no disponible se informa solo después de un HTTP 404. Los errores de autorización, límite de velocidad, servidor, respuesta malformada, tiempo de espera y transporte hacen fallar la llamada a la herramienta en lugar de omitir silenciosamente los metadatos.
rawDiff de Cloud conserva la respuesta sin procesar del proveedor. Server/Data Center usa la respuesta estructurada /diff y normaliza sus archivos, fragmentos, segmentos y líneas en texto de revisión de estilo git; esto evita errores específicos de versión de la ruta de exportación .diff separada. rawDiffSource hace explícita esa distinción.
path es compatible con ambos proveedores y es la forma preferida de revisar solicitudes de extracción grandes archivo por archivo; los metadatos de files devueltos se limitan a la misma ruta. renames es solo de Cloud. context se asigna a context de Cloud y contextLines de Server/Data Center. ignore_whitespace se asigna a ignore_whitespace de Cloud y whitespace=ignore-all de Server/Data Center. Cuando no están presentes, estos controles no alteran los valores predeterminados del proveedor.
Los patrones usan rutas relativas al repositorio y admiten *, ** y ?. Un patrón sin /, como package-lock.json o *.png, coincide con ese nombre de archivo en cualquier lugar. Una barra final excluye un directorio de forma recursiva. Cuando las exclusiones están activas, la respuesta incluye ignored.patterns, ignored.files e ignored.rawDiffFiltered. Un valor falso de rawDiffFiltered significa que un proveedor de Cloud devolvió un formato de diferencia que no es git y que no se pudo filtrar de forma segura; la respuesta se conserva en lugar de eliminar contenido silenciosamente.
add_pull_request_comment
Crea un comentario general, a nivel de archivo o en línea en una solicitud de extracción. Esta operación de escritura solo está disponible cuando BITBUCKET_ENABLE_WRITE_TOOLS=true está establecido en el entorno del servidor MCP.
Comentario general:
{
"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."
}
}Comentario en línea sobre una línea añadida:
{
"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"
}
}Use los valores de line_type added, removed o context. Las líneas añadidas se asignan de forma predeterminada al lado new, las líneas eliminadas al lado old y las líneas de contexto a new; establezca line_side explícitamente para colocar un comentario de contexto en old. Proporcione file_path sin campos de línea para un comentario a nivel de archivo. Para archivos renombrados en Server/Data Center, source_file_path puede identificar la ruta anterior.
El usuario autenticado de Bitbucket se convierte en el autor del comentario. Revise el espacio de trabajo, el repositorio, el ID de la solicitud de extracción y el texto del comentario de destino antes de aprobar la llamada a la herramienta en su cliente MCP.
Comportamiento del proveedor
El host de la URL determina el proveedor. bitbucket.org y api.bitbucket.org usan Bitbucket Cloud; todos los demás hosts usan Server/Data Center.
Las URL de Cloud se normalizan a un prefijo de API /2.0 y usan:
/repositories/{workspace}/{repository}/pullrequests/{id}/repositories/{workspace}/{repository}/pullrequests/{id}/diff/repositories/{workspace}/{repository}/pullrequests/{id}/diffstat/repositories/{workspace}/{repository}/pullrequests/{id}/comments(GET;POSTcuando está habilitado)/repositories/{workspace}/{repository}/pullrequests/{id}/commits(GET)
Las URL de Server/Data Center conservan una ruta de contexto como /bitbucket, se normalizan a un prefijo /rest/api/1.0 y usan:
/projects/{project}/repos/{repository}/pull-requests/{id}/projects/{project}/repos/{repository}/pull-requests/{id}/diff(diferencia estructurada normalizada a texto de revisión de estilo git)/projects/{project}/repos/{repository}/pull-requests/{id}/diff/{path}(diferencia estructurada con ámbito de ruta)/projects/{project}/repos/{repository}/pull-requests/{id}/changes/projects/{project}/repos/{repository}/pull-requests/{id}/comments(GET;POSTcuando está habilitado)/projects/{project}/repos/{repository}/pull-requests/{id}/commits(GET)
La solicitud opcional de diffstat o changes informa filesStatus.reason: "unsupported" después de un HTTP 404. Otros errores HTTP, de tiempo de espera, de transporte y de análisis hacen fallar la llamada a la herramienta para que los metadatos incompletos no se confundan con una respuesta completa.
MCP de Atlassian Rovo
Atlassian documenta una acción bitbucketPullRequest.diff solo para Cloud, pero no publica su esquema de argumentos, forma de salida, paginación, filtrado ni contrato de truncamiento. Por lo tanto, este servidor mantiene las APIs directas de Bitbucket como autoritativas. Un adaptador de Rovo solo debe añadirse tras validar un esquema tools/list en vivo y una respuesta de diff controlada; debe permanecer configurado explícitamente y no puede sustituir el soporte de Server/Data Center. Consulta la página de herramientas compatibles de Atlassian.
Hoja de ruta
Las áreas previstas para futuras versiones incluyen:
Añadir manejo de reintentos y diagnósticos más claros de límite de tasa.
Proporcionar salida normalizada de pull requests manteniendo el acceso a campos específicos del proveedor.
Añadir herramientas de solo lectura para listar pull requests y recuperar el estado de compilación.
Ofrecer un transporte HTTP Streamable opcional manteniendo stdio como predeterminado.
Publicar lanzamientos versionados con rutas de instalación y actualización más sencillas.
Las operaciones de escritura permanecerán deshabilitadas por defecto. No se planean operaciones de aprobación, fusión u otras de alto impacto en Bitbucket. Las ideas y propuestas de implementación son bienvenidas a través de GitHub issues.
Desarrollo
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 CIEl registro de comandos mantiene cada herramienta MCP aislada en src/tools. Consulta CONTRIBUTING.md antes de abrir una pull request.
Seguridad
Este servidor maneja las credenciales en memoria y las envía únicamente al BITBUCKET_URL configurado. Revisa esa URL cuidadosamente antes de iniciar el servidor. Habilitar herramientas de escritura permite que los clientes MCP conectados publiquen comentarios en PR como el usuario autenticado de Bitbucket. Para informar de una vulnerabilidad de forma privada, sigue SECURITY.md.
Licencia
Publicado bajo la Licencia 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.232 npmMIT