How to integrate Bitbucket MCP with Mastra AI

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Bitbucket logo
Mastra AI logo
divider

Introduction

This guide walks you through connecting Bitbucket to Mastra AI using the Composio tool router. By the end, you'll have a working Bitbucket agent that can create a new branch off main, open a pull request for your feature, comment on the latest open issue through natural language commands.

This guide will help you understand how to give your Mastra AI agent real control over a Bitbucket account through Composio's Bitbucket MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

Also integrate Bitbucket with

TL;DR

Here's what you'll learn:
  • Set up your environment so Mastra, OpenAI, and Composio work together
  • Create a Tool Router session in Composio that exposes Bitbucket tools
  • Connect Mastra's MCP client to the Composio generated MCP URL
  • Fetch Bitbucket tool definitions and attach them as a toolset
  • Build a Mastra agent that can reason, call tools, and return structured results
  • Run an interactive CLI where you can chat with your Bitbucket agent

What is Mastra AI?

Mastra AI is a TypeScript framework for building AI agents with tool support. It provides a clean API for creating agents that can use external services through MCP.

Key features include:

  • MCP Client: Built-in support for Model Context Protocol servers
  • Toolsets: Organize tools into logical groups
  • Step Callbacks: Monitor and debug agent execution
  • OpenAI Integration: Works with OpenAI models via @ai-sdk/openai

What is the Bitbucket MCP server, and what's possible with it?

The Bitbucket MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Bitbucket account. It provides structured and secure access to your repositories, issues, and pull requests, so your agent can create branches, manage issues, review code, and handle repository operations for you.

  • Branch and repository management: Let your agent create new branches for feature work or initialize fresh repositories within your Bitbucket workspace—no manual setup required.
  • Automated issue tracking: Have your agent create, comment on, or delete issues to streamline team collaboration and bug tracking directly from your workflows.
  • Pull request automation: Empower your agent to open new pull requests for code review, ensuring changes are properly tracked and integrated.
  • File and snippet operations: Ask your agent to fetch specific files from any branch or commit, or to post comments on code snippets for contextual discussions.
  • User profile and workspace insights: Retrieve your Bitbucket user profile details on demand, making it easy to personalize and audit agent-driven actions.

Supported Tools & Triggers

