# Pbi Context

> AI context engine for Power BI models — turns .pbit/.pbip (TMDL) into indexed, queryable context for LLM agents (MCP server, CLI, docs). Zero dependencies.

- **Type:** MCP server
- **Install:** `agentstack add mcp-osc2405-pbi-context`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [Osc2405](https://agentstack.voostack.com/s/osc2405)
- **Installs:** 0
- **Category:** [AI & ML](https://agentstack.voostack.com/c/ai-and-ml)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [Osc2405](https://github.com/Osc2405)
- **Source:** https://github.com/Osc2405/pbi-context
- **Website:** https://pypi.org/project/pbi-docs/

## Install

```sh
agentstack add mcp-osc2405-pbi-context
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# pbi-context — AI Context Engine for Power BI Models

[](https://pypi.org/project/pbi-context/)
[](https://github.com/Osc2405/pbi-context/actions/workflows/tests.yml)
[](https://www.python.org/)
[](https://github.com/Osc2405/pbi-context/blob/main/LICENSE)
[](https://github.com/Osc2405/pbi-context/actions/workflows/tests.yml)

**pbi-context is the zero-dependency context compiler that lets any AI agent read, query, and audit
a Power BI model** — via CLI, indexed JSON, or a read-only MCP server.

**Who it's for:** data engineers documenting dashboards, consultants auditing models they didn't
build, and anyone connecting an AI agent (Claude, GPT, Copilot) to a Power BI model's structure.

## Quick Start

```bash
pip install pbi-context

# From a .pbit file...
pbi-context --input "data/pbit/my-model.pbit"
# ...or a PBIP project (folder, .pbip marker, or .SemanticModel/ — auto-detected)
pbi-context --input "data/pbip/my-model/"

cat "output/my-model.pbit/model_documentation.md"
```

**Result:** 7 files in `output//` in seconds — human-readable Markdown, JSON/JSONL
context for AI agents, and an indexed, queryable version for large models.

Full walkthrough — folder structure, expected output, and using the context in Python

The command generates a folder in `output/` with all documentation files:

```
output/my-model.pbit/          (or output/my-model/ for PBIP)
├── metadata.json              # Structured model metadata
├── model_documentation.md     # Human-readable documentation
├── agent_context.json         # LLM-optimized context (top-20 measures)
├── model_context.jsonl        # JSONL format for embeddings/RAG
├── index.json                 # Lightweight index + pointers
├── relationships.json         # All relationships
└── tables/
    ├── Sales.json             # Full detail per table
    └── ...
```

```bash
cat "output/my-model.pbit/model_documentation.md" | head -n 15
```
```markdown
# my-model - Power BI Data Model

**Generated:** 2025-12-22 14:23:29

## Model Summary

- **Business Tables:** 9
- **Total Columns:** 23
- **Total Measures:** 44
- **Relationships:** 9
```

Use the JSON context directly in Python (or point an AI agent at it via `--query` or
`--mcp-serve` — see [Use Cases](#use-cases) below):

```python
import json

with open("output/my-model.pbit/agent_context.json", "r", encoding="utf-8") as f:
    context = json.load(f)

print(f"Model: {context['model_name']}")
print(f"Key measures: {len(context['key_measures'])}")
print(f"First measure: {context['key_measures'][0]['name']}")
```
```
Model: my-model
Key measures: 20
First measure: Revenue Budget
```

## Why pbi-context?

| Your Need | pbi-context Solution |
|-----------|---------------------|
| **Document 10+ dashboards fast** | Batch processing with `--batch` |
| **Support the new PBIP format** | Full TMDL parser, auto-detected from `.pbip` or folder |
| **Train AI agents on your models** | Indexed JSON/JSONL context, a query CLI, and an MCP server |
| **Let an AI agent query the model live** | Read-only MCP server (`--mcp-serve`) — validated against a test harness, not yet a live MCP client, see [MCP server](https://github.com/Osc2405/pbi-context/blob/main/docs/use-cases.md#7-mcp-server---mcp-serve) |
| **Use it from your AI coding assistant** | Chat-invocable Skill for Claude Code + prompt file for GitHub Copilot |
| **Actually readable DAX** | Hierarchical indentation (4x better than raw) |
| **Compare model versions** | Content-aware `--diff`, with impact analysis (`--diff-impact`) |
| **See the model at a glance** | Embedded Mermaid ER diagram in `model_documentation.md` — renders natively on GitHub/VS Code |
| **Visualize the model in Gephi/yEd** | `--export-graph` — JSON node/edge lists or GraphML |
| **Zero-cost, zero-install** | Python-only, no .NET dependencies |

**Perfect for:** Data engineers onboarding teams, consultants auditing models, organizations building AI copilots for BI.

## Project Status

**v1.1.0 is published on [PyPI](https://pypi.org/project/pbi-context/)** under the name
`pbi-context` — this project was previously published as `pbi-docs` (v1.0.0–1.0.1); the tool
didn't change, only the name, to avoid a discoverability collision with an unrelated,
similarly-named project. See [CHANGELOG.md](https://github.com/Osc2405/pbi-context/blob/main/CHANGELOG.md)
for the full rename note.

The read/context layer — PBIP/TMDL support, indexed output, query resolver, MCP server,
`--diff-impact`, `--export-graph` — is done, implemented and tested (see the Tests badge above for
the current count). Every claim above is backed by a dated, reproducible report, not just
asserted: see [Validation](#validation) below.

**Next up:** validating with real human users that scoped context doesn't cost time or accuracy
versus raw file dumps — the protocol is ready
([docs/human_validation_protocol.md](https://github.com/Osc2405/pbi-context/blob/main/docs/human_validation_protocol.md)),
currently blocked on recruiting participants, not on code.

Writing/editing TMDL models and PBIR/report-layer parsing remain deliberately out of scope (see
[Roadmap](#roadmap) for why).

*Last updated: 2026-08-03.*

## Requirements
- Python 3.10+ (3.12 recommended)
- Works on Windows, macOS, and Linux

Optional: virtual environment (`venv`). No external libraries required.

## Installation

Just want to run `pbi-context`? `pip install pbi-context` (see Quick Start above) is all you need. The
steps below are for working on `pbi-context` itself (editable install from a local clone).

```bash
# 1) Clone or download the repository
# 2) (Optional) Create and activate a virtual environment
python -m venv venv
source venv/bin/activate

# 3) Editable installation (development)
pip install -e .

# Verify Python version
python --version
```

Windows/PowerShell notes

```powershell
python -m venv venv
./venv/Scripts/Activate.ps1
```

If PowerShell blocks activation, run as Administrator:

```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```

---

## Quick Usage

### Basic Commands

**Process a `.pbit` file:**
```bash
pbi-context --input "data/pbit/my-model.pbit"
```

**Process a PBIP project (new in v1.0):**
```bash
# From the .pbip marker file
pbi-context --input "data/pbip/my-model.pbip"

# From the .SemanticModel folder directly
pbi-context --input "data/pbip/my-model.SemanticModel"

# From the project root folder (auto-detected)
pbi-context --input "data/pbip/my-model/"
```

**Specify custom output directory:**
```bash
pbi-context -i "data/pbit/my-model.pbit" -o "my-results"
```

**Process multiple files (batch mode — mixed formats supported):**
```bash
pbi-context --batch "data/pbit/*.pbit"
```

**Compare two versions of a model (mixed `.pbit`/`.pbip` supported):**
```bash
pbi-context --diff "data/pbit/model_v1.pbit" "data/pbip/model_v2/"
```

**Verbose mode (more debugging information):**
```bash
pbi-context --input "data/pbit/my-model.pbit" --verbose
```

**Human-readable indexed output (indented JSON, for debugging — compact by default):**
```bash
pbi-context --input "data/pbit/my-model.pbit" --pretty
```

**Generate documentation in Spanish:**
```bash
pbi-context --input "data/pbit/my-model.pbit" --lang es
```

**Generate documentation in English (default):**
```bash
pbi-context --input "data/pbit/my-model.pbit" --lang en
# Or simply omit --lang (English is the default)
pbi-context --input "data/pbit/my-model.pbit"
```

See [docs/troubleshooting.md](https://github.com/Osc2405/pbi-context/blob/main/docs/troubleshooting.md)
for the full expected-output walkthrough, how to verify a fresh install, and common errors.

### Important Notes

- **Supported formats:** `.pbit` files (ZIP + JSON TMSL) and `.pbip` projects (TMDL folder structure). `.pbix` files must be exported to `.pbit` from Power BI Desktop (File > Export > Power BI Template).
- **PBIP entry points:** The `--input` flag accepts a `.pbip` marker file, a `.SemanticModel/` folder, or a project root folder. Format is auto-detected.
- **Microsoft Fabric semantic models:** Fabric uses the same TMDL format as PBIP, so compatibility is *expected* but **not empirically validated** (no real Fabric export has been tested against this parser yet) — see [docs/fabric_compatibility.md](https://github.com/Osc2405/pbi-context/blob/main/docs/fabric_compatibility.md).
- **Language selection:** Use `--lang en` for English (default) or `--lang es` for Spanish. The language affects the generated `model_documentation.md` and `agent_context.json` files.
- **Paths with spaces:** Use quotes around paths that contain spaces.
- **Recommended paths:** Place your files in `data/` or `data/pbit/` to keep the project organized.

---

## Project Structure

```
pbi-context/
├── pbi_extractor/           # Main package
│   ├── __init__.py
│   ├── cli.py              # CLI with argparse (auto-detection, --index-format)
│   ├── extractor.py        # .pbit (ZIP+JSON TMSL) extractor
│   ├── pbip_extractor.py   # .pbip / TMDL extractor (new in v1.0)
│   ├── processor.py        # Metadata processing (format-agnostic)
│   ├── indexed_output.py   # index.json + tables/*.json writer (new in v1.0)
│   ├── formatters.py       # Advanced hierarchical DAX formatting
│   ├── categorizer.py      # Table/measure categorization
│   ├── documentation.py    # Markdown generation
│   ├── diff.py             # Model comparison
│   ├── jsonl_generator.py  # JSONL generator for LLMs
│   └── i18n.py             # Translations (en/es)
├── tests/
│   ├── fixtures/
│   │   └── minimal_pbip/   # TMDL test fixtures (new in v1.0)
│   ├── test_pbip_extractor.py
│   ├── test_cli_detection.py
│   ├── test_indexed_output.py
│   ├── test_categorizer.py
│   ├── test_i18n.py
│   └── test_processor_and_context.py
├── githooks/                # Reference pre-commit hook (docs/pre_commit_hook.md)
├── data/                   # Input model files
├── output/                 # Generated results
├── pyproject.toml          # Package configuration
├── README.md
├── CHANGELOG.md
└── LICENSE
```

---

## Generated Outputs

After running the command, a folder is created in `output/` with the model name. Inside you'll find:

- **`metadata.json`**
  - `summary`: totals of tables, visible columns, visible measures and relationships.
  - `tables`: each table with `columns` (type, visibility, category) and `measures` (clean expression, format, display folder, category).
  - `relationships`: from/to, cardinality, direction and active status.

- **`model_documentation.md`**
  - Model summary (language depends on `--lang` flag, default: English).
  - List of tables (hidden or business), visible columns and measures grouped by category: revenue, cost, margin, percentage, ratio, temporal, etc.
  - Sections with DAX expressions formatted with **hierarchical indentation**.
  - Relationships table with visual representation of table connections.
  - AI Agent Usage Guide with sample questions (translated based on selected language).

- **`agent_context.json`**
  - Model name, totals, available tables, key measures (up to 20), temporal columns and sample questions (language depends on `--lang` flag, default: English).

- **`model_context.jsonl`**
  - Line-delimited JSON format optimized for embeddings and RAG.
  - Each line is an independent object (table, measure or relationship).
  - Includes formatted DAX and sample prompts.

- **`index.json`** *(new in v1.0)*
  - Lightweight model summary with per-table metadata (column/measure counts, categories) and relative paths to all other output files.
  - Allows LLM agents to navigate large models without loading the full `metadata.json`.

- **`relationships.json`** *(new in v1.0)*
  - All model relationships in a single focused file.

- **`tables/.json`** *(new in v1.0)*
  - Full detail for one table (columns + measures including DAX).
  - One file per table, addressable via `index.json`.

---

## `index.json` — open format specification

`index.json` is a small, stable contract meant to be consumed directly by any tool — not just
pbi-context' own CLI/resolver/MCP server: a lightweight per-table summary (name, column/measure
counts, categories, format, and a relative path to that table's detail file) plus pointers to
every other output file, so an agent can navigate a large model without loading `metadata.json`.
By default it's written **compact** (no indentation); pass `--pretty` for indented JSON.

Full field-by-field contract — top-level shape, per-table entry, the `tables/.json` JSON vs.
TOON shapes, and the versioning policy — is documented in
**[docs/index-json-spec.md](https://github.com/Osc2405/pbi-context/blob/main/docs/index-json-spec.md)**.

---

## Use Cases

### 1. Automatic Dashboard Documentation

**Problem:** Your company has multiple undocumented Power BI dashboards. Analysts waste time searching for which measures to use and how tables are related.

**Solution:**
```bash
# Process all dashboards in a folder (English documentation)
pbi-context --batch "data/dashboards/*.pbit"

# Or generate Spanish documentation for all dashboards
pbi-context --batch "data/dashboards/*.pbit" --lang es
```

**Result:**
- Each dashboard generates its own documentation in `output/[dashboard-name].pbit/`
- Documentation ready to share with the team
- Automatic identification of measures by category (revenue, cost, margin, etc.)

**Output example:**
```
output/
├── Sales Dashboard.pbit/
│   ├── model_documentation.md  # 23 documented measures
│   └── metadata.json
├── Finance Dashboard.pbit/
│   ├── model_documentation.md  # 31 documented measures
│   └── metadata.json
└── Operations Dashboard.pbit/
    ├── model_documentation.md  # 18 documented measures
    └── metadata.json
```

---

### 2. New Analyst Onboarding

**Problem:** New employees need weeks to understand Power BI model structure and which measures to use for each analysis.

**Solution:**
1. Generate the model documentation (in your preferred language):
```bash
# English documentation (default)
pbi-context --input "data/pbit/my-model.pbit"

# Spanish documentation
pbi-context --input "data/pbit/my-model.pbit" --lang es
```

2. Upload the `model_documentation.md` file to your favorite AI agent (Claude, GPT-4, etc.)

3. The agent can answer questions like:
   - "What revenue measures are available?"
   - "How is Gross Margin calculated?"
   - "What tables are related to Customer?"

**Interaction example:**
```
User: What revenue measures does this model have?

Agent: The "my-model" model has 11 revenue measures:
- Total Revenue (simple): SUM([Revenue])
- YTD Revenue (simple): TOTALYTD(SUM([Revenue]),'Date'[Date])
- Revenue SPLY (medium): CALCULATE([Total Revenue],SAMEPERIODLASTYEAR('Date'[Date]))
- Revenue Budget (medium): CALCULATE([Total Revenue], FILTER(Scenario, Scenario[Scenario]="Budget"))
...
```

**Benefit:** Significant reduction in onboarding time by having immediate answers about the model structure.

---

### 3. Model Auditing

**Problem:** You need to compare two versions of the same dashboard to identify which measures or relationships changed between releases.

**Solution:**
```bash
# Compare two versions of the model
pbi-context --diff "data/pbit/dashboard_v1.pbit" "data/pbit/dashboard_v2.pbit"
```

**Result:** A `diff_dashboard_v1_vs_dashboard_v2.json` file is generated, content-aware — not just
which measures/columns/relationships were added or removed, but which existing ones changed
content (DAX expression, format string, display folder, hidden flag, category, data type,
cardinality, cross-filtering, active flag).

Identity for matching an object across both models:
- Measures and columns: `(table, name)`.
- Relationships: `(from_table, from_column, to_table, to_column)` — a relationship that keeps the
  same connected columns but changes cardinality/cross-filtering/active flag shows up in
  `relationships_modified`, not as a remove+add.

DAX changes are flagged `"semantic"` or `"cosmetic"` via a whitespace-insensitive compari

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [Osc2405](https://github.com/Osc2405)
- **Source:** [Osc2405/pbi-context](https://github.com/Osc2405/pbi-context)
- **License:** MIT
- **Homepage:** https://pypi.org/project/pbi-docs/

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-osc2405-pbi-context
- Seller: https://agentstack.voostack.com/s/osc2405
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
