power-bi-mcp
Power BI MCP Server
An MCP (Model Context Protocol) server that lets AI agents manage Power BI workspaces, datasets, and refreshes via natural language.
For refresh incidents, the server brings dataset context, execution errors, same-workspace report dependencies, and optional local PBIP source hints into one evidence bundle. An agent can use it to propose the next investigation step while leaving fixes and operational decisions to the operator.
Walk through a simulated refresh diagnosis, or follow Quick Start to connect your MCP client.
Features
Authentication & Discovery
Tool | Description |
| Authenticate via Azure AD device code flow (with token caching & auto-refresh) |
| List accessible workspaces (with optional name filter) |
| List datasets in a workspace |
Dataset & Refresh Management
Tool | Description |
| Aggregate dataset metadata + datasources + gateways + refresh schedule + impacted reports + PBIP locate (single call) |
| Trigger an Enhanced refresh (supports table-level, polling, retry, timeout) |
| Refresh lifecycle: view history ( |
Diagnostics & Source Code
Tool | Description |
| Collect refresh evidence, classify known errors, suggest next actions, and link matching local PBIP source |
| Locate PBIP source code for a dataset (fuzzy folder match + optional table TMDL & M source extraction) |
Query & Reporting
Tool | Description |
| Execute DAX queries against a dataset (supports RLS impersonation) |
| Generate a daily scheduled-refresh status report across all datasets in a workspace (JSON or Markdown table) |
Related MCP server: powerbi-mcp-local
Example: diagnose a failed dataset refresh
Simulated demonstration — not a real Power BI execution. All names, IDs, paths, service responses, source code, and agent conclusions below are fictional. The example illustrates the current tool contract; it does not demonstrate a production incident, a successful repair, or measured time savings.
A failed refresh can leave several tables marked as failed. This workflow connects execution messages to a candidate table, matching local source, and reports that may still show stale data, giving the operator a concrete place to investigate.
1. Ask the agent
In "Demo Operations", the "Demo Sales" dataset failed to refresh. Find the likely cause, show which reports in this workspace may be affected, and tell me what to inspect before retrying. Do not change settings or start a refresh.
For this example, assume:
The MCP server is connected and authentication has completed through
pbi_auth; the signed-in user can read the workspace, dataset, and refresh details.The dataset has a failed Enhanced API refresh with structured
messagesandobjects.Optional source lookup is enabled through
pbip_root, with a readable local file at<pbip_root>/Demo Sales/Demo Sales.SemanticModel/definition/tables/fact_sales.tmdl.
2. Resolve the target, then diagnose
The agent discovers the workspace, then lists its datasets and uses the returned IDs. In this simulated discovery, "Demo Operations" maps to 11111111-1111-1111-1111-111111111111 and "Demo Sales" maps to 22222222-2222-2222-2222-222222222222.
Illustrative MCP tool names and arguments, called in order after reading each discovery result (these are not JSON-RPC envelopes):
[
{
"name": "pbi_list_workspaces",
"arguments": {"filter": "Demo Operations"}
},
{
"name": "pbi_list_datasets",
"arguments": {"workspace_id": "11111111-1111-1111-1111-111111111111"}
},
{
"name": "pbi_diagnose",
"arguments": {
"workspace_id": "11111111-1111-1111-1111-111111111111",
"dataset_id": "22222222-2222-2222-2222-222222222222",
"refresh_id": ""
}
}
]The interface is pbi_diagnose(workspace_id: str, dataset_id: str, refresh_id: str = "") -> str. It returns a JSON-encoded string. With an empty refresh_id, it reads the latest 10 refresh records and selects the first record in API response order with status == "Failed" and refreshType == "ViaEnhancedApi". This may differ from the most recent scheduled or on-demand failure. To investigate a known incident, pass its requestId as refresh_id.
3. Read the evidence
Simulated output excerpt: selected fields from the decoded JSON string are shown below; other metadata, history, and nested fields are omitted for readability. Field names and nesting follow the implementation.
{
"dataset_summary": {
"id": "22222222-2222-2222-2222-222222222222",
"name": "Demo Sales"
},
"target_refresh_id": "33333333-3333-3333-3333-333333333333",
"target_refresh": {
"status": "Failed",
"messages": [
{
"type": "Error",
"code": "0xC1450012",
"message": "Expression.Error: The column '' of the table wasn't found.",
"location": {"SourceObject": {"Table": "fact_sales", "Partition": "fact_sales"}}
},
{
"type": "Error",
"code": "0xC11C0006",
"message": "Cancelled because another table in the same transaction failed.",
"location": {"SourceObject": {"Table": "dim_date", "Partition": "dim_date"}}
}
],
"objects": [
{"table": "fact_sales", "partition": "fact_sales", "status": "Failed"},
{"table": "dim_date", "partition": "dim_date", "status": "Failed"}
]
},
"classification": {
"root_cause_table": "fact_sales",
"root_cause_partition": "fact_sales",
"root_cause_column": null,
"error_code": "0xC1450012",
"error_category": "MashupDataAccessError",
"underlying": {
"pattern": "EmptyColumnReference",
"snippet": "Expression.Error: The column '' of the table wasn't found."
},
"failed_user_tables": ["dim_date", "fact_sales"],
"next_actions": [
"Open PBIP and inspect M expression of table 'fact_sales'. Call pbi_locate_pbip with this table name; then grep for empty column refs: Table[\"\"], Field=\"\", PromoteHeaders missing source columns."
]
},
"impacted_reports": [
{"id": "44444444-4444-4444-4444-444444444444", "name": "Demo Sales Overview"}
],
"pbip_locate": {
"status": "found",
"matches": [
{
"match_type": "exact",
"tables_dir": "/demo/pbip/Demo Sales/Demo Sales.SemanticModel/definition/tables"
}
]
},
"root_cause_source": {
"table_name": "fact_sales",
"file": "/demo/pbip/Demo Sales/Demo Sales.SemanticModel/definition/tables/fact_sales.tmdl"
}
}The agent can now follow an inspectable chain:
The first
Errormessage withlocation.SourceObject.Tableidentifiesfact_salesand its partition as the initial investigation candidate.0xC1450012maps toMashupDataAccessError, and the message matches the catalog'sEmptyColumnReferencepattern. The laterdim_datecancellation may be a cascade; a failed-table list alone does not prove two independent faults.The PBIP lookup finds a matching folder and table file. Its fictional M partition is shown separately below. When extraction succeeds,
root_cause_source.partition_source_mcontains the extracted TMDL partition body, includingsource =.
Fictional local TMDL source:
table fact_sales
partition fact_sales = m
mode: import
source =
let
Source = #table({"OrderId", "SalesAmount"}, {{1, 100}}),
SelectedColumns = Table.SelectColumns(Source, {""})
in
SelectedColumns
annotation PBI_ResultType = TableHere, Table.SelectColumns asks for an empty column name, while the fictional source defines only OrderId and SalesAmount. This corroborates the error pattern and gives the operator a specific expression to inspect. The tool does not choose the intended replacement column.
Illustrative agent conclusion, not tool output or a verified repair:
Start with the
fact_salesM expression: it selects an empty column name. Confirm the intended column and upstream schema before editing; if the intent is to selectSalesAmount, replace{""}with{"SalesAmount"}only after that check. Validate the change in Power Query/Power BI Desktop, confirm the local PBIP version matches the deployed model, then publish and retry through your normal approval process. Review the next refresh result to verify recovery.dim_datemay have failed as a consequence of the same transaction. The bound "Demo Sales Overview" report in this workspace may still show stale data. This diagnosis has not changed settings or started a refresh.
4. Know the limits
Area | Implemented behavior and required human judgment |
Refresh selection | Automatic selection covers failed |
Missing evidence | No eligible refresh produces |
Error classification |
|
Local source | Requires an existing, readable |
Report impact |
|
Remediation | This workflow reads evidence and suggests actions. It does not edit M, reset credentials, publish a model, or prove recovery. Refresh/cancel tools are separate capabilities; an operator must decide whether and when to use them. |
Implementation references: diagnostic tool, classification and PBIP lookup, error catalog, dataset/report context, and refresh history/details.
Architecture
server.py # Entry point — configures logging, runs MCP via stdio
app.py # FastMCP instance with server instructions
config.py # Configuration loader (config.json, defaults, constants)
auth.py # Azure AD device code flow, token caching, HTTP helpers
diagnostics.py # Refresh error classification, PBIP folder/table locator
error_catalog.py # Error code catalog + regex patterns for failure classification
tools/ # MCP tool modules (auto-registered via __init__.py)
├── auth_tool.py # pbi_auth
├── workspace.py # pbi_list_workspaces, pbi_list_datasets
├── dataset.py # pbi_dataset_info
├── refresh.py # pbi_refresh_dataset, pbi_refresh_manage
├── diagnose.py # pbi_diagnose, pbi_locate_pbip
├── query.py # pbi_execute_query
└── report.py # pbi_scheduled_refresh_report
setup.ps1 # Azure AD App Registration automation (PowerShell)
config.json # User-specific config (gitignored)Quick Start
1. Install dependencies
git clone https://github.com/FreelexHo/power-bi-mcp.git && cd power-bi-mcp
uv venv && uv syncpython -m venv .venv
# Windows
.venv\Scripts\activate
# macOS/Linux
source .venv/bin/activate
pip install -e .2. Register in your MCP client
Add to your MCP client configuration:
Cursor / Windsurf / Antigravity IDE (mcp.json):
{
"mcpServers": {
"power-bi": {
"command": "uv",
"args": ["run", "--directory", "/path/to/power-bi-mcp", "server.py"],
"transport": "stdio"
}
}
}3. Authenticate (one-time)
Just use the MCP! On first use, the agent will call pbi_auth and show you a message like:
To sign in, visit https://microsoft.com/devicelogin
and enter the code XXXXXXXXOpen the link in your browser
Enter the code shown
Sign in with your Microsoft work account
Approve the permissions
That's it. Tokens are cached to ~/.powerbi-mcp/token.json and auto-refreshed — you won't need to do this again unless you revoke access.
Configuration
The server works out of the box with a built-in public client_id. Create a config.json in the project root to customize:
{
"client_id": "<your-azure-ad-client-id>",
"token_cache_dir": "~/.powerbi-mcp",
"pbip_root": "C:/path/to/your/pbip-repo/data/power-bi-report"
}Key | Default | Description |
| Built-in public app | Azure AD App Registration client ID |
|
| Directory for cached OAuth tokens |
| (none) | Local PBIP repo root — enables |
A setup.ps1 script is included to automate App Registration creation via Azure CLI. See Advanced Setup below.
Troubleshooting
AADSTS7000218: The request body must contain ... client_assertion
Your organization may block public client flows. Ask your Azure AD admin to either:
Allow public client flows on the app registration, or
Create a dedicated App Registration for your team (use
setup.ps1)
AADSTS65001: The user or administrator has not consented
First-time users in a new Azure AD tenant need to consent to Power BI permissions. If your tenant requires admin consent:
Ask your admin to grant consent via Azure Portal -> App registrations -> API permissions -> "Grant admin consent"
Or use
setup.ps1to create your own App Registration where you are the owner
AADSTS50076: MFA required or AADSTS50079
Multi-factor authentication is required by your organization. The device code flow supports MFA — complete the MFA challenge in your browser when prompted.
Not authenticated. Call pbi_auth first.
Token has expired and could not be refreshed. The agent should automatically re-trigger pbi_auth. If it doesn't, ask the agent to call pbi_auth again.
Token keeps expiring
By default, tokens are cached at ~/.powerbi-mcp/token.json. Make sure:
The directory is writable
You are not running multiple instances that overwrite each other's tokens
Refresh details return 403
A 403 on pbi_refresh_manage action=details typically indicates insufficient permissions or the refresh record has expired.
Advanced Setup
For organizations that require their own App Registration:
Prerequisites
Azure AD permissions to create App Registrations
Run setup
./setup.ps1This creates an Azure AD App Registration with the correct configuration:
Setting | Value |
Sign-in audience | Multi-tenant (any Azure AD directory) |
Public client flows | Enabled |
Redirect URI |
|
API Permissions |
|
Tech Stack
Python ≥ 3.10
FastMCP (
mcp[cli]≥ 1.6.0) — MCP server framework, stdio transporthttpx ≥ 0.27.0 — HTTP client for Azure AD & Power BI REST API calls
License
MIT
Available Tools
11 toolspbi_authA
Authenticate to Power BI service.
Checks for cached token first, attempts refresh if expired, falls back to device code flow if needed.
Returns: JSON with authentication status and instructions if user action needed.
Inputs: no named parameters. Returns: result
pbi_dataset_infoA
Aggregate dataset metadata + datasources + bound gateways + refresh schedule + impacted reports.
Single call that returns everything needed to understand dataset configuration without making multiple round-trips. Useful for diagnostics and context-gathering.
Args: workspace_id: The workspace (group) ID. dataset_id: The dataset ID.
Returns: JSON object: {dataset, datasources, gateways, schedule, impacted_reports, pbip_locate}
Inputs: workspace_id (required), dataset_id (required). Returns: result
pbi_diagnoseA
One-shot diagnostic report for a Power BI dataset refresh failure.
Pipeline:
Pull dataset metadata + datasources + gateways + schedule + impacted reports.
Pick a refresh to analyze: explicit refresh_id, OR latest Failed ViaEnhancedApi refresh.
Fetch refresh execution details (messages, objects, attempts).
Classify error: root cause table/partition, error code, underlying pattern, next actions.
Add PBIP source code locate hint (folder path, expressions.tmdl, table file).
Args: workspace_id: The workspace (group) ID. dataset_id: The dataset ID. refresh_id: Optional specific refresh requestId. If omitted, auto-picks latest failed Enhanced refresh.
Returns: Structured JSON diagnostic report.
Inputs: workspace_id (required), dataset_id (required), refresh_id. Returns: result
pbi_execute_queryA
Execute a DAX query against a Power BI dataset and return the result rows.
Uses the Execute Queries REST API (POST executeQueries). Only DAX queries are supported; MDX and DMV are not.
Limitations (enforced by the Power BI service):
One query per call, one table per query.
Max 100,000 rows or 1,000,000 cell values (whichever is hit first).
Max 15 MB per response payload.
120 requests/minute/user rate limit.
Args:
workspace_id: The workspace (group) ID.
dataset_id: The dataset ID.
query: A DAX query string, e.g. EVALUATE SUMMARIZECOLUMNS(...).
impersonated_user: Optional UPN for RLS impersonation (ignored if model has no RLS).
include_nulls: Whether null values are serialised in the response (default True).
Returns: JSON with {rows, row_count} on success, or {error, ...} on failure.
Inputs: workspace_id (required), dataset_id (required), query (required), impersonated_user, +1 more. Returns: result
pbi_list_datasetsA
List datasets in a Power BI workspace.
Args: workspace_id: The workspace (group) ID.
Returns: JSON array: [{id, name, configuredBy, isRefreshable, isOnPremGatewayRequired}]
Inputs: workspace_id (required). Returns: result
pbi_list_workspacesA
List Power BI workspaces accessible to the authenticated user.
Args: filter: Optional name filter (case-insensitive substring match).
Returns: JSON array of workspaces: [{id, name, type, state, isOnDedicatedCapacity, capacityId}]
Inputs: filter. Returns: result
pbi_local_modelA
Read local PBIP semantic model structure (TMDL files, no Desktop connection needed).
Requires 'pbip_root' configured in config.json.
Actions:
overview: Model summary - all tables with column/measure counts, relationship count.
table: Single table detail - columns, measures, partition M expression. Requires name.
measure: Single measure DAX expression + metadata. Requires name (fuzzy match across all tables).
expressions: Shared M expressions (datasource definitions).
relationships: All model relationships with from/to table.column and cardinality.
Args: dataset_name: Dataset name as it appears in Power BI Service. action: overview | table | measure | expressions | relationships name: Table or measure name (required for action=table/measure).
Returns: Structured JSON with model information.
Inputs: dataset_name (required), action, name. Returns: result
pbi_locate_pbipA
Locate PBIP source code for a dataset (and optionally read a specific table's TMDL + M source).
Requires 'pbip_root' configured in config.json (path to local PBIP repo root, e.g. 'C:/repos/my-project/data/power-bi-report').
Args: dataset_name: Dataset name as it appears in Power BI Service (e.g. 'QC Compliance Report'). Folder match is fuzzy: case-insensitive + non-alphanumeric stripped. table_name: Optional table name. If provided and dataset found, reads that table's .tmdl and extracts its partition M source.
Returns: JSON with {status, matches[], optional table content + partition_source_m}.
Inputs: dataset_name (required), table_name. Returns: result
pbi_refresh_datasetA
Trigger an Enhanced refresh for a Power BI dataset.
Uses the Enhanced Refresh API (refreshType=ViaEnhancedApi), which enables GET refresh execution details with structured messages[] and objects[] (partition-level failures, error codes, SourceObject pointing to Table/Column/etc).
Args: workspace_id: The workspace (group) ID. dataset_id: The dataset ID. refresh_type: Full / ClearValues / Calculate / DataOnly / Automatic / Defragment (default Full). commit_mode: Transactional / PartialBatch (default Transactional). retry_count: Number of automatic retries (default 0). timeout: HH:MM:SS string, max 24:00:00 (default 01:00:00). tables: Optional list of table names to refresh, e.g. ["fact_sales", "dim_date"]. When omitted the entire dataset is refreshed. poll: If True, poll refresh details until terminal (default False). poll_interval: Seconds between polls (default 30). poll_timeout: Max seconds to wait when polling (default 1800).
Returns: JSON with {status, requestId, location, ...}. If poll=True also includes terminal details.
Inputs: workspace_id (required), dataset_id (required), refresh_type, commit_mode, +6 more. Returns: result
pbi_refresh_manageA
Manage refresh lifecycle: view history, get execution details, or cancel.
Actions:
status: List recent refreshes (lightweight). Returns [{requestId, refreshType, startTime, endTime, status}].
details: Get execution details for a specific refresh (attempts, timing, status). Requires refresh_id. Works for all refresh types (Enhanced, OnDemand, Scheduled). Enhanced refreshes return richer data (messages, objects with partition-level detail); standard refreshes return basic timing/status.
cancel: Cancel an in-progress Enhanced refresh. Requires refresh_id.
Args: workspace_id: The workspace (group) ID. dataset_id: The dataset ID. action: Operation to perform - "status", "details", or "cancel". refresh_id: Required for "details" and "cancel" actions. top: Number of recent refreshes for "status" action (default 5). format: Output format - "json" (default) or "table" (Markdown table with local times).
Returns: JSON or Markdown table with action-specific results.
Inputs: workspace_id (required), dataset_id (required), action, refresh_id, +2 more. Returns: result
pbi_scheduled_refresh_reportA
List scheduled refresh status for every dataset that had scheduled refreshes recently.
Scans all refreshable datasets in a workspace, identifies those with any Scheduled refresh in the past 7 days, and reports refresh records for the target date (local display timezone). If a qualified dataset has no refresh on the target date, its most recent Scheduled refresh is shown instead (e.g. when Power BI auto-disabled the schedule after repeated failures).
Each record includes a current_status snapshot of the dataset's most
recent refresh (any type), so the reader can tell whether a past Scheduled
failure has since been resolved by an on-demand or API-triggered refresh.
Note: Scheduled refreshes do NOT support the Enhanced Refresh Details API, so error info comes from serviceExceptionJson only.
Args: workspace_id: The workspace (group) ID. date: Optional date string (YYYY-MM-DD) in display timezone. Defaults to today. format: Output format - "json" (default) or "table" (Markdown table).
Returns: JSON report or Markdown table with flat refresh records and workspace-level summary.
Inputs: workspace_id (required), date, format. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 11 tools
Every tool focuses on a distinct Power BI operation—auth, dataset info, diagnostics, querying, listing, refreshing, managing refreshes, and local model exploration—with no functional overlaps. Descriptions clearly differentiate each tool's role.
All tools share a consistent 'pbi_' prefix. Most follow a verb_noun pattern (e.g., pbi_list_datasets, pbi_execute_query), but a few deviate (e.g., pbi_auth is a bare verb, pbi_local_model is adjective_noun, pbi_scheduled_refresh_report is lengthy). Overall pattern is recognizable.
11 tools is well-scoped for a Power BI dataset-focused server. It covers authentication, workspace/dataset listing, dataset info, DAX queries, refresh triggering, refresh management, diagnostics, and local source file interaction without bloat.
The tool surface provides strong coverage for dataset lifecycle: query, refresh, diagnose failures, and inspect local models. Minor gaps exist, such as no direct tool for creating or deleting datasets, but these are often handled outside the server's intended scope.
Maintenance
Related MCP Connectors
MCP server for building and testing AI agents with multi-model experimentation and insights.
Official Microsoft MCP Server to query Microsoft Entra data using natural language
MCP server that lets your AI assistant build and deploy apps, hosting each one at a live URL.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA Python-based MCP server that enables interaction with Microsoft Fabric APIs for managing workspaces, lakehouses, warehouses, and tables through natural language.17-
- AlicenseCqualityCmaintenanceLocal-first MCP server for Power BI Desktop automation. Automate semantic model changes, DAX, Power Query, Excel, and report layout from MCP-capable AI clients.1002MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server for Microsoft Fabric that enables AI agents to query and analyze Lakehouse and Eventhouse data, and manage Eventstreams, using natural language through the MCP interface.MIT
- AlicenseNot gradedqualityDmaintenanceA Python-based MCP server that exposes Power BI semantic models to Claude, enabling natural-language querying of Power BI data through tools like listing workspaces, exploring datasets, executing DAX queries, and triggering refreshes.MIT