Tools
Approve Pull RequestTool to approve a pull request as the authenticated user.
Browse repository pathTool to retrieve content for a file path or browse directory contents at a specified revision in a Bitbucket repository.
Create a branchCreates a new branch in a Bitbucket repository from a target commit hash; the branch name must be unique, adhere to Bitbucket's naming conventions, and not include the 'refs/heads/' prefix.
Create an issueCreates a new issue in a Bitbucket repository, setting the authenticated user as reporter; ensures assignee (if provided) has repository access, and that any specified milestone, version, or component IDs exist.
Create an issue commentAdds a new comment with markdown support to an existing Bitbucket issue.
Create a pull requestCreates a new pull request in a specified Bitbucket repository, ensuring the source branch exists and is distinct from the (optional) destination branch.
Create pull request commentCreates a new comment on a Bitbucket pull request.
Create commit report annotationsAdds multiple annotations to a commit report in bulk.
List commits from revision (POST)Tool to list commits from a revision using POST method.
Create repositoryCreates a new Bitbucket 'git' repository in a specified workspace, defaulting to the workspace's oldest project if `project_key` is not provided.
Create snippet commentPosts a new top-level comment or a threaded reply to an existing comment on a specified Bitbucket snippet.
Create team pipeline variableCreates a team-level pipeline configuration variable in Bitbucket.
Create user pipeline variableCreates a user-level pipeline variable for Bitbucket pipelines.
Delete commit commentPermanently deletes a specific comment on a commit.
Delete issuePermanently deletes a specific issue, identified by its `issue_id`, from the repository specified by `repo_slug` within the given `workspace`.
Delete pull request commentPermanently deletes a specific pull request comment (top-level, inline, or threaded reply).
Delete commit report annotationDeletes a single annotation matching the provided ID from a commit report.
Delete repositoryPermanently deletes a specified Bitbucket repository; this action is irreversible and does not affect forks.
Delete snippet watchStops watching a specific snippet.
Delete user pipeline variablePermanently deletes a user-level pipeline configuration variable identified by its UUID.
Get branchRetrieves detailed information about a specific branch in a Bitbucket repository.
Get Commit Build StatusGet a specific build status for a commit in Bitbucket.
Get Commit ChangesTool to retrieve a page of changes made in a specified commit, showing all changed files with their change statistics (lines added/removed, status).
Get commit commentRetrieves a specific comment from a commit by its ID.
Get Commit DiffTool to retrieve the unified diff between two provided revisions or for a single commit in a Bitbucket repository.
Get current user (v2)Tool to retrieve complete profile information for the currently authenticated Bitbucket user.
Get deployment environment variablesRetrieves deployment environment level variables for a specific Bitbucket repository environment.
Get file from repositoryRetrieves a specific file's content from a Bitbucket repository at a given commit (hash, branch, or tag), failing if the file path is invalid for that commit.
Get hook eventsRetrieves a paginated list of all valid webhook events for a specified entity type (repository or workspace).
Get OpenID configuration for OIDC in PipelinesRetrieves the OpenID Connect discovery configuration for Bitbucket Pipelines OIDC.
Get Pull RequestGet a single pull request by ID with complete details.
Get pull request commentTool to retrieve a specific comment from a pull request by its ID.
Get Pull Request CommitsTool to retrieve commits for a specified pull request.
Get Pull Request DiffTool to fetch the unified diff for a Bitbucket pull request (follows 302 redirect to repository diff).
Get Pull Request DiffstatTool to get the diffstat for a Bitbucket pull request, showing all changed files with their change statistics (lines added/removed, status).
Get Repository Branching ModelReturn the branching model as applied to the repository.
Get Repository CommitTool to retrieve detailed information about a specific commit in a Bitbucket repository.
Get commit commentsRetrieves all comments on a specific commit in a Bitbucket repository.
Get commit reportReturns a single report matching the provided ID from a commit.
Get Commit ReportsTool to get reports linked to a specific commit.
Get commit report annotationReturns a single annotation matching the provided ID from a commit report.
Get commit statusesReturns all build statuses (e.
Get effective branching modelRetrieves the effective branching model for a Bitbucket repository, showing which branching model is currently applied (including any inheritance from project-level settings).
Get Repository EnvironmentRetrieve detailed information about a specific deployment environment in a Bitbucket repository.
Get file commit historyReturns a paginated list of commits that modified the specified file.
Check if user voted for issueTool to check whether the authenticated user has voted for a specific issue in a Bitbucket repository.
Get Repositories Merge BaseGet the merge base (best common ancestor) between two commits in a Bitbucket repository.
Get specific pipelineRetrieve a specified pipeline from a Bitbucket repository.
Get repository pipelines cachesRetrieves the repository pipelines caches.
Get repository pipeline runnersRetrieves the list of self-hosted runners configured for a repository's pipelines.
Get repository pipeline schedulesRetrieves configured pipeline schedules for a Bitbucket repository.
Get repository SSH known hostsRetrieves repository-level SSH known hosts configured for Bitbucket Pipelines.
Get repository pipeline variablesRetrieves repository-level pipeline variables for a specific Bitbucket repository.
Get pipeline stepsRetrieves all steps for a given pipeline.
Get pull requests activity logGet paginated activity log for all pull requests in a repository.
Get pull request commentsRetrieves a paginated list of comments on a specific pull request in a Bitbucket repository.
Get pull request statusesReturns all build statuses (e.
Get repository refsReturns the branches and tags in the repository.
Get tagRetrieves detailed information about a specific tag in a Bitbucket repository.
Get repositories srcLists the contents of the root directory on the repository's main branch without needing to specify a commit or branch.
Get repository watchersRetrieves a paginated list of all the watchers on the specified repository.
Get repositoryRetrieves detailed information about a specific repository in a Bitbucket workspace.
Get Repository PatchTool to retrieve the git patch content for a Bitbucket repository at a specified revision or commit range.
Get snippetRetrieves a specific Bitbucket snippet by its encoded ID from an existing workspace, returning its metadata and file structure.
Get snippet watch statusChecks if the current user is watching a specific snippet.
Get SSH keys for userRetrieves a paginated list of SSH keys for a specified Bitbucket user.
Get userRetrieves public profile information for a specific Bitbucket user by username or UUID.
Get user emailsReturns all the authenticated user's email addresses, both confirmed and unconfirmed.
Get user email detailsRetrieves details about a specific email address for the authenticated user.
Get user permissions for repositoriesReturns an object for each repository the caller has explicit access to, including their permission level.
Get user permissions for workspacesRetrieves workspace memberships and permission levels for the authenticated user.
Get user workspacesTool to retrieve all workspaces accessible to the authenticated user.
Get workspaceRetrieves detailed information about a specific Bitbucket workspace.
Get Workspace Pull Requests by UserTool to get all workspace pull requests authored by a specified user.
Search code in workspaceTool to search for code in the repositories of the specified workspace.
List branchesLists branches in a Bitbucket repository with optional server-side filtering by name pattern (BBQL) and sorting.
List commitsTool to retrieve a page of commits from a Bitbucket repository.
List commits from revisionTool to list commits starting from a specific revision in a Bitbucket repository.
List commits on masterLists commits on the master branch of a Bitbucket repository.
List deploymentsLists deployments for a specified Bitbucket repository.
List issues in a repositoryLists issues in a Bitbucket repository with optional filtering by state, priority, kind, or assignee.
List pipelinesTool to find pipelines in a Bitbucket repository.
List pull requestsLists pull requests in a specified, accessible Bitbucket repository, optionally filtering by state (OPEN, MERGED, DECLINED).
List pull request tasksLists all tasks associated with a pull request in a Bitbucket repository.
List all public repositoriesRetrieves a paginated list of all public repositories on Bitbucket.
List repository environmentsList all deployment environments configured for a Bitbucket repository.
List repositories in workspaceLists repositories in a specified Bitbucket workspace, accessible to the authenticated user, with options to filter by role or query string, and sort results.
List repository pathsLists file and directory entries under a repository path at a given revision, with optional breadth-first recursion via max_depth for repository traversal and scanning.
List snippetsReturns all snippets accessible to the authenticated user.
List tagsLists tags in a Bitbucket repository with optional server-side filtering by name pattern or commit hash (BBQL) and sorting.
List versionsLists versions (milestones) in a Bitbucket repository's issue tracker.
List workspace membersLists all members of a specified Bitbucket workspace; the workspace must exist.
List workspace projectsLists projects in a specified Bitbucket workspace.
List workspacesLists Bitbucket workspaces accessible to the authenticated user, optionally filtered and sorted.
Merge Pull RequestTool to merge a Bitbucket Cloud pull request via the REST API.
Request Pull Request ChangesTool to request changes on a pull request as the authenticated user.
Resolve pull request commentTool to resolve or reopen a pull request comment thread.
Search code in user repositoriesTool to search for code in the repositories of a specified user.
Update commit insight reportCreate or update an insight report for a commit.
Update an issueUpdates an existing issue in a Bitbucket repository by modifying specified attributes; requires `workspace`, `repo_slug`, `issue_id`, and at least one attribute to update.
Update Pull RequestTool to update an existing pull request's editable fields (e.
Update commit commentUpdates the contents of a comment on a commit.
Update commit report annotationCreates or updates an individual annotation for a commit report.
Update team pipeline variableUpdates a team-level pipeline configuration variable in Bitbucket.
Update user pipeline variableUpdates a user-level pipeline variable for Bitbucket pipelines.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Prerequisites

Before starting, make sure you have:
  • Node.js 18 or higher
  • A Composio account with an active API key
  • An OpenAI API key
  • Basic familiarity with TypeScript

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key.
  • You need credits or a connected billing setup to use the models.
  • Store the key somewhere safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Go to Settings and copy your API key.
  • This key lets your Mastra agent talk to Composio and reach Bitbucket through MCP.

Install dependencies

bash
npm install @composio/core @mastra/core @mastra/mcp @ai-sdk/openai dotenv

Install the required packages.

What's happening:

  • @composio/core is the Composio SDK for creating MCP sessions
  • @mastra/core provides the Agent class
  • @mastra/mcp is Mastra's MCP client
  • @ai-sdk/openai is the model wrapper for OpenAI
  • dotenv loads environment variables from .env

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your requests to Composio
  • COMPOSIO_USER_ID tells Composio which user this session belongs to
  • OPENAI_API_KEY lets the Mastra agent call OpenAI models

Import libraries and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey as string,
});
What's happening:
  • dotenv/config auto loads your .env so process.env.* is available
  • openai gives you a Mastra compatible model wrapper
  • Agent is the Mastra agent that will call tools and produce answers
  • MCPClient connects Mastra to your Composio MCP server
  • Composio is used to create a Tool Router session

