mcp-server-powerbi
# mcp-server-powerbi
A [Model Context Protocol](https://modelcontextprotocol.io) server for [Microsoft Power BI](https://learn.microsoft.com/en-us/rest/api/power-bi/). It lets an MCP client (Claude or any other MCP-capable assistant) find reports and semantic models, ask the numbers behind them with DAX, follow refreshes and, when enabled, start a refresh.
> This is an independent, unofficial project. It is not developed, endorsed or supported by Microsoft. Power BI is a trademark of Microsoft.
- Acts as one person: it uses that person's Microsoft Entra access token (delegated), so their own rights in Power BI and the models' row-level security apply.
- Read-only by default; the one write (starting a refresh) is opt-in per instance.
- One access token per server instance; the server does no per-user authorization itself (see [Security model](#security-model)).
- Two transports: stdio for local clients, stateless streamable HTTP for containers and gateways.
- Embeddable: the `./gateway` export exposes the same tools, validation, policy and audit to a host application.
## Tools
| Tool | Purpose |
|---|---|
| `powerbi_list_workspaces` | Workspaces the person can see, optionally by name. |
| `powerbi_list_reports` | Reports in a workspace or in "My workspace", with the semantic model each one reads. |
| `powerbi_report_pages` | The pages of a report, in order. |
| `powerbi_list_datasets` | Semantic models (datasets) in a workspace: owner, refreshable, row-level security. |
| `powerbi_get_dataset` | One semantic model. |
| `powerbi_find` | Find reports and models by name across the person's workspaces (at most 200 searched; the answer says whether all were). |
| `powerbi_model_columns` | Tables and columns of a model (`COLUMNSTATISTICS()`; measures are not listed by the API). |
| `powerbi_summarize` | Measures grouped by columns, filtered by values or a date range, optionally the top N. Built from names, never from DAX text. |
| `powerbi_query` *(broad)* | One DAX query (`EVALUATE ...`) through Execute Queries. |
| `powerbi_refresh_history` | The latest refreshes of a model and why one failed. |
| `powerbi_refresh_schedule` | When a model refreshes automatically. |
| `powerbi_refresh_dataset` *(write)* | Start a refresh of a model now, without a mail from Power BI. |
Every tool answers in a fixed form (`outputSchema`). A DAX answer is `{ columns, rows, rowCount, truncated }`: the column names as Power BI gives them (`Table[Column]`, `[Measure]`) and one array of values per row.
### What Power BI requires
- **Delegated permissions** on the Power BI Service for the app that signs the person in (`Workspace.Read.All`, `Report.Read.All`, `Dataset.Read.All`, and `Dataset.ReadWrite.All` for `powerbi_refresh_dataset`). A service principal is not supported by this server: Execute Queries does not support one against a model with row-level security, and a person's own rights are what should apply.
- **DAX queries** (`powerbi_query`, `powerbi_summarize`, `powerbi_model_columns`) need Read **and Build** permission on the model and the tenant setting *Dataset Execute Queries REST API* (on by default). One query per call, at most 100,000 rows, 1,000,000 values or 15 MB, 120 queries per minute per person ([Microsoft](https://learn.microsoft.com/en-us/rest/api/power-bi/datasets/execute-queries)).
- **Licence:** Power BI Pro or Premium Per User, unless the content is on a Premium or Fabric capacity (F64 or larger).
- **Refreshes:** 8 on-demand refreshes per model per day on Pro, 48 on Premium or Fabric capacity.
## Quick start
Requires Node.js 22 or later and a Microsoft Entra access token for the Power BI REST API (for a quick test: `az account get-access-token --resource https://analysis.windows.net/powerbi/api`). It expires after about an hour.
```bash
npx mcp-server-powerbi
```
Or build from source:
```bash
git clone https://github.com/borgels/mcp-server-powerbi.git
cd mcp-server-powerbi
npm ci
npm run build
```
Claude Code:
```bash
claude mcp add powerbi \
--env POWERBI_ACCESS_TOKEN=<token> \
-- npx -y mcp-server-powerbi
```
Claude Desktop (`claude_desktop_config.json`), or any client that launches stdio servers:
```json
{
"mcpServers": {
"powerbi": {
"command": "npx",
"args": ["-y", "mcp-server-powerbi"],
"env": {
"POWERBI_ACCESS_TOKEN": "<token>"
}
}
}
}
```
### Docker and HTTP
Images are published to `ghcr.io/borgels/mcp-server-powerbi`: `latest` and the commit SHA from `main`, and `vX.Y.Z` for release tags. The container serves streamable HTTP at `/mcp` on port 3000, plus an unauthenticated `GET /healthz`.
```bash
TOKEN=$(openssl rand -hex 32); echo "$TOKEN"
docker run -d --name powerbi-mcp -p 127.0.0.1:3000:3000 \
-e POWERBI_ACCESS_TOKEN=<token> \
-e MCP_HTTP_TOKEN="$TOKEN" \
ghcr.io/borgels/mcp-server-powerbi:latest
claude mcp add --transport http powerbi http://127.0.0.1:3000/mcp \
--header "Authorization: Bearer $TOKEN"
```
To keep an audit log in the container, mount a writable directory and point `POWERBI_AUDIT_LOG` into it (e.g. `-v powerbi-audit:/audit -e POWERBI_AUDIT_LOG=/audit/audit.jsonl`); the image runs as the `node` user and `/app` is not writable.
Clients send `Authorization: Bearer <MCP_HTTP_TOKEN>`. The server will not start on a non-loopback address without a token of at least 32 characters. It does not terminate TLS; run it behind a reverse proxy or gateway that does.
## Configuration
Configuration is read from the environment (see `.env.example`). Invalid numbers, booleans, URLs and unknown tool names stop the server at startup. Booleans accept `true`/`false`, `1`/`0`, `yes`/`no` and `on`/`off`.
### Upstream API
| Variable | Default | Description |
|---|---|---|
| `POWERBI_ACCESS_TOKEN` | – | **Required.** A person's Microsoft Entra access token for the Power BI REST API (delegated). |
| `POWERBI_BASE_URL` | `https://api.powerbi.com/v1.0/myorg` | Base URL of the API. Must be on `api.powerbi.com` (loopback `http` is allowed for local mocks). |
| `POWERBI_ALLOW_CUSTOM_BASE_URL` | `false` | Allow a base URL outside `api.powerbi.com`. |
| `POWERBI_TIMEOUT_MS` | `30000` | Timeout per request attempt. |
| `POWERBI_MAX_CONCURRENCY` | `4` | Maximum concurrent upstream requests. |
| `POWERBI_MAX_RESPONSE_BYTES` | `10485760` | Largest response body read (at most 100 MB). |
### Access control
| Variable | Default | Description |
|---|---|---|
| `POWERBI_ENABLE_WRITES` | `false` | Enable the write tool (`powerbi_refresh_dataset`). |
| `POWERBI_DISABLED_TOOLS` | – | Comma-separated tool names to disable, with or without the `powerbi_` prefix. |
| `POWERBI_AUDIT_LOG` | – | Path of a JSONL audit log: one record per tool call start, finish and error, with ids in clear text, free text hashed, duration, status and the caller passed by an embedding host. Write tools refuse to run if the log cannot be written. |
### HTTP transport
| Variable | Default | Description |
|---|---|---|
| `MCP_HTTP_TOKEN` | – | Bearer token, at least 32 printable ASCII characters (also on loopback). Required unless bound to loopback. |
| `MCP_HTTP_HOST` or `HOST` | `127.0.0.1` (`0.0.0.0` in the image) | Bind address; `MCP_HTTP_HOST` takes precedence. |
| `PORT` | `3000` | Listen port. |
| `MCP_ALLOWED_ORIGINS` | localhost origins | Comma-separated browser origins allowed to call the server. |
| `MCP_ALLOW_ANY_ORIGIN` | `false` | Allow any origin; requires a token. |
| `MCP_ALLOWED_HOSTS` | loopback names on a loopback bind | Comma-separated accepted `Host` header names. |
| `MCP_MAX_BODY_BYTES` | `10485760` | Maximum request body. |
| `MCP_AUTH_FAILURE_LIMIT`, `MCP_AUTH_FAILURE_WINDOW_MS` | `20`, `60000` | Failed-authentication limit per client address; `0` disables it. |
| `MCP_HTTP_ALLOW_UNAUTHENTICATED` | `false` | Permit a non-loopback bind without a token. Only for isolated networks. |
## Embedding (`./gateway`)
A host application can run the tools in-process instead of over MCP:
```ts
import { createPowerbiGateway, powerbiToolCatalog } from 'mcp-server-powerbi/gateway';
// One instance per person and call, with that person's current access token (the host renews it).
const gateway = createPowerbiGateway({ accessToken: token, policy: { enableWrites: false, audit } });
const result = await gateway.callTool('summarize', {
datasetId: '66666666-7777-4888-9999-000000000000',
measures: ['Sales Amount'],
groupBy: [{ table: 'Date', column: 'Month' }],
filters: [{ column: { table: 'Date', column: 'Date' }, from: '2026-01-01', to: '2026-12-31' }],
}, { caller: 'person-1' });
```
- **Explicit credentials.** `accessToken` is required; a missing value throws when the gateway is created. `baseUrl` is optional and defaults to `https://api.powerbi.com/v1.0/myorg`. A gateway never reads `POWERBI_ACCESS_TOKEN` or `POWERBI_BASE_URL` from the environment, so one person cannot silently fall back to the process's credentials. The stdio and HTTP transports still read them from the environment. The server never sees a refresh token: the host signs the person in, keeps and renews the token, and creates an instance with the current one.
- **Several people in one process.** Create one gateway per access token. Each instance redacts error text, tool results and audit records with its own key only; no secret is kept in a process-wide registry, and a dropped instance releases its key.
- **Instance policy from the host.** Pass `policy` to `createPowerbiGateway`: `enableWrites` (default false), `disabledTools` (must name known tools) and `audit`, a function that receives each audit record instead of `POWERBI_AUDIT_LOG` (without it the instance writes no audit; a write tool does not run if the sink throws on its start record). An instance with `policy` reads none of `POWERBI_ENABLE_WRITES`, `POWERBI_DISABLED_TOOLS`, `POWERBI_AUDIT_LOG` or `POWERBI_ALLOW_CUSTOM_BASE_URL`, so tenants in one process can have different settings. Without `policy` the instance uses the environment, like the MCP server. Each call runs in a scope of its own, so a call made from inside another instance's call never inherits its policy, sink or redactor, and every audit record is redacted as a whole with the instance's own key before the sink sees it. The limits (`POWERBI_TIMEOUT_MS`, ...) are still read from the environment and apply to every gateway in the process. Per-user and per-tenant authorization is the host's job.
- **Result format.** A successful `callTool` result has `structuredContent` and one text block: a short summary, a blank line, and the same data as compact JSON, as the MCP specification recommends (many clients read only the text). The JSON is built from the redacted result, so it holds exactly `structuredContent`. An error result has only its text (a batch in which every row failed also keeps its outcome per row in `structuredContent`), and, when the upstream API answered with an HTTP error, `failure: { httpStatus, requestId? }`: the status, and the vendor's request id from a response header (`REQUEST_ID_HEADERS` in `src/errors.ts`) only when it is a hex id of 8 to 64 characters (one run of hex digits, or groups of four or more joined by single hyphens, as in a UUID) and does not hold the shape of a personal number. A host can count failures from it without reading their text. Never the response body, the vendor's error code or message.
- **Answers in a fixed form.** A tool that declares an output form (`outputSchema` in the catalog and on `gateway.tools`, JSON Schema with an object root) returns its data as `structuredContent` in exactly that form: amounts as decimal strings with exactly two decimals and an ISO 4217 currency code (or integers in minor units, named so, also for a currency with 0 or 3 decimals), dates as ISO 8601, a value the vendor did not give as `null`. A host can list the form to its clients and check each answer against it. Over MCP the server checks the answer itself before it sends `structuredContent`; one that does not fit is never refused, it goes on as text only behind a note that the call succeeded, marked as an error for the protocol only (a client with the form refuses a successful answer without `structuredContent`). A tool without a form passes the vendor's data on as before.
- **Act as a person.** A host that has verified the person a call is made for passes `actAs: { email, name? }` in the call context (`src/act-as.ts`). A handler reads it with `currentActAs()` and makes the call's changes as the person's own user in the system, found by that email (a header or a user field, as the vendor documents it). When the person has no single active user there, or the key may not act for others, the handler throws `ActAsRefusedError` and the result is an error with `actAsRefused` (`no_user`, `not_permitted`) and a fixed text: a change is never made as the key's own user instead. A malformed `actAs` refuses the call (`invalid`) before anything is sent. Whether a read also goes as the person is decided per server and written in its README. The server adds the email to no audit record, text or field of its own; data the system returns is passed on as it is. Only an absent `actAs` means no person (`null` is refused). Without `actAs` every call runs as the key's own user. This server does not use `actAs`: the access token is already the person's own, so every call is made as that person in Power BI.
- **Changes in batch.** This server has no batch tool (a refresh is one call per model); the shared batch code stays for the template's conformance. A batch tool changes many independent rows in one call (`src/batch.ts`): its input is `items`, 1 to 200 rows (`MAX_BATCH_ITEMS`; a tool may set a lower limit for its API, never a higher one). Every row is checked before anything is sent (its schema, then the tool's own check, such as two rows for the same record); one bad row and nothing is sent, and the error names the row (`items[3].price`). Where the API has a batch endpoint the rows go through it, split into the vendor's own chunk size; otherwise each row is its own request, at most 4 at a time (`BATCH_CONCURRENCY`). After a 401, 403 or 429 the rows not yet sent are not sent. The answer's `structuredContent` has `total`, `ok`, `failed`, `unknown` and `items`, one outcome per row by its `index`: `ok`, `failed` (certainly not carried out, with the reason: never sent, or its write request itself was refused with a 4xx other than 408) or `unknown` (a timeout, a 3xx, a 408 or a 5xx on the write, or any error from a request after the write: it may have been carried out, so check it before repeating it). A server marks the one request that writes a row with `rowWrite`; an error from any other request leaves the row `unknown`. The person to act as is resolved once, before the rows are sent. A result withheld by the key check says that the rows may have been carried out. The text says first what happened to the rows; it says that the call changed nothing only when every row failed, and only then is the result an error. The catalog marks a batch tool with `batch: { itemsField: 'items', maxItems, itemLogFields }`: `itemLogFields` names the fields of a row a host may log (ids, numbers, amounts; never free text), so a host can write one log line per row before it calls the tool and one outcome per row after it. For the host's permission check a batch is one call to one tool.
- **Tool catalog.** `powerbiToolCatalog` is a frozen list of every tool: `name` (without the `powerbi_` prefix), `title`, `description`, `riskLevel` (`read`, `write` or `destructive`), `enabledByDefault`, `inputSchema` (JSON Schema), `outputSchema` (JSON Schema, only on a tool with a fixed answer form), `batch` (only on a batch tool, see above), `broad` (true when a tool can read more than its name says, so a host gives it only to roles that may read everything) and `upstream`, the API requests the tool may make (`access`, `method` and path template). It is generated from the same tool table as the MCP server, so it cannot drift from the registered tools. `powerbiGatewayTools` holds the same definitions without `upstream` and `broad`; `gateway.tools` lists those enabled on the instance.
## Threat model
What this server guarantees about the access token ("the key" below), and what it does not. It is
the yardstick for every change that touches errors, results or audit.
**Scope.** Guarantees (a), (b) and (c) apply to the embeddable gateway
(`./gateway`), the surface a multi-tenant host uses. The standalone MCP
server, configured from the environment for one key, keeps best-effort
redaction: its errors and audit records are redacted with its key, but it is
not held to these guarantees.
**Guaranteed:**
- **(a) The key never reaches anything persisted or shared:** audit sinks and
the audit log file, logs, error texts, export hooks or files. Errors are
our own texts; audit records and everything a gateway instance returns are
redacted with the instance's own key before they leave it.
- **(b) No vendor-controlled free text in errors.** An error carries our own
fixed text, the HTTP status, numbers we parse (Retry-After), and codes from
a fixed list we wrote down; never a response body, a vendor message or
code, a redirect's `Location`, a type or field name from the vendor, or
the message of an error thrown while reading a response. A failure kept
inside an otherwise returned result is the status or a fixed text as well.
Errors never quote the key, the configured address or a refused configuration value (a timeout names its limit in milliseconds).
- **(c) Results go only to the tenant whose key it is.** One gateway
instance per tenant; every call runs in a scope of its own; nothing about a
tenant is kept in process-wide state. The MCP server serves one key.
**Not guaranteed (residual risk):** a vendor that deliberately echoes the
customer's own key back in data. Results are redacted on a best-effort
basis: the exact key, its URL- and JSON-encoded forms and any piece of it of
6 characters or more, in strings, object keys and the string form of
numbers and booleans, are replaced by `"‹redacted›"` before anything is
serialised. A key that comes back otherwise transformed (split into pieces
shorter than 6 characters, reversed, re-encoded, hashed) is not recognised.
Such data reaches only the tenant whose key it is, which already holds the
key. **What leaves a gateway holds no piece of the key.** This is checked at
the sink, not inferred from our texts: every output is checked in its final
form, and one that holds a piece of 6 characters of the key (or of one of
its encoded forms) is replaced by a fixed fallback. The outputs are the tool
list, every tool result as a whole (outer fields such as `isError`
included), audit records and stderr lines, and construction errors. A result becomes a fixed
"withheld" error, an audit record or line becomes a fixed one, and a
construction error becomes the fixed refusal. Every error a gateway throws is a fresh error in final form: no `cause`, a `stack` of only `name: message` (no frames, paths or function names), and name, message and stack masked against the secret. The fallbacks are a small,
closed set (`src/fallbacks.ts`), and a key that shares a piece with any of
them, or with the tool list, is refused when the gateway is created.
**Key admission.** Every key is a secret the vendor issues. A gateway
accepts only printable ASCII (0x21-0x7E) of at least 16 characters, checked
before anything is built from the key. As a cheap first filter it also
refuses a key that shares a piece of 6 characters with a string literal in
`src/` (`src/fixed-corpus.generated.ts`, kept up to date by a test). The
refusal is a fixed text that never repeats the key. The standalone MCP server applies the same redaction to errors
and audit records on a best-effort basis; its successful results are passed
on as the API returned them.
## Security model
- **One person per instance.** Every call acts with the rights of the configured access token: one person's own rights in Power BI, with row-level security applied to them. Give the app that gets the token only the delegated permissions above.
- **Per-user authorization belongs in front of the server.** The server checks a single bearer token and does not know the end user. For multi-user use, run it behind an identity-aware gateway that decides which users may call which tools, holds the bearer token, and is the only network path to the server. Hosts can also embed the tools through the `./gateway` module export and pass the caller identity into the audit log.
- **Tool access is not data access.** A gateway controls who may call which tool; what the person can see is decided by Power BI. `powerbi_query` is marked `broad`: it can read anything in a model the person may query.
- **Writes are off by default.** The one write tool starts a refresh; it deletes nothing and is annotated as not destructive and not idempotent. Read-only tools get a client that refuses every POST except a DAX query to an `executeQueries` path. When `POWERBI_AUDIT_LOG` is set, a write tool does not run unless its start record is written; without it there is no audit record.
- **No answers are kept.** What the API answers is passed on to the caller and never stored or cached, not even briefly in memory: every call asks the API again. Rate limits are handled by retrying within a budget, not by reusing an earlier answer. The conformance test (`test/conformance.test.ts`) flags a cache in `src/`.
- **DAX errors are not quoted.** When Power BI refuses a query, the answer says so in our own words (and by status), never with Power BI's message, which can quote data. `powerbi_summarize` builds its query from names: every table, column and measure name and every value is quoted, so input cannot add DAX of its own.
- **Upstream content is untrusted input.** Data returned by the API may be written by anyone with access to it. Tool results label it as data; clients that combine this server with other tools should treat it accordingly.
- **The access token stays on the API origin.** Redirects are never followed, the base URL must be `https` on `api.powerbi.com`, and error messages and audit records are redacted (by each instance, with that instance's key) and size-capped. See the threat model above for what is and is not guaranteed.
- **The HTTP transport fails closed.** It refuses to start on a non-loopback address or with any origin allowed unless a token is set, compares tokens in constant time, throttles failed authentication per client address, checks `Origin` and `Host` (DNS rebinding), and caps request bodies.
Report vulnerabilities as described in [SECURITY.md](SECURITY.md).
## Development
```bash
npm run dev # stdio transport
npm run dev:http # HTTP transport on 127.0.0.1:3000
npm run typecheck
npm test
npm run build
```
`test/conformance.test.ts` checks the baseline shared by all servers built from this template: license, Node versions, strict type checking, CI steps and pinned actions, Dependabot, README sections, changelog, no answer cache, and a title, risk level and input schema for every tool in the catalog. It is the same file in every server; change it in the template, never in a server.
Project layout:
| Path | Contents |
|---|---|
| `src/tools/powerbi.ts` | Shared tool table (MCP and gateway), policy and audit wrapper. |
| `src/powerbi/` | Upstream client, API calls, policy, audit, tool annotations. |
| `src/transports/` | stdio and HTTP entry points; HTTP auth, origin and host checks. |
| `src/gateway.ts` | Embeddable entry point (`./gateway` export). |
| `src/config-env.ts` | Validated environment readers. |
## Releasing
1. Bump the version in `package.json`, `server.json` (`version` and the npm package `version`) and `src/version.ts`; tests and CI check that they agree. Update `CHANGELOG.md`. Merge.
2. Tag the merged commit and push the tag: `git tag vX.Y.Z && git push origin vX.Y.Z`. Every version gets its tag, also one that is only used embedded, so each published or vendored package can be traced to its commit.
3. `release.yml` tests, packs and publishes the tarball to npm through trusted publishing (no stored token; npm adds provenance when the repository is public), then publishes `server.json` to the MCP Registry. Versions already on npm or in the registry are skipped, so a failed run can be re-run. Pre-release tags (`vX.Y.Z-rc.1`) go to the npm dist-tag `next` and not to the registry. `publish.yml` pushes the `vX.Y.Z` image.
The first version of a new package is published by hand; see the header of `.github/workflows/release.yml` (and [docs/NEW-SERVER.md](docs/NEW-SERVER.md)).
## License
The code is source-available under the [Functional Source License, Version 1.1, ALv2 Future License](LICENSE) (FSL-1.1-ALv2).
In plain words:
- **Allowed:** reading the code, running it, changing it, using it inside your own organisation (also commercially), using it for non-commercial education and research, and contributing changes back.
- **Not allowed:** making it, or something built from it, available to others as a commercial product or service that competes with it, for example a hosted service with the same functionality.
- **Becomes Apache-2.0:** each version is also licensed under the Apache License 2.0 from two years after it is released.
The terms in [LICENSE](LICENSE) are what apply; this summary does not replace them.
TDQS
Scored across 12 tools
Each tool targets a distinct Power BI resource or operation: workspaces, reports, report pages, datasets, metadata, search, querying/summarizing, and refresh actions. The few potentially overlapping areas, such as find vs. list and summarize vs. query, are explicitly distinguished by their descriptions.
All tool names use the same powerbi_ prefix and snake_case style, making them predictable and readable. However, a few names are noun phrases or lack a clear verb, such as powerbi_report_pages, powerbi_model_columns, and powerbi_find, so the verb_noun pattern is not perfectly uniform.
The 12-tool set is well scoped for a Power BI server, covering discovery, metadata inspection, querying, and refresh lifecycle operations. Each tool corresponds to a meaningful capability, and the count is neither too thin nor bloated.
The surface covers the core workflows well: finding workspaces/reports/datasets, inspecting schemas, querying data, and managing refresh operations. Minor gaps remain, notably that measures are not directly listable and there is no direct report visual/export capability.