pbi-mcp-server 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pbi_mcp_server/__init__.py +16 -0
- pbi_mcp_server/analyst.py +448 -0
- pbi_mcp_server/config.py +23 -0
- pbi_mcp_server/engine_a/__init__.py +1 -0
- pbi_mcp_server/engine_a/parser.py +385 -0
- pbi_mcp_server/engine_a/writer.py +414 -0
- pbi_mcp_server/engine_b/__init__.py +1 -0
- pbi_mcp_server/engine_b/parser.py +876 -0
- pbi_mcp_server/errors.py +101 -0
- pbi_mcp_server/integrity/__init__.py +1 -0
- pbi_mcp_server/integrity/references.py +26 -0
- pbi_mcp_server/integrity/validator.py +121 -0
- pbi_mcp_server/jinja_templates.py +460 -0
- pbi_mcp_server/lineage.py +710 -0
- pbi_mcp_server/logging_utils.py +80 -0
- pbi_mcp_server/m_codec.py +1142 -0
- pbi_mcp_server/main.py +171 -0
- pbi_mcp_server/meta_tools.py +269 -0
- pbi_mcp_server/models.py +199 -0
- pbi_mcp_server/mutation.py +199 -0
- pbi_mcp_server/pbip_references.py +173 -0
- pbi_mcp_server/server.py +804 -0
- pbi_mcp_server/service.py +1188 -0
- pbi_mcp_server/sql_edit.py +1764 -0
- pbi_mcp_server/sql_sections.py +739 -0
- pbi_mcp_server/tmdl_sql.py +1413 -0
- pbi_mcp_server/workflows.py +345 -0
- pbi_mcp_server/workspace.py +73 -0
- pbi_mcp_server/workspace_registry.py +498 -0
- pbi_mcp_server-0.3.0.dist-info/METADATA +202 -0
- pbi_mcp_server-0.3.0.dist-info/RECORD +34 -0
- pbi_mcp_server-0.3.0.dist-info/WHEEL +4 -0
- pbi_mcp_server-0.3.0.dist-info/entry_points.txt +2 -0
- pbi_mcp_server-0.3.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""PBI MCP Server package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .server import create_server
|
|
6
|
+
from .service import PbipService
|
|
7
|
+
from .workspace_registry import WorkspaceRegistry
|
|
8
|
+
|
|
9
|
+
__version__ = "0.3.0"
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"PbipService",
|
|
13
|
+
"WorkspaceRegistry",
|
|
14
|
+
"__version__",
|
|
15
|
+
"create_server",
|
|
16
|
+
]
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .engine_a.parser import scan_model
|
|
7
|
+
from .engine_b.parser import list_pages, list_visuals
|
|
8
|
+
from .lineage import find_unused_model_objects
|
|
9
|
+
from .models import BpaIssue, TmdlObject, WorkspaceInfo
|
|
10
|
+
from .workspace import compute_workspace_id
|
|
11
|
+
|
|
12
|
+
_DAX_FUNCTIONS = {
|
|
13
|
+
"abs", "acos", "acosh", "addcolumns", "addmissingitems", "all", "allcrossfiltered",
|
|
14
|
+
"allexcept", "allnoblankrow", "allselected", "and", "approximatedistinctcount",
|
|
15
|
+
"asin", "asinh", "atan", "atanh", "average", "averagea", "averagex", "betadist",
|
|
16
|
+
"betainv", "blank", "calculate", "calculatetable", "calendar", "calendarauto",
|
|
17
|
+
"ceiling", "chisqdist", "chisqinv", "CLOSINGBALANCEMONTH", "closingbalancequarter",
|
|
18
|
+
"closingbalanceyear", "coalesce", "columnstatistics", "combin", "combina",
|
|
19
|
+
"concatenate", "concatenatex", "confidence.norm", "confidence.t", "contains",
|
|
20
|
+
"containsrow", "containsstring", "containsstringexact", "convert", "cos", "cosh",
|
|
21
|
+
"count", "counta", "countax", "countblank", "countrows", "countx", "crossfilter",
|
|
22
|
+
"crossjoin", "currency", "currentgroup", "customdata", "datatable", "date",
|
|
23
|
+
"dateadd", "datediff", "datesbetween", "datesinperiod", "datesmtd", "datesqtd",
|
|
24
|
+
"datesytd", "datevalue", "day", "degrees", "detailrows", "distinct",
|
|
25
|
+
"distinctcount", "distinctcountnoblank", "divide", "earlier", "earliest",
|
|
26
|
+
"edate", "endofmonth", "endofquarter", "endofyear", "eomonth", "error", "even",
|
|
27
|
+
"exact", "except", "exp", "expondist", "fact", "false", "filter", "filters",
|
|
28
|
+
"find", "firstdate", "firstnonblank", "firstnonblankvalue", "fixed", "floor",
|
|
29
|
+
"format", "gcd", "generate", "generateall", "generateseries", "grouping",
|
|
30
|
+
"hasonefilter", "hasonevalue", "hour", "if", "if.eager", "iferror", "ignore",
|
|
31
|
+
"in", "index", "int", "intersect", "isafter", "isblank", "iscrossfiltered",
|
|
32
|
+
"isempty", "iserror", "iseven", "isfiltered", "isinsubtotal", "islogical",
|
|
33
|
+
"isnontext", "isnumber", "iso.ceiling", "isodd", "isonorafter", "isselectedmeasure",
|
|
34
|
+
"issubtotal", "istext", "keepfilters", "keywordmatch", "lastdate", "lastnonblank",
|
|
35
|
+
"lastnonblankvalue", "lcm", "left", "len", "ln", "log", "log10", "lookupvalue",
|
|
36
|
+
"lower", "max", "maxa", "maxx", "median", "medianx", "mid", "min", "mina",
|
|
37
|
+
"minute", "minx", "mod", "month", "mround", "naturalinnerjoin",
|
|
38
|
+
"naturalleftouterjoin", "networkdays", "nextday", "nextmonth", "nextquarter",
|
|
39
|
+
"nextyear", "nonvisual", "norm.dist", "norm.inv", "norm.s.dist", "norm.s.inv",
|
|
40
|
+
"not", "now", "odd", "offset", "openingbalancemonth", "openingbalancequarter",
|
|
41
|
+
"openingbalanceyear", "or", "orderby", "parallelperiod", "partitionby", "path",
|
|
42
|
+
"pathcontains", "pathitem", "pathitemreverse", "pathlength", "percentile.exc",
|
|
43
|
+
"percentile.inc", "percentilex.exc", "percentilex.inc", "permut", "pi",
|
|
44
|
+
"poisson.dist", "power", "previousday", "previousmonth", "previousquarter",
|
|
45
|
+
"previousyear", "product", "productx", "quarter", "quotient", "radians", "rand",
|
|
46
|
+
"randbetween", "rank", "rank.eq", "rankx", "related", "relatedtable",
|
|
47
|
+
"removefilters", "replace", "rept", "return", "right", "rollup",
|
|
48
|
+
"rollupaddissubtotal", "rollupgroup", "rollupissubtotal", "round", "rounddown",
|
|
49
|
+
"roundup", "row", "rownumber", "sameperiodlastyear", "sample", "search",
|
|
50
|
+
"second", "selectcolumns", "selectedmeasure", "selectedmeasureformatstring",
|
|
51
|
+
"selectedmeasurename", "selectedvalue", "sign", "sin", "sinh", "sqrt", "sqrtpi",
|
|
52
|
+
"startofmonth", "startofquarter", "startofyear", "stdev.p", "stdev.s",
|
|
53
|
+
"stdevx.p", "stdevx.s", "substitute", "substitutewithindex", "sum", "summarize",
|
|
54
|
+
"summarizecolumns", "sumx", "switch", "t.dist", "t.dist.2t", "t.dist.rt",
|
|
55
|
+
"t.inv", "t.inv.2t", "tan", "tanh", "time", "timevalue", "today", "topn",
|
|
56
|
+
"topnperlevel", "topnskip", "totalmtd", "totalqtd", "totalytd", "treatas",
|
|
57
|
+
"trim", "true", "trunc", "unichar", "unicode", "union", "upper",
|
|
58
|
+
"userculture", "userelationship", "username", "userobjectid",
|
|
59
|
+
"userprincipalname", "utcNow", "utctoday", "value", "values", "var", "var.p",
|
|
60
|
+
"var.s", "varx.p", "varx.s", "weekday", "weeknum", "window", "xirr", "xnpv",
|
|
61
|
+
"year", "yearfrac",
|
|
62
|
+
}
|
|
63
|
+
_DAX_KEYWORDS_LOWER = {k.lower() for k in _DAX_FUNCTIONS}
|
|
64
|
+
|
|
65
|
+
_TOKEN_PROTECT_RE = re.compile(r"('(?:''|[^'])*'|\"(?:\"\"|[^\"])*\"|\[[^\]]*\])")
|
|
66
|
+
_WORD_RE = re.compile(r"\b([A-Za-z_][A-Za-z0-9_.]*)\b")
|
|
67
|
+
_BRACKET_REF_RE = re.compile(r"(?:'(?P<qtable>[^']+)'|(?P<table_bare>[A-Za-z_][A-Za-z0-9_]*))?\s*\[(?P<ref>[^\]]+)\]")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def format_dax_string(dax: str, *, multiline: bool = False) -> str:
|
|
71
|
+
"""Format a DAX formula to clean SQLBI-style casing and operator spacing."""
|
|
72
|
+
raw = dax.strip()
|
|
73
|
+
if not raw:
|
|
74
|
+
return raw
|
|
75
|
+
|
|
76
|
+
placeholders: list[str] = []
|
|
77
|
+
|
|
78
|
+
def _protect(match: re.Match[str]) -> str:
|
|
79
|
+
idx = len(placeholders)
|
|
80
|
+
placeholders.append(match.group(0))
|
|
81
|
+
return f"__DAX_PROTECT_{idx}__"
|
|
82
|
+
|
|
83
|
+
protected = _TOKEN_PROTECT_RE.sub(_protect, raw)
|
|
84
|
+
|
|
85
|
+
# Collapse redundant whitespace into single spaces
|
|
86
|
+
protected = re.sub(r"\s+", " ", protected).strip()
|
|
87
|
+
|
|
88
|
+
# Uppercase DAX functions and keywords
|
|
89
|
+
def _upper_kw(match: re.Match[str]) -> str:
|
|
90
|
+
word = match.group(1)
|
|
91
|
+
if word.lower() in _DAX_KEYWORDS_LOWER:
|
|
92
|
+
return word.upper()
|
|
93
|
+
return word
|
|
94
|
+
|
|
95
|
+
protected = _WORD_RE.sub(_upper_kw, protected)
|
|
96
|
+
|
|
97
|
+
# Normalize spacing around commas and binary operators
|
|
98
|
+
protected = re.sub(r"\s*,\s*", ", ", protected)
|
|
99
|
+
protected = re.sub(r"\s*(<>|<=|>=|&&|\|\||[=+\-*/<>])\s*", r" \1 ", protected)
|
|
100
|
+
protected = re.sub(r"\(\s+", "(", protected)
|
|
101
|
+
protected = re.sub(r"\s+\)", ")", protected)
|
|
102
|
+
protected = re.sub(r"\s+", " ", protected).strip()
|
|
103
|
+
|
|
104
|
+
if multiline and ("VAR " in protected or "RETURN " in protected):
|
|
105
|
+
protected = re.sub(r"\bVAR\s+", "\nVAR ", protected)
|
|
106
|
+
protected = re.sub(r"\bRETURN\s+", "\nRETURN\n ", protected)
|
|
107
|
+
protected = protected.strip()
|
|
108
|
+
|
|
109
|
+
# Restore protected tokens (removing accidental space between Table and [Col])
|
|
110
|
+
for idx, token in enumerate(placeholders):
|
|
111
|
+
protected = protected.replace(f"__DAX_PROTECT_{idx}__", token)
|
|
112
|
+
|
|
113
|
+
protected = re.sub(r"([A-Za-z0-9_'])\s+(\[[^\]]+\])", r"\1\2", protected)
|
|
114
|
+
return protected
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def generate_measure_docstring(
|
|
118
|
+
measure_name: str,
|
|
119
|
+
table_name: str | None,
|
|
120
|
+
dax: str,
|
|
121
|
+
*,
|
|
122
|
+
dependent_visual_count: int = 0,
|
|
123
|
+
dependent_measure_count: int = 0,
|
|
124
|
+
) -> str:
|
|
125
|
+
"""Synthesize a concise TMDL description comment from a measure's DAX formula and lineage."""
|
|
126
|
+
expr = dax.strip()
|
|
127
|
+
refs: list[str] = []
|
|
128
|
+
for m in _BRACKET_REF_RE.finditer(expr):
|
|
129
|
+
tbl = m.group("qtable") or m.group("table_bare")
|
|
130
|
+
ref = m.group("ref")
|
|
131
|
+
formatted_ref = f"{tbl}[{ref}]" if tbl else f"[{ref}]"
|
|
132
|
+
if formatted_ref not in refs:
|
|
133
|
+
refs.append(formatted_ref)
|
|
134
|
+
|
|
135
|
+
upper = expr.upper()
|
|
136
|
+
operations: list[str] = []
|
|
137
|
+
for fn, label in [
|
|
138
|
+
("CALCULATE(", "filtered context calculation"),
|
|
139
|
+
("SUMX(", "row-by-row sum iteration"),
|
|
140
|
+
("SUM(", "sum aggregation"),
|
|
141
|
+
("AVERAGEX(", "row-by-row average iteration"),
|
|
142
|
+
("AVERAGE(", "average aggregation"),
|
|
143
|
+
("DIVIDE(", "safe ratio division"),
|
|
144
|
+
("DISTINCTCOUNT(", "distinct count"),
|
|
145
|
+
("COUNTROWS(", "row count"),
|
|
146
|
+
("SAMEPERIODLASTYEAR(", "year-over-year time intelligence"),
|
|
147
|
+
("DATESYTD(", "year-to-date time intelligence"),
|
|
148
|
+
("TOTALYTD(", "year-to-date aggregation"),
|
|
149
|
+
("DATEADD(", "date-shifted time intelligence"),
|
|
150
|
+
("FILTER(", "table filtering"),
|
|
151
|
+
]:
|
|
152
|
+
if fn in upper:
|
|
153
|
+
operations.append(label)
|
|
154
|
+
|
|
155
|
+
table_clause = f" in {table_name}" if table_name else ""
|
|
156
|
+
op_clause = f" using {', '.join(operations[:3])}" if operations else ""
|
|
157
|
+
ref_clause = f" (references: {', '.join(refs[:5])})" if refs else ""
|
|
158
|
+
usage_parts: list[str] = []
|
|
159
|
+
if dependent_measure_count > 0:
|
|
160
|
+
usage_parts.append(f"{dependent_measure_count} measure(s)")
|
|
161
|
+
if dependent_visual_count > 0:
|
|
162
|
+
usage_parts.append(f"{dependent_visual_count} visual(s)")
|
|
163
|
+
usage_clause = f" Used by {' and '.join(usage_parts)}." if usage_parts else ""
|
|
164
|
+
return f"Computes {measure_name}{table_clause}{op_clause}{ref_clause}.{usage_clause}"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _normalize_rel_endpoint(endpoint: str | None) -> tuple[str, str] | None:
|
|
168
|
+
if not endpoint or "." not in endpoint:
|
|
169
|
+
return None
|
|
170
|
+
tbl, col = endpoint.split(".", 1)
|
|
171
|
+
return tbl.strip("'\" "), col.strip("'\"[] ")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def find_unused_objects(info: WorkspaceInfo) -> dict[str, Any]:
|
|
175
|
+
"""Identify unreferenced measures and columns across the Semantic Model and Report Layout."""
|
|
176
|
+
return find_unused_model_objects(info)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def check_model_bpa(info: WorkspaceInfo) -> dict[str, Any]:
|
|
180
|
+
"""Run Best Practice Analyzer rules against the Semantic Model and Report Layout."""
|
|
181
|
+
ws_id = info.workspace_id or compute_workspace_id(info.root, info.pbip_file)
|
|
182
|
+
objects = scan_model(info.semantic_model_dir, info.root, workspace_id=ws_id)
|
|
183
|
+
issues: list[BpaIssue] = []
|
|
184
|
+
|
|
185
|
+
columns_by_key: dict[tuple[str, str], TmdlObject] = {}
|
|
186
|
+
measures_by_name_cf: dict[str, TmdlObject] = {}
|
|
187
|
+
measures_by_key: dict[tuple[str, str], TmdlObject] = {}
|
|
188
|
+
|
|
189
|
+
for obj in objects:
|
|
190
|
+
if obj.kind in {"column", "calculated_column"} and obj.table:
|
|
191
|
+
columns_by_key[(obj.table.casefold(), obj.name.casefold())] = obj
|
|
192
|
+
elif obj.kind == "measure":
|
|
193
|
+
measures_by_name_cf[obj.name.casefold()] = obj
|
|
194
|
+
if obj.table:
|
|
195
|
+
measures_by_key[(obj.table.casefold(), obj.name.casefold())] = obj
|
|
196
|
+
|
|
197
|
+
# Rule 1, 2, 7, 8: Relationship checks
|
|
198
|
+
for rel in [x for x in objects if x.kind == "relationship"]:
|
|
199
|
+
if (rel.cross_filtering or "").casefold() == "bothdirections":
|
|
200
|
+
issues.append(
|
|
201
|
+
BpaIssue(
|
|
202
|
+
rule_id="BPA_BIDIRECTIONAL_RELATIONSHIP",
|
|
203
|
+
severity="warning",
|
|
204
|
+
category="Relationships",
|
|
205
|
+
object_type="relationship",
|
|
206
|
+
object_name=rel.name,
|
|
207
|
+
object_id=rel.object_id,
|
|
208
|
+
message=f"Relationship {rel.name!r} uses bidirectional cross-filtering.",
|
|
209
|
+
recommendation="Prefer single-direction filtering and use CROSSFILTER inside specific measures when needed.",
|
|
210
|
+
file=rel.file,
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
if (
|
|
214
|
+
(rel.from_cardinality or "").casefold() == "many"
|
|
215
|
+
and (rel.to_cardinality or "").casefold() == "many"
|
|
216
|
+
):
|
|
217
|
+
issues.append(
|
|
218
|
+
BpaIssue(
|
|
219
|
+
rule_id="BPA_MANY_TO_MANY_RELATIONSHIP",
|
|
220
|
+
severity="warning",
|
|
221
|
+
category="Relationships",
|
|
222
|
+
object_type="relationship",
|
|
223
|
+
object_name=rel.name,
|
|
224
|
+
object_id=rel.object_id,
|
|
225
|
+
message=f"Relationship {rel.name!r} uses many-to-many cardinality.",
|
|
226
|
+
recommendation="Introduce a bridging dimension table to avoid ambiguous filter propagation.",
|
|
227
|
+
file=rel.file,
|
|
228
|
+
)
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
from_ep = _normalize_rel_endpoint(rel.from_column)
|
|
232
|
+
to_ep = _normalize_rel_endpoint(rel.to_column)
|
|
233
|
+
for ep_name, ep in (("fromColumn", from_ep), ("toColumn", to_ep)):
|
|
234
|
+
if not ep:
|
|
235
|
+
continue
|
|
236
|
+
col_obj = columns_by_key.get((ep[0].casefold(), ep[1].casefold()))
|
|
237
|
+
if not col_obj:
|
|
238
|
+
issues.append(
|
|
239
|
+
BpaIssue(
|
|
240
|
+
rule_id="BPA_BROKEN_RELATIONSHIP_ENDPOINT",
|
|
241
|
+
severity="error",
|
|
242
|
+
category="Relationships",
|
|
243
|
+
object_type="relationship",
|
|
244
|
+
object_name=rel.name,
|
|
245
|
+
object_id=rel.object_id,
|
|
246
|
+
message=f"Relationship {rel.name!r} {ep_name} references missing column '{ep[0]}[{ep[1]}]'.",
|
|
247
|
+
recommendation="Update or remove the broken relationship endpoint in relationships.tmdl.",
|
|
248
|
+
file=rel.file,
|
|
249
|
+
)
|
|
250
|
+
)
|
|
251
|
+
elif ep_name == "fromColumn" and not col_obj.is_hidden:
|
|
252
|
+
issues.append(
|
|
253
|
+
BpaIssue(
|
|
254
|
+
rule_id="BPA_UNHIDDEN_FOREIGN_KEY",
|
|
255
|
+
severity="warning",
|
|
256
|
+
category="Maintenance",
|
|
257
|
+
object_type="column",
|
|
258
|
+
object_name=col_obj.name,
|
|
259
|
+
table=col_obj.table,
|
|
260
|
+
object_id=col_obj.object_id,
|
|
261
|
+
message=f"Foreign key column '{col_obj.table}[{col_obj.name}]' used in relationship {rel.name!r} is visible.",
|
|
262
|
+
recommendation="Hide foreign key columns on the many-side of relationships so users filter via dimension tables.",
|
|
263
|
+
file=col_obj.file,
|
|
264
|
+
)
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
# Rule 3, 4, 6: Measure checks
|
|
268
|
+
for m in [x for x in objects if x.kind == "measure"]:
|
|
269
|
+
if not (m.description or "").strip():
|
|
270
|
+
issues.append(
|
|
271
|
+
BpaIssue(
|
|
272
|
+
rule_id="BPA_MISSING_MEASURE_DESCRIPTION",
|
|
273
|
+
severity="info",
|
|
274
|
+
category="Maintenance",
|
|
275
|
+
object_type="measure",
|
|
276
|
+
object_name=m.name,
|
|
277
|
+
table=m.table,
|
|
278
|
+
object_id=m.object_id,
|
|
279
|
+
message=f"Measure '{m.name}' has no /// documentation description.",
|
|
280
|
+
recommendation="Use generate_measure_docs to add a TMDL /// description comment.",
|
|
281
|
+
file=m.file,
|
|
282
|
+
)
|
|
283
|
+
)
|
|
284
|
+
if not (m.format_string or "").strip():
|
|
285
|
+
issues.append(
|
|
286
|
+
BpaIssue(
|
|
287
|
+
rule_id="BPA_MISSING_FORMAT_STRING",
|
|
288
|
+
severity="warning",
|
|
289
|
+
category="Formatting",
|
|
290
|
+
object_type="measure",
|
|
291
|
+
object_name=m.name,
|
|
292
|
+
table=m.table,
|
|
293
|
+
object_id=m.object_id,
|
|
294
|
+
message=f"Measure '{m.name}' is missing an explicit formatString.",
|
|
295
|
+
recommendation="Specify a formatString (e.g. '#,##0' or '$#,##0.00') for consistent visual rendering.",
|
|
296
|
+
file=m.file,
|
|
297
|
+
)
|
|
298
|
+
)
|
|
299
|
+
if m.expression and "/" in m.expression and "DIVIDE(" not in m.expression.upper():
|
|
300
|
+
issues.append(
|
|
301
|
+
BpaIssue(
|
|
302
|
+
rule_id="BPA_DIRECT_DIVISION_OPERATOR",
|
|
303
|
+
severity="info",
|
|
304
|
+
category="DAX",
|
|
305
|
+
object_type="measure",
|
|
306
|
+
object_name=m.name,
|
|
307
|
+
table=m.table,
|
|
308
|
+
object_id=m.object_id,
|
|
309
|
+
message=f"Measure '{m.name}' uses the '/' division operator directly.",
|
|
310
|
+
recommendation="Use DIVIDE(numerator, denominator) to handle division-by-zero safely.",
|
|
311
|
+
file=m.file,
|
|
312
|
+
)
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
# Rule 5 & 9: Column data types and calculated column complexity
|
|
316
|
+
for col in [x for x in objects if x.kind in {"column", "calculated_column"}]:
|
|
317
|
+
if (col.data_type or "").casefold() == "double":
|
|
318
|
+
issues.append(
|
|
319
|
+
BpaIssue(
|
|
320
|
+
rule_id="BPA_FLOAT_DATA_TYPE",
|
|
321
|
+
severity="warning",
|
|
322
|
+
category="Performance",
|
|
323
|
+
object_type=col.kind,
|
|
324
|
+
object_name=col.name,
|
|
325
|
+
table=col.table,
|
|
326
|
+
object_id=col.object_id,
|
|
327
|
+
message=f"Column '{col.table}[{col.name}]' uses floating-point 'double' dataType.",
|
|
328
|
+
recommendation="Use 'decimal' (Fixed Decimal Currency) or 'int64' to prevent floating-point rounding inaccuracies.",
|
|
329
|
+
file=col.file,
|
|
330
|
+
)
|
|
331
|
+
)
|
|
332
|
+
if col.kind == "calculated_column" and col.expression:
|
|
333
|
+
upper_expr = col.expression.upper()
|
|
334
|
+
if any(fn in upper_expr for fn in ("SUMX(", "FILTER(", "CALCULATE(", "RELATEDTABLE(", "LOOKUPVALUE(")):
|
|
335
|
+
issues.append(
|
|
336
|
+
BpaIssue(
|
|
337
|
+
rule_id="BPA_CALCULATED_COLUMN_COMPLEXITY",
|
|
338
|
+
severity="warning",
|
|
339
|
+
category="Performance",
|
|
340
|
+
object_type="calculated_column",
|
|
341
|
+
object_name=col.name,
|
|
342
|
+
table=col.table,
|
|
343
|
+
object_id=col.object_id,
|
|
344
|
+
message=f"Calculated column '{col.table}[{col.name}]' uses context transition or table scan functions.",
|
|
345
|
+
recommendation="Push calculated column logic upstream to SQL/Power Query or convert to a DAX measure.",
|
|
346
|
+
file=col.file,
|
|
347
|
+
)
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
# Rule 10, 11, 12: Report Layout checks (broken visual bindings, empty pages, duplicate visuals)
|
|
351
|
+
if info.report_dir and info.report_dir.exists() and objects:
|
|
352
|
+
pages = list_pages(info.report_dir, info.root, workspace_id=ws_id)
|
|
353
|
+
visuals = list_visuals(info.report_dir, info.root, workspace_id=ws_id)
|
|
354
|
+
|
|
355
|
+
for p in pages:
|
|
356
|
+
if p.get("visual_count", 0) == 0:
|
|
357
|
+
issues.append(
|
|
358
|
+
BpaIssue(
|
|
359
|
+
rule_id="BPA_EMPTY_REPORT_PAGE",
|
|
360
|
+
severity="info",
|
|
361
|
+
category="Report",
|
|
362
|
+
object_type="page",
|
|
363
|
+
object_name=str(p.get("display_name") or p.get("name")),
|
|
364
|
+
object_id=p.get("object_id"),
|
|
365
|
+
message=f"Report page '{p.get('display_name') or p.get('name')}' contains 0 visuals.",
|
|
366
|
+
recommendation="Remove unused blank pages or populate with visuals before publishing.",
|
|
367
|
+
file=p.get("file"),
|
|
368
|
+
)
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
seen_visual_signatures: dict[tuple[str, str, tuple[str, ...]], str] = {}
|
|
372
|
+
for v in visuals:
|
|
373
|
+
# Check for broken bindings
|
|
374
|
+
for qref in v.bound_fields:
|
|
375
|
+
if "." not in qref:
|
|
376
|
+
continue
|
|
377
|
+
tbl, prop = qref.split(".", 1)
|
|
378
|
+
t_cf = tbl.strip("'\" ").casefold()
|
|
379
|
+
p_cf = prop.strip("'\"[] ").casefold()
|
|
380
|
+
has_col = (t_cf, p_cf) in columns_by_key
|
|
381
|
+
has_meas = (t_cf, p_cf) in measures_by_key or p_cf in measures_by_name_cf
|
|
382
|
+
if not has_col and not has_meas:
|
|
383
|
+
issues.append(
|
|
384
|
+
BpaIssue(
|
|
385
|
+
rule_id="BPA_BROKEN_VISUAL_BINDING",
|
|
386
|
+
severity="error",
|
|
387
|
+
category="Report",
|
|
388
|
+
object_type="visual",
|
|
389
|
+
object_name=v.visual_id,
|
|
390
|
+
object_id=v.object_id,
|
|
391
|
+
message=f"Visual '{v.title or v.visual_id}' on page '{v.page_display_name}' binds to missing model field '{qref}'.",
|
|
392
|
+
recommendation="Use update_visual_fields to remove the stale field binding or bind the replacement field.",
|
|
393
|
+
file=v.file,
|
|
394
|
+
)
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
# Check for duplicate visuals on the same page with identical type and non-empty bound fields
|
|
398
|
+
if v.visual_type and v.bound_fields:
|
|
399
|
+
sig = (v.page.casefold(), v.visual_type.casefold(), tuple(sorted(f.casefold() for f in v.bound_fields)))
|
|
400
|
+
if sig in seen_visual_signatures:
|
|
401
|
+
first_vis_id = seen_visual_signatures[sig]
|
|
402
|
+
issues.append(
|
|
403
|
+
BpaIssue(
|
|
404
|
+
rule_id="BPA_DUPLICATE_VISUAL",
|
|
405
|
+
severity="info",
|
|
406
|
+
category="Report",
|
|
407
|
+
object_type="visual",
|
|
408
|
+
object_name=v.visual_id,
|
|
409
|
+
object_id=v.object_id,
|
|
410
|
+
message=(
|
|
411
|
+
f"Visual '{v.title or v.visual_id}' on page '{v.page_display_name}' has identical "
|
|
412
|
+
f"type ({v.visual_type}) and field bindings as visual '{first_vis_id}'."
|
|
413
|
+
),
|
|
414
|
+
recommendation="Consolidate duplicate visuals on the same report page.",
|
|
415
|
+
file=v.file,
|
|
416
|
+
)
|
|
417
|
+
)
|
|
418
|
+
else:
|
|
419
|
+
seen_visual_signatures[sig] = v.visual_id
|
|
420
|
+
|
|
421
|
+
by_severity = {
|
|
422
|
+
"error": sum(i.severity == "error" for i in issues),
|
|
423
|
+
"warning": sum(i.severity == "warning" for i in issues),
|
|
424
|
+
"info": sum(i.severity == "info" for i in issues),
|
|
425
|
+
}
|
|
426
|
+
by_category: dict[str, int] = {}
|
|
427
|
+
for i in issues:
|
|
428
|
+
by_category[i.category] = by_category.get(i.category, 0) + 1
|
|
429
|
+
|
|
430
|
+
health_status = (
|
|
431
|
+
"critical"
|
|
432
|
+
if by_severity["error"] > 0
|
|
433
|
+
else ("needs_attention" if by_severity["warning"] > 0 else "healthy")
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
return {
|
|
437
|
+
"issue_count": len(issues),
|
|
438
|
+
"by_severity": by_severity,
|
|
439
|
+
"by_category": by_category,
|
|
440
|
+
"health_summary": {
|
|
441
|
+
"status": health_status,
|
|
442
|
+
"error_count": by_severity["error"],
|
|
443
|
+
"warning_count": by_severity["warning"],
|
|
444
|
+
"info_count": by_severity["info"],
|
|
445
|
+
"top_recommendations": [i.recommendation for i in issues[:3]],
|
|
446
|
+
},
|
|
447
|
+
"issues": [i.model_dump() for i in issues],
|
|
448
|
+
}
|
pbi_mcp_server/config.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Settings:
|
|
10
|
+
workspace: Path
|
|
11
|
+
log_level: str = "INFO"
|
|
12
|
+
create_backups: bool = True
|
|
13
|
+
|
|
14
|
+
@classmethod
|
|
15
|
+
def from_values(cls, workspace: str | None = None) -> Settings:
|
|
16
|
+
raw = workspace or os.getenv("PBI_WORKSPACE_PATH")
|
|
17
|
+
if not raw:
|
|
18
|
+
raise ValueError("Provide --workspace or set PBI_WORKSPACE_PATH")
|
|
19
|
+
path = Path(raw).expanduser().resolve()
|
|
20
|
+
if not path.exists():
|
|
21
|
+
raise FileNotFoundError(f"Workspace does not exist: {path}")
|
|
22
|
+
backups = os.getenv("PBI_MCP_CREATE_BACKUPS", "true").lower() in {"1", "true", "yes"}
|
|
23
|
+
return cls(path, os.getenv("LOG_LEVEL", "INFO").upper(), backups)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Engine A: Semantic Model (TMDL) parsing and writing."""
|