Create a Tool Router session for Bitbucket

typescript
async function main() {
  const session = await composio.create(
    composioUserID as string,
    {
      toolkits: ["bitbucket"],
    },
  );

  const composioMCPUrl = session.mcp.url;
  console.log("Bitbucket MCP URL:", composioMCPUrl);
What's happening:
  • create spins up a short-lived MCP HTTP endpoint for this user
  • The toolkits array contains "bitbucket" for Bitbucket access
  • session.mcp.url is the MCP URL that Mastra's MCPClient will connect to

Configure Mastra MCP client and fetch tools

typescript
const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      nasdaq: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

console.log("Fetching MCP tools from Composio...");
const composioTools = await mcpClient.getTools();
console.log("Number of tools:", Object.keys(composioTools).length);
What's happening:
  • MCPClient takes an id for this client and a list of MCP servers
  • The headers property includes the x-api-key for authentication
  • getTools fetches the tool definitions exposed by the Bitbucket toolkit

Create the Mastra agent

typescript
const agent = new Agent({
    name: "bitbucket-mastra-agent",
    instructions: "You are an AI agent with Bitbucket tools via Composio.",
    model: "openai/gpt-5",
  });
What's happening:
  • Agent is the core Mastra agent
  • name is just an identifier for logging and debugging
  • instructions guide the agent to use tools instead of only answering in natural language
  • model uses openai("gpt-5") to configure the underlying LLM

Set up interactive chat interface

typescript
let messages: AiMessageType[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end.\n");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();

rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

  if (!trimmedInput) {
    rl.prompt();
    return;
  }

  messages.push({
    id: crypto.randomUUID(),
    role: "user",
    content: trimmedInput,
  });

  console.log("\nAgent is thinking...\n");

  try {
    const response = await agent.generate(messages, {
      toolsets: {
        bitbucket: composioTools,
      },
      maxSteps: 8,
    });

    const { text } = response;

    if (text && text.trim().length > 0) {
      console.log(`Agent: ${text}\n`);
        messages.push({
          id: crypto.randomUUID(),
          role: "assistant",
          content: text,
        });
      }
    } catch (error) {
      console.error("\nError:", error);
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    console.log("\nSession ended.");
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • messages keeps the full conversation history in Mastra's expected format
  • agent.generate runs the agent with conversation history and Bitbucket toolsets
  • maxSteps limits how many tool calls the agent can take in a single run
  • onStepFinish is a hook that prints intermediate steps for debugging

Complete Code

Here's the complete code to get you started with Bitbucket and Mastra AI:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({ apiKey: composioAPIKey as string });

async function main() {
  const session = await composio.create(composioUserID as string, {
    toolkits: ["bitbucket"],
  });

  const composioMCPUrl = session.mcp.url;

  const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      bitbucket: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "bitbucket-mastra-agent",
    instructions: "You are an AI agent with Bitbucket tools via Composio.",
    model: "openai/gpt-5",
  });

  let messages: AiMessageType[] = [];

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (input: string) => {
    const trimmed = input.trim();
    if (["exit", "quit"].includes(trimmed.toLowerCase())) {
      rl.close();
      return;
    }

    messages.push({ id: crypto.randomUUID(), role: "user", content: trimmed });

    const { text } = await agent.generate(messages, {
      toolsets: { bitbucket: composioTools },
      maxSteps: 8,
    });

    if (text) {
      console.log(`Agent: ${text}\n`);
      messages.push({ id: crypto.randomUUID(), role: "assistant", content: text });
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main();

Conclusion

You've built a Mastra AI agent that can interact with Bitbucket through Composio's Tool Router. You can extend this further by:
  • Adding other toolkits like Gmail, Slack, or GitHub
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows

How to build Bitbucket MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Bitbucket MCP?

With a standalone Bitbucket MCP server, the agents and LLMs can only access a fixed set of Bitbucket tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Bitbucket and many other apps based on the task at hand, all through a single MCP endpoint.

Can I use Tool Router MCP with Mastra AI?

Yes, you can. Mastra AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Bitbucket tools.

Can I manage the permissions and scopes for Bitbucket while using Tool Router?

Yes, absolutely. You can configure which Bitbucket scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Bitbucket data and credentials are handled as safely as possible.

Used by agents from

Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.