How to integrate Microsoft Power Bi MCP with Mastra AI

This guide walks you through connecting Microsoft Power Bi to Mastra AI using the Composio tool router. By the end, you'll have a working Microsoft Power Bi agent that can list dashboards in your workspace, refresh the sales performance dataset, summarize quarterly revenue report insights through natural language commands. This guide will help you understand how to give your Mastra AI agent real control over a Microsoft Power Bi account through Composio's Microsoft Power Bi MCP server. Before we dive in, let's take a quick look at the key ideas and tools involved.

Microsoft Power Bi logoMicrosoft Power Bi
Oauth2

Microsoft Power BI is Microsoft's business analytics service for dashboards, reports, datasets, and interactive data visualizations. Use it to turn business data into clear insights that teams can explore, share, and act on.

116 Tools

Introduction

This guide walks you through connecting Microsoft Power Bi to Mastra AI using the Composio tool router. By the end, you'll have a working Microsoft Power Bi agent that can list dashboards in your workspace, refresh the sales performance dataset, summarize quarterly revenue report insights through natural language commands.

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

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

Also integrate Microsoft Power Bi 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 Microsoft Power Bi tools
  • Connect Mastra's MCP client to the Composio generated MCP URL
  • Fetch Microsoft Power Bi 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 Microsoft Power Bi 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 Microsoft Power Bi MCP server, and what's possible with it?

The Microsoft Power Bi MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Microsoft Power Bi account. It provides structured and secure access to your workspaces, dashboards, reports, datasets, dataflows, and scorecards, so your agent can create analytics resources, retrieve business insights, run DAX queries, manage reports, and prepare content for embedding on your behalf.

  • Workspace and dashboard management: Have your agent create or delete workspaces, add dashboards, and list the dashboards available in a workspace.
  • Report and dataset operations: Let the agent retrieve datasets, list reports from an app, clone reports, delete reports, and create push datasets.
  • Business data analysis: Direct your agent to run DAX queries against Power BI datasets and return the results for analysis or summaries.
  • Scorecard and goal tracking: Instruct your agent to create scorecards, record goal value check-ins, and remove goals, notes, or status rules when needed.
  • Embedded analytics access: Have your agent generate viewing or editing tokens for dashboards, reports, and datasets that you want to embed in an application.

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

Step by step09 STEPS
1

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
2

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 Microsoft Power Bi through MCP.
3

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
4

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
5

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
6

Create a Tool Router session for Microsoft Power Bi

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

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

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 Microsoft Power Bi toolkit
8

Create the Mastra agent

typescript
const agent = new Agent({
    name: "microsoft_power_bi-mastra-agent",
    instructions: "You are an AI agent with Microsoft Power Bi 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
9

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: {
        microsoft_power_bi: 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 Microsoft Power Bi 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 Microsoft Power Bi 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: ["microsoft_power_bi"],
  });

  const composioMCPUrl = session.mcp.url;

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

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "microsoft_power_bi-mastra-agent",
    instructions: "You are an AI agent with Microsoft Power Bi 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: { microsoft_power_bi: 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 Microsoft Power Bi 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
TOOLS

Supported Tools

Every Microsoft Power Bi action and event your agent gets out of the box.

Add Dashboard to Workspace

Creates a new empty dashboard in the specified workspace.

Get Reports From App

Returns a list of reports from the specified app.

Assign Workspace to Capacity

Assigns the specified workspace to the specified capacity.

Cancel Dataset Refresh in Workspace

Cancels the specified refresh operation for the specified dataset from the specified workspace.

Clone Report

Clones the specified report from My workspace.

Clone Report in Workspace

Clones the specified report from the specified workspace.

Create Goal Value Check-in

Creates a new goal value check-in for a Power BI scorecard goal.

Create Workspace

Creates a new workspace in Power BI.

Create Push Dataset

Creates a new dataset on My workspace in Power BI.

Create Scorecard

Creates a new scorecard in the specified Power BI workspace.

Create Temporary Upload Location

Creates a temporary blob storage upload location for importing large Power BI .

Create Temporary Upload Location

Creates a temporary blob storage upload location for importing large Power BI .

Delete Dashboard

Deletes the specified dashboard from My workspace.

Delete Dataflow

Deletes the specified dataflow from Power BI data prep storage, including its definition file and model.

Delete Dataset

Deletes the specified dataset from My workspace.

Delete Dataset from Workspace

Deletes the specified dataset from the specified workspace.

Delete Goal

Deletes a goal from a scorecard by goal ID.

Delete Goal Note by ID

Deletes a goal value check-in note by its unique identifier.

Delete Goal Status Rules

Removes status rule definitions from a goal.

Delete Pipeline User

Removes user permissions from the specified deployment pipeline.

Delete Report from Workspace

Deletes the specified report from the specified workspace.

Delete Rows from Dataset Table

Deletes all rows from the specified table within the specified dataset from My workspace.

Delete Rows from Dataset Table in Workspace

Deletes all rows from the specified table within the specified dataset from the specified workspace.

Delete Scorecard By ID

Deletes a scorecard by its ID from the specified workspace.

Delete Workspace

Deletes the specified workspace.

Discover Gateways for Dataset

Returns a list of gateways that the specified dataset from the specified workspace can be bound to.

Execute DAX Queries

Executes Data Analysis Expressions (DAX) queries against the provided dataset in My workspace.

Execute DAX Queries on Dataset

Executes Data Analysis Expressions (DAX) queries against the specified Power BI dataset.

Execute Subscription

Executes the Subscription specified by the Id.

Generate Dashboard Embed Token

Generates an embed token to view or edit the specified dashboard from the specified workspace.

Generate Embed Token for Power BI

Generates an embed token for multiple reports, datasets, and target workspaces.

Generate Report Embed Token in Group

Generates an embed token to view or edit the specified report from the specified workspace.

Generate Dataset Embed Token in Group

Generates an embed token based on the specified dataset from the specified workspace.

Get Available Feature By Name

Returns the specified available feature for the user by name.

Get Capacities

Returns a list of Power BI capacities that the authenticated user has access to.

Get Dashboard from My Workspace

Returns the specified dashboard from My workspace.

Get Dashboards

Returns a list of dashboards from the specified workspace.

Get Dataflows

Returns a list of all dataflows from the specified workspace.

Get Dataset

Returns the specified dataset from My workspace.

Get Dataset in Workspace

Returns the specified dataset from the specified workspace.

Get DataSet Data

Gets the query results for the specified DataSet.

Get Datasets from My Workspace

Returns a list of datasets from My workspace.

Get DataSets from Power BI

Gets an array of DataSet CatalogItems from Power BI.

Get Dataset to Dataflows Links

Returns a list of upstream dataflows for datasets from the specified workspace.

Get Dataset Users

Returns a list of principals that have access to the specified dataset.

Get Dataset Users In Group

Returns a list of principals that have access to the specified dataset within a workspace.

Get Datasources for Dataset

Returns a list of data sources for the specified dataset from My workspace.

Get Datasources for Dataset in Workspace

Returns a list of data sources for the specified dataset from the specified workspace.

Get Gateway

Returns the specified gateway.

Get Gateway Datasources in Group

Returns a list of gateway data sources for the specified dataset from the specified workspace.

Get Gateways

Returns a list of gateways for which the user is an admin.

Get Goals from Scorecard

Returns a list of goals from a scorecard.

Get Goals Refresh History

Reads refresh history of a connected goal.

Get Goals Status Rules

Returns status rules of a goal.

Get Goal Value By ID

Reads a goal value check-in by a UTC date timestamp.

Get Groups

Returns a list of workspaces the user has access to.

Get Groups Capacity Assignment Status

Gets the status of the assignment-to-capacity operation for the specified workspace.

Get Group Users

Returns a list of users that have access to the specified workspace.

Get Import

Returns the specified import from My workspace.

Get Imports from My Workspace

Returns a list of imports from My workspace.

Get Imports in Workspace

Returns a list of imports from the specified workspace.

Get Linked Report History Snapshot

Gets requested HistorySnapshot item specified by HistoryId of the LinkedReport specified by Id.

Get Report Page

Returns the specified page within the specified report from the specified workspace.

Get Pages from Report

Returns a list of pages within the specified report from the specified workspace.

Get Pages from Report in My Workspace

Returns a list of pages within the specified report from My workspace.

Get Dataset Parameters

Returns a list of parameters for the specified dataset from **My workspace**.

Get Dataset Parameters in Workspace

Returns a list of parameters for the specified dataset from the specified workspace.

Get Query Scale Out Sync Status

Returns the query scale-out sync status for the specified dataset from the specified workspace.

Get Refreshable For Capacity

Returns the specified refreshable for the specified capacity that the user has access to.

Get refreshables for all capacities

Returns a list of refreshables for all capacities that the user has access to.

Get Refresh Execution Details In Group

Returns execution details of a refresh operation for the specified dataset from the specified workspace.

Get Refresh History for Dataset

Returns the refresh history for the specified dataset from My workspace.

Get Dataset Refresh Schedule

Returns the refresh schedule for the specified dataset from My workspace.

Get Refresh Schedule In Group 2

Returns the refresh schedule for the specified dataset from the specified workspace.

Get Report from My Workspace

Returns the specified report from My workspace.

Get Report Page From My Workspace

Returns the specified page within the specified report from My workspace.

Get Reports

Gets an array of Report CatalogItems from Power BI.

Get Reports From My Workspace

Returns a list of reports from My workspace.

Get Resources

Gets an array of Resource catalog items.

Get Scorecard By ID

Returns a scorecard with the specified ID.

Get Scorecards

Returns a list of scorecards from a workspace.

Get Tables in Dataset

Returns a list of tables within the specified dataset from My workspace.

Get Tables in Dataset within Workspace

Returns a list of tables within the specified dataset from the specified workspace.

Get Tiles from My Workspace Dashboard

Returns a list of tiles within the specified dashboard from My workspace.

Get Tiles from Workspace Dashboard

Returns a list of tiles within the specified dashboard from the specified workspace.

Get Workspace

Returns a specified workspace (group).

Trigger Query Scale Out Sync in Workspace

Triggers a query scale-out sync of read-only replicas for the specified dataset from the specified workspace.

Move Power BI Scorecard Goals

Moves goals within the scorecard.

Patch Goal Note

Updates a goal value check-in note by ID.

Patch Goal Value By ID

Updates a goal value check-in by a UTC date timestamp.

Patch Scorecard By ID

Updates a scorecard by its ID.

Create Push Dataset in Workspace

Creates a new push dataset in the specified Power BI workspace.

Grant Dataset User Permissions

Grants the specified user's permissions to the specified dataset.

Grant Dataset User Permissions In Group

Grants the specified user's permissions to the specified dataset in a workspace.

Post Goal

Adds a new goal to a Power BI scorecard.

Post Goal Note

Adds a new note to a goal value check-in for a Power BI scorecard goal.

Add Rows to Dataset Table in Workspace

Adds new data rows to the specified table within the specified dataset from the specified workspace.

Post Goal Status Rules

Creates or updates status rules of a goal in Power BI.

Update Table Schema

Updates the metadata and schema for the specified table within the specified dataset from My workspace.

Update Table Schema in Workspace

Updates the metadata and schema for the specified table within the specified dataset from the specified workspace.

Rebind Report to Dataset

Rebinds the specified report from the specified workspace to the specified dataset.

Trigger Dataset Refresh in Workspace

Triggers a refresh for the specified dataset from the specified workspace.

Generate Report Embed Token for Create in Group

Generates an embed token to allow report creation in the specified workspace based on the specified dataset.

Set Linked Report Cache Options

Replaces the CacheOption's content for a given LinkedReport using the provided definition.

Take Over Dataset

Transfers ownership over the specified dataset to the current authorized user.

Take Over Paginated Report Ownership

Transfers ownership of the data sources for the specified paginated report (RDL) to the current authorized user.

Trigger Query Scale Out Sync

Triggers a query scale-out sync of read-only replicas for the specified dataset from My workspace.

Update Dataset

Updates the properties for the specified dataset from My workspace.

Update Dataset In Workspace

Updates the properties for the specified dataset from the specified workspace.

Update Paginated Report Data Sources

Updates the data sources of the specified paginated report (RDL) from the specified workspace.

Patch Goal By ID

Updates a goal by its ID within a Power BI scorecard.

Update Dataset Parameters in Workspace

Updates the parameters values for the specified dataset from the specified workspace.

Update Refresh Schedule

Updates the refresh schedule for the specified dataset from My workspace.

Update Refresh Schedule In Group

Updates the refresh schedule for the specified dataset from the specified workspace.

Update Report Content

Updates the content of the specified report from **My workspace** with the content of a specified source report.

Update Workspace

Updates the properties for the specified workspace.

FAQ

Frequently asked questions

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

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 Microsoft Power Bi tools.

Yes, absolutely. You can configure which Microsoft Power Bi 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.

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 Microsoft Power Bi data and credentials are handled as safely as possible.

Start with Microsoft Power Bi.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Microsoft Power Bi tool your agent needs.Free to start.

Start building