@lightdash-tools/mcp 0.22.0 → 0.23.0

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.
@@ -11,12 +11,12 @@ Answer a data question by iterating Explore-style queries **without saving** a c
11
11
  1. `get_project` → confirm pin / `projectUuid`.
12
12
  2. `list_explores` with **`search` + `limit` (≤15)**. Prefer exact `label` or explore `name` containing `__{table}`; skip empty `schemaName` / errors.
13
13
  3. `get_explore` → lock `exploreId` (= explore `name` = `exploreName` for `run_metric_query`).
14
- 4. Shortlist dimensions (`list_dimensions`, base table default) and metrics (`list_metrics` filtered to this explore, or `tables[baseTable].metrics` from `get_explore`).
15
- 5. Optional: `compile_query` with the same fieldIds; verify SELECT aliases; ≤2 fix retries.
14
+ 4. Shortlist dimensions (`list_dimensions`, base table default; `baseTableOnly=false` for joins or ARRAY UNNEST tables `{base}__{column}`) and metrics (`list_metrics` filtered to this explore, or `tables[baseTable].metrics` from `get_explore`).
15
+ 5. Optional: `compile_query` with the same fieldIds; verify SELECT aliases; ≤2 fix retries. STRUCT dim `name`s with dots use `__` in `fieldId` from `list_dimensions` (copy that id). ARRAY fields live on join tables — copy those ids too.
16
16
  6. `run_metric_query` with:
17
17
  - `exploreName` = locked explore name
18
- - `dimensions` / `metrics` = full **fieldIds** only (`{table}_{name}`)
19
- - `filters` (dimensions/metrics only) / `sorts` / `limit` as needed — never send `tableCalculations`
18
+ - `dimensions` / `metrics` = full **fieldIds** only (`{table}_{name}`; STRUCT nested dots → `__`)
19
+ - `filters` (dimensions/metrics only) as `{ "id": "…", "and"|"or": [ rules ] }` FilterGroups / `sorts` / `limit` as needed — never send `tableCalculations`. MCP fills missing FilterGroup/FilterRule `id`s; still prefer explicit ids.
20
20
  - Rows are a **data artifact** by default (not inlined in the summary). Read `content[]` resource parts or `artifacts` catalog — do not expect `data.rows` in the summary JSON.
21
21
  7. If status is running, poll `get_query_result` with the returned `queryUuid` (same artifact shape). Cancel with `cancel_query` when abandoning.
22
22
  8. Iterate: change dims/metrics/filters and re-run. Do **not** create charts unless the user asks to save (then hand off to content-developer).
@@ -25,24 +25,50 @@ URI: `lightdash://playbooks/semantic-layer/compose-compile`
25
25
 
26
26
  `metrics` may be `[]`. Every string in `dimensions` / `metrics` / `sorts[].fieldId` must appear in prior tool output.
27
27
 
28
- MCP `compile_query` always sets `exploreName` from the tool `exploreId` (path is authoritative) and defaults missing `tableCalculations` to `[]`. Keep the full skeleton for other OpenAPI-required keys (`filters`, `sorts`, `limit`, …) and for CLI/JSON callers. Prefer SELECT aliases / metric `compiledSql` over metric **name/label** when they disagree.
28
+ MCP `compile_query` always sets `exploreName` from the tool `exploreId` (path is authoritative), defaults missing `tableCalculations` to `[]`, and **fills missing FilterGroup/FilterRule `id`s** (does not invent wrappers for unknown shapes). Keep the full skeleton for other OpenAPI-required keys (`filters`, `sorts`, `limit`, …) and for CLI/JSON callers. Prefer SELECT aliases / metric `compiledSql` over metric **name/label** when they disagree.
29
+
30
+ When filters are non-empty, prefer an explicit FilterGroup:
31
+
32
+ ```json
33
+ {
34
+ "filters": {
35
+ "dimensions": {
36
+ "id": "dim-filters-1",
37
+ "and": [
38
+ {
39
+ "id": "rule-1",
40
+ "target": { "fieldId": "{exploreId}_{dim}" },
41
+ "operator": "equals",
42
+ "values": ["example"]
43
+ }
44
+ ]
45
+ }
46
+ }
47
+ }
48
+ ```
49
+
50
+ MCP may inject missing `id`s; still copy this shape so non-MCP clients and hosts that bypass hardeners succeed.
29
51
 
30
52
  ## Field IDs — failure modes
31
53
 
32
- | Symptom | Cause | Fix |
33
- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
34
- | `unknown field id` / hard error | Short names or typos | Use full `fieldId` from `list_dimensions` / `{exploreId}_{metricName}` |
35
- | Server `isError` + empty SELECT | Upstream accepted bad ids with **zero** columns | Replace with real fieldIds; re-compile once |
36
- | SQL “succeeds” but a requested dim/metric is **missing** from SELECT | Invented or wrong fieldId (e.g. non-existent `*_session_day`) while another field still projected | Re-check against `list_dimensions` / metrics map; re-compile |
37
- | `UPSTREAM_VALIDATION` / `'tableCalculations' is required` | Body omitted `tableCalculations` (pre-harden / non-MCP clients) | MCP defaults to `[]`; pass `tableCalculations: []` explicitly if needed |
38
- | `UPSTREAM_VALIDATION` / `'exploreName' is required` | Body omitted `exploreName` (pre-harden / non-MCP clients) or wrong exploreId | Pass locked `exploreId`; MCP fills `exploreName` — re-compile once |
39
- | `Metric not found` on `get_metric` | `tableName` was warehouse label | Use full explore id |
40
- | Lineage works with short name but compile fails | `get_field_lineage` accepts short names; `compile_query` does not | Always copy full `fieldId` into `metricQuery` |
54
+ | Symptom | Cause | Fix |
55
+ | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
56
+ | `unknown field id` / hard error | Short names or typos | Use full `fieldId` from `list_dimensions` / `{exploreId}_{metricName}` |
57
+ | Server `isError` + empty SELECT | Upstream accepted bad ids with **zero** columns | Replace with real fieldIds; re-compile once |
58
+ | Server `isError` + missing SELECT aliases | Invented id, dotted STRUCT id (`…_customer.first_name` vs `…_customer__first_name`), or ARRAY join id without `baseTableOnly=false` | Copy `fieldId` from `list_dimensions` (STRUCT dots → `__`; ARRAY via join tables); re-compile |
59
+ | SQL “succeeds” but a requested dim/metric is **missing** from SELECT | Invented or wrong fieldId while another field still projected (pre-guard / non-MCP clients) | Re-check against `list_dimensions` / metrics map; re-compile |
60
+ | `UPSTREAM_VALIDATION` / `'tableCalculations' is required` | Body omitted `tableCalculations` (pre-harden / non-MCP clients) | MCP defaults to `[]`; pass `tableCalculations: []` explicitly if needed |
61
+ | `UPSTREAM_VALIDATION` / `'exploreName' is required` | Body omitted `exploreName` (pre-harden / non-MCP clients) or wrong exploreId | Pass locked `exploreId`; MCP fills `exploreName` — re-compile once |
62
+ | `UPSTREAM_VALIDATION` on `filters.dimensions` (`'id'/'or' required`) | FilterGroup missing top-level `id` (rules alone are not enough; pre-harden / non-MCP) | Prefer `{ "id": "…", "and": [ { "id": "…", "target": { "fieldId": "…" }, "operator": "…", "values": […] } ] }`; MCP fills missing ids |
63
+ | `Metric not found` on `get_metric` | `tableName` was warehouse label | Use full explore id |
64
+ | Lineage works with short name but compile fails | `get_field_lineage` accepts short names; `compile_query` does not | Always copy full `fieldId` into `metricQuery` |
41
65
 
42
66
  Compiled SQL may include **extra related metrics** the semantic layer pulls in — OK if every **requested** fieldId still appears as a SELECT alias. Prefer SELECT aliases / metric `compiledSql` over metric **name/label** when they disagree (e.g. a metric named `num_unique_order_ids` that actually `COUNT(DISTINCT customer_id)`).
43
67
 
44
68
  ## Verify after every compile (mandatory)
45
69
 
70
+ MCP `compile_query` sets `isError` when the SELECT is empty or when requested `dimensions` / `metrics` are missing from SELECT aliases. Still verify locally (belt-and-suspenders for hosts that ignore `isError`):
71
+
46
72
  1. Parse the compiled `query` SELECT list (aliases / AS names).
47
73
  2. Confirm **each** requested dimension and metric `fieldId` is present.
48
74
  3. If any are missing → treat as failure even when the tool did not set `isError`.
@@ -60,7 +86,7 @@ When the user asks for N insights on one table/explore:
60
86
  ## Debug checklist
61
87
 
62
88
  - Unknown field id / short names / empty SELECT / missing SELECT alias → fix fieldIds from `list_dimensions` + explore-local metrics; re-compile (≤2 retries). Prefer SELECT aliases / `compiledSql` over metric name/label.
63
- - Other OpenAPI-required keys still failing (`filters`, `sorts`, `limit`, …) → copy the skeleton; MCP already fills `exploreName` and missing `tableCalculations`.
89
+ - Other OpenAPI-required keys still failing (`filters`, `sorts`, `limit`, …) → copy the skeleton; MCP already fills `exploreName`, missing `tableCalculations`, and missing filter `id`s.
64
90
  - Wrong explore → re-disambiguate (`schemaName`; exact `label` or `name` `__{table}`; skip empty schema / eda unless asked).
65
91
  - Catalog empty / metric not found → `get_explore` `tables[baseTable].metrics`; compile as `{exploreId}_{metricName}`.
66
92
  - Stop after a good verified compile or a clear blocker.
@@ -31,15 +31,15 @@ Record when a budget stopped you.
31
31
 
32
32
  ## Allowed tools (`lightdash_` prefix)
33
33
 
34
- | Tool | Use for |
35
- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
- | `list_projects` / `get_project` | Confirm UUID ↔ name. Credentials never returned (`REDACTED` warning is normal). |
37
- | `list_explores` | Summaries only. **Always** pass `search` + `limit`. |
38
- | `list_dimensions` | Compact `{ name, label, table, type, fieldId }`. Default = base table only. |
39
- | `get_explore` | **Preferred** metric menu: `tables[baseTable].metrics` names/labels only. Ignore join **metrics**; joined dims via `list_dimensions` (`baseTableOnly=false`) when needed. |
40
- | `list_metrics` / `get_metric` | Optional catalog / definition dig. Filter `tableName === exploreId`. |
41
- | `compile_query` | Compile only — never “run”. Sets `exploreName` from `exploreId`; defaults missing `tableCalculations` to `[]`. Prefer compiled SQL aliases over metric labels. |
42
- | `get_field_lineage` | Optional provenance; summarize, don’t dump. |
34
+ | Tool | Use for |
35
+ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
+ | `list_projects` / `get_project` | Confirm UUID ↔ name. Credentials never returned (`REDACTED` warning is normal). |
37
+ | `list_explores` | Summaries only. **Always** pass `search` + `limit`. |
38
+ | `list_dimensions` | Compact `{ name, label, table, type, fieldId }`. Default = base table only. Use `baseTableOnly=false` for ordinary joins **and** ARRAY UNNEST tables (`{base}__{column}`). |
39
+ | `get_explore` | **Preferred** metric menu: `tables[baseTable].metrics` names/labels only. Ignore join **metrics**; joined/ARRAY dims via `list_dimensions` (`baseTableOnly=false`) when needed. |
40
+ | `list_metrics` / `get_metric` | Optional catalog / definition dig. Filter `tableName === exploreId`. |
41
+ | `compile_query` | Compile only — never “run”. Sets `exploreName` from `exploreId`; defaults missing `tableCalculations` to `[]`. Prefer compiled SQL aliases over metric labels. |
42
+ | `get_field_lineage` | Optional provenance; summarize, don’t dump. |
43
43
 
44
44
  ## Project scope (critical)
45
45
 
@@ -36,7 +36,7 @@ Remember: `databaseName` may differ from the Lightdash project’s usual warehou
36
36
  ## Progressive discovery
37
37
 
38
38
  1. `list_explores` → disambiguate → lock `exploreId` (= explore `name`).
39
- 2. `list_dimensions` (default `baseTableOnly=true`). Set `baseTableOnly=false` only if you need joined-table fields (payload grows a lot).
39
+ 2. `list_dimensions` (default `baseTableOnly=true`). Set `baseTableOnly=false` when you need joined-table fields **or** repeated ARRAY nests (payload grows a lot). `get_explore` may show ARRAY nests as `joinedTables` / `tables[…].nestedFrom` with names like `{baseTable}__{column}`.
40
40
  3. Metrics: **`get_explore` → `tables[baseTable].metrics` only** (see below). Ignore join metrics; do not dump the explore JSON.
41
41
  4. Stop at a shortlist unless the user asked to compile.
42
42
 
@@ -58,7 +58,18 @@ Rules:
58
58
  3. `get_metric` `tableName` must be the full explore id. Short labels → “Metric not found”. Call only when definition/SQL is needed; summarize — payloads include huge `availableTimeDimensions` from joins. Prefer `compiledSql` over name/label when they disagree.
59
59
  4. Compile metric ids as `{exploreId}_{metricName}` (same pattern as dimension `fieldId` from `list_dimensions`).
60
60
  5. Dimension-only (`metrics: []`) is valid for volume-by-time; for “insights” prefer real explore metrics when available.
61
- 6. Joined **dimension** `fieldId`s (e.g. `customers_*` on an `orders` explore) are valid when `list_dimensions` with `baseTableOnly=false` returns them — use only those copied ids.
61
+ 6. Joined **dimension** `fieldId`s (ordinary joins like `customers_*`, or ARRAY UNNEST tables like `{base}__payments_*`) are valid when `list_dimensions` with `baseTableOnly=false` returns them — use only those copied ids.
62
+
63
+ ## Nested dimensions: STRUCT vs ARRAY (critical)
64
+
65
+ Do **not** conflate these shapes:
66
+
67
+ | Shape | Where it lives | Discovery | Example `fieldId` |
68
+ | ------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | ----------------------------------------------- |
69
+ | **STRUCT** (non-repeated) | Still on `baseTable`; API `name` may contain dots (`customer.first_name`) | Default `list_dimensions` (`baseTableOnly=true`) is enough | `…_customer__first_name` (`.` in `name` → `__`) |
70
+ | **ARRAY** (repeated) | Join tables named `{baseTable}__{column}` (often `UNNEST` + `nestedFrom` on `get_explore`) | Requires `list_dimensions(..., baseTableOnly=false)` | `…__payments_payment_method`, `…__tags_value` |
71
+
72
+ Copy `fieldId` from tool output only. Do not invent `{base}_payments__amount` unless that exact id appears — ARRAY element fields often have simple `name`s on the join table, not dotted base-table names.
62
73
 
63
74
  ## Dimension shortlist (large explores)
64
75
 
@@ -73,7 +84,7 @@ Prefer high-signal fields that **appear in `list_dimensions`**, by **role**:
73
84
 
74
85
  Skip nested event dumps and deep struct paths unless the question targets them.
75
86
 
76
- **Copy `fieldId` literally.** Do not invent grains like `{explore}_session_day` if that string is not in `list_dimensions`.
87
+ **Copy `fieldId` literally.** Do not invent grains like `{explore}_session_day` if that string is not in `list_dimensions`. For STRUCT nests, `list_dimensions` emits compile-ready ids with dots → `__` — copy that `fieldId`; do not join `table` + dotted `name` yourself.
77
88
 
78
89
  ## Field lineage
79
90
 
@@ -11,6 +11,7 @@ const content_reader_js_1 = require("../../policy/content-reader.js");
11
11
  const result_limits_js_1 = require("../../policy/result-limits.js");
12
12
  const artifacts_js_1 = require("../lib/artifacts.js");
13
13
  const schema_fields_js_1 = require("../lib/schema-fields.js");
14
+ const ensure_filter_ids_js_1 = require("../semantic/ensure-filter-ids.js");
14
15
  const shared_js_1 = require("../shared.js");
15
16
  const types_js_1 = require("../types.js");
16
17
  const bounded_saved_query_js_1 = require("./bounded-saved-query.js");
@@ -45,7 +46,7 @@ const runMetricQueryInputSchema = zod_1.z.object({
45
46
  function registerRunMetricQuery(server, contextProvider) {
46
47
  (0, content_reader_js_1.registerContentReaderTool)(server, 'run_metric_query', {
47
48
  title: 'Run metric query',
48
- description: 'Execute an unsaved explore metric query (dimensions, metrics, filters, sorts). Bounded rows as a separate data artifact by default (same shape as get_query_result); no chart save; no tableCalculations/SQL. Prefer fieldIds from get_explore / list_dimensions / list_metrics.',
49
+ description: 'Execute an unsaved explore metric query (dimensions, metrics, filters, sorts). Fills missing FilterGroup/FilterRule ids. Bounded rows as a separate data artifact by default (same shape as get_query_result); no chart save; no tableCalculations/SQL. Prefer fieldIds from get_explore / list_dimensions / list_metrics.',
49
50
  safety: content_reader_js_1.METRIC_QUERY_SAFETY,
50
51
  inputSchema: runMetricQueryInputSchema.shape,
51
52
  }, (profile) => (0, shared_js_1.wrapTool)(contextProvider, (c) => async (args) => {
@@ -54,12 +55,13 @@ function registerRunMetricQuery(server, contextProvider) {
54
55
  const scope = (0, project_scope_js_1.resolveProjectScope)({ projectUuid: args.projectUuid });
55
56
  const limit = (0, result_limits_js_1.clampRowLimit)(args.limit);
56
57
  const include = (0, artifacts_js_1.parseIncludeArtifacts)(args.includeArtifacts, ['data']);
58
+ const filters = (0, ensure_filter_ids_js_1.ensureFilterIds)((_a = args.filters) !== null && _a !== void 0 ? _a : {});
57
59
  const body = {
58
60
  query: {
59
61
  exploreName: args.exploreName,
60
62
  dimensions: args.dimensions,
61
63
  metrics: args.metrics,
62
- filters: (_a = args.filters) !== null && _a !== void 0 ? _a : {},
64
+ filters,
63
65
  sorts: (_b = args.sorts) !== null && _b !== void 0 ? _b : [],
64
66
  limit,
65
67
  tableCalculations: [],
@@ -118,4 +118,53 @@ const PROJECT = '550e8400-e29b-41d4-a716-446655440000';
118
118
  (0, vitest_1.expect)(JSON.stringify(result)).toContain('PROJECT_SCOPE_REQUIRED');
119
119
  (0, vitest_1.expect)(runMetricQuery).not.toHaveBeenCalled();
120
120
  });
121
+ (0, vitest_1.it)('injects missing FilterGroup and FilterRule ids before run', async () => {
122
+ const runMetricQuery = vitest_1.vi.fn().mockResolvedValue({ queryUuid: 'q-filter' });
123
+ const getAsyncQueryResults = vitest_1.vi.fn().mockResolvedValue({
124
+ queryUuid: 'q-filter',
125
+ status: 'ready',
126
+ columns: {},
127
+ rows: [],
128
+ totalResults: 0,
129
+ });
130
+ const contextProvider = {
131
+ getContext: async () => ({
132
+ lightdashClient: {
133
+ v2: { query: { runMetricQuery, getAsyncQueryResults } },
134
+ },
135
+ auth: { mode: 'none' },
136
+ }),
137
+ };
138
+ const mockServer = { registerTool: vitest_1.vi.fn() };
139
+ (0, server_profile_js_1.bindServerProfile)(mockServer, 'data-analyst');
140
+ (0, run_metric_query_js_1.registerRunMetricQuery)(mockServer, contextProvider);
141
+ const [, , handler] = mockServer.registerTool.mock.calls[0];
142
+ const sessionId = (0, mcp_client_session_js_1.resolveMcpClientSessionId)({ sessionId: 'mcp-analyst-filters' });
143
+ await (0, mcp_client_session_js_1.runWithMcpClientSessionAsync)(sessionId, async () => {
144
+ await handler({
145
+ projectUuid: PROJECT,
146
+ exploreName: 'orders',
147
+ dimensions: ['orders_status'],
148
+ metrics: ['orders_order_count'],
149
+ filters: {
150
+ dimensions: {
151
+ and: [
152
+ {
153
+ target: { fieldId: 'orders_status' },
154
+ operator: 'equals',
155
+ values: ['completed'],
156
+ },
157
+ ],
158
+ },
159
+ },
160
+ limit: 10,
161
+ waitForResults: true,
162
+ timeoutMs: 5000,
163
+ });
164
+ });
165
+ const body = runMetricQuery.mock.calls[0][1];
166
+ (0, vitest_1.expect)(body.query.filters.dimensions.id).toBeTruthy();
167
+ (0, vitest_1.expect)(body.query.filters.dimensions.and[0].id).toBeTruthy();
168
+ (0, vitest_1.expect)(body.query.filters.dimensions.and[0].target.fieldId).toBe('orders_status');
169
+ });
121
170
  });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Fill missing FilterGroup / FilterRule `id`s for MetricQuery filters.
3
+ *
4
+ * Lightdash compile/run use strict Filters (id required). Chart-as-code FiltersInput
5
+ * auto-generates ids — that does not apply here. Only fill missing/empty ids via
6
+ * structural duck-typing; leave unrecognized shapes unchanged for flexibility.
7
+ */
8
+ /**
9
+ * Recursively ensure ids on FilterGroup / FilterRule-shaped nodes.
10
+ * Does not invent wrappers for arrays or rewrite other fields.
11
+ */
12
+ export declare function ensureFilterNode(node: unknown): unknown;
13
+ /**
14
+ * Ensure missing ids on `filters.dimensions|metrics|tableCalculations` FilterGroups.
15
+ * Empty `{}`, null, non-objects, and array-valued keys pass through unchanged.
16
+ */
17
+ export declare function ensureFilterIds(filters: unknown): unknown;
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ /**
3
+ * Fill missing FilterGroup / FilterRule `id`s for MetricQuery filters.
4
+ *
5
+ * Lightdash compile/run use strict Filters (id required). Chart-as-code FiltersInput
6
+ * auto-generates ids — that does not apply here. Only fill missing/empty ids via
7
+ * structural duck-typing; leave unrecognized shapes unchanged for flexibility.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.ensureFilterNode = ensureFilterNode;
11
+ exports.ensureFilterIds = ensureFilterIds;
12
+ const node_crypto_1 = require("node:crypto");
13
+ const stable_stringify_js_1 = require("../lib/stable-stringify.js");
14
+ function hasNonEmptyId(value) {
15
+ return typeof value === 'string' && value.length > 0;
16
+ }
17
+ function withId(node) {
18
+ if (hasNonEmptyId(node.id)) {
19
+ return node;
20
+ }
21
+ return Object.assign(Object.assign({}, node), { id: (0, node_crypto_1.randomUUID)() });
22
+ }
23
+ /**
24
+ * Recursively ensure ids on FilterGroup / FilterRule-shaped nodes.
25
+ * Does not invent wrappers for arrays or rewrite other fields.
26
+ */
27
+ function ensureFilterNode(node) {
28
+ if (!(0, stable_stringify_js_1.isRecord)(node)) {
29
+ return node;
30
+ }
31
+ const hasAnd = Array.isArray(node.and);
32
+ const hasOr = Array.isArray(node.or);
33
+ if (hasAnd && hasOr) {
34
+ // Ambiguous — do not invent structure; pass through for upstream validation.
35
+ return node;
36
+ }
37
+ if (hasAnd) {
38
+ const items = node.and.map((item) => ensureFilterNode(item));
39
+ return Object.assign(Object.assign({}, withId(node)), { and: items });
40
+ }
41
+ if (hasOr) {
42
+ const items = node.or.map((item) => ensureFilterNode(item));
43
+ return Object.assign(Object.assign({}, withId(node)), { or: items });
44
+ }
45
+ if ('target' in node && 'operator' in node) {
46
+ return withId(node);
47
+ }
48
+ return node;
49
+ }
50
+ /**
51
+ * Ensure missing ids on `filters.dimensions|metrics|tableCalculations` FilterGroups.
52
+ * Empty `{}`, null, non-objects, and array-valued keys pass through unchanged.
53
+ */
54
+ function ensureFilterIds(filters) {
55
+ if (!(0, stable_stringify_js_1.isRecord)(filters)) {
56
+ return filters;
57
+ }
58
+ const next = Object.assign({}, filters);
59
+ let touched = false;
60
+ // Always rewrite present FilterGroup keys — and/or groups allocate even when ids already exist.
61
+ // Fixed property names (not dynamic keys) keep security/detect-object-injection quiet.
62
+ if ('dimensions' in filters && !Array.isArray(filters.dimensions)) {
63
+ next.dimensions = ensureFilterNode(filters.dimensions);
64
+ touched = true;
65
+ }
66
+ if ('metrics' in filters && !Array.isArray(filters.metrics)) {
67
+ next.metrics = ensureFilterNode(filters.metrics);
68
+ touched = true;
69
+ }
70
+ if ('tableCalculations' in filters && !Array.isArray(filters.tableCalculations)) {
71
+ next.tableCalculations = ensureFilterNode(filters.tableCalculations);
72
+ touched = true;
73
+ }
74
+ return touched ? next : filters;
75
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * ensureFilterIds / ensureFilterNode unit tests.
3
+ */
4
+ export {};
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ /**
3
+ * ensureFilterIds / ensureFilterNode unit tests.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const vitest_1 = require("vitest");
7
+ const ensure_filter_ids_js_1 = require("./ensure-filter-ids.js");
8
+ (0, vitest_1.describe)('ensureFilterNode', () => {
9
+ (0, vitest_1.it)('fills missing group id on and-group and rule ids', () => {
10
+ const result = (0, ensure_filter_ids_js_1.ensureFilterNode)({
11
+ and: [
12
+ {
13
+ target: { fieldId: 'orders_status' },
14
+ operator: 'equals',
15
+ values: ['completed'],
16
+ },
17
+ ],
18
+ });
19
+ (0, vitest_1.expect)(result.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
20
+ (0, vitest_1.expect)(result.and).toHaveLength(1);
21
+ (0, vitest_1.expect)(result.and[0].id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
22
+ (0, vitest_1.expect)(result.and[0].target.fieldId).toBe('orders_status');
23
+ (0, vitest_1.expect)(result.and[0].operator).toBe('equals');
24
+ });
25
+ (0, vitest_1.it)('fills missing group id on or-group', () => {
26
+ const result = (0, ensure_filter_ids_js_1.ensureFilterNode)({
27
+ or: [{ target: { fieldId: 'orders_status' }, operator: 'isNull' }],
28
+ });
29
+ (0, vitest_1.expect)(result.id).toBeTruthy();
30
+ (0, vitest_1.expect)(result.or).toHaveLength(1);
31
+ });
32
+ (0, vitest_1.it)('preserves existing non-empty ids', () => {
33
+ const input = {
34
+ id: 'group-1',
35
+ and: [
36
+ {
37
+ id: 'rule-1',
38
+ target: { fieldId: 'orders_status' },
39
+ operator: 'equals',
40
+ values: ['shipped'],
41
+ },
42
+ ],
43
+ };
44
+ const result = (0, ensure_filter_ids_js_1.ensureFilterNode)(input);
45
+ (0, vitest_1.expect)(result.id).toBe('group-1');
46
+ (0, vitest_1.expect)(result.and[0].id).toBe('rule-1');
47
+ });
48
+ (0, vitest_1.it)('fills nested group ids', () => {
49
+ const result = (0, ensure_filter_ids_js_1.ensureFilterNode)({
50
+ id: 'root',
51
+ and: [
52
+ {
53
+ or: [{ target: { fieldId: 'orders_status' }, operator: 'equals', values: ['a'] }],
54
+ },
55
+ ],
56
+ });
57
+ (0, vitest_1.expect)(result.id).toBe('root');
58
+ (0, vitest_1.expect)(result.and[0].id).toBeTruthy();
59
+ (0, vitest_1.expect)(result.and[0].or[0].id).toBeTruthy();
60
+ });
61
+ (0, vitest_1.it)('leaves both and and or untouched', () => {
62
+ const input = {
63
+ and: [],
64
+ or: [],
65
+ };
66
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterNode)(input)).toBe(input);
67
+ });
68
+ (0, vitest_1.it)('passes through unrecognized shapes', () => {
69
+ const input = { foo: 1 };
70
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterNode)(input)).toBe(input);
71
+ });
72
+ (0, vitest_1.it)('passes through non-objects', () => {
73
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterNode)(null)).toBe(null);
74
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterNode)('x')).toBe('x');
75
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterNode)(1)).toBe(1);
76
+ });
77
+ (0, vitest_1.it)('treats empty string id as missing', () => {
78
+ const result = (0, ensure_filter_ids_js_1.ensureFilterNode)({
79
+ id: '',
80
+ and: [{ id: '', target: { fieldId: 'a' }, operator: 'equals' }],
81
+ });
82
+ (0, vitest_1.expect)(result.id.length).toBeGreaterThan(0);
83
+ (0, vitest_1.expect)(result.and[0].id.length).toBeGreaterThan(0);
84
+ });
85
+ });
86
+ (0, vitest_1.describe)('ensureFilterIds', () => {
87
+ (0, vitest_1.it)('returns empty filters unchanged', () => {
88
+ const empty = {};
89
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterIds)(empty)).toBe(empty);
90
+ });
91
+ (0, vitest_1.it)('returns non-objects unchanged', () => {
92
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterIds)(undefined)).toBeUndefined();
93
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterIds)(null)).toBe(null);
94
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterIds)('x')).toBe('x');
95
+ });
96
+ (0, vitest_1.it)('fills ids under dimensions and metrics', () => {
97
+ const result = (0, ensure_filter_ids_js_1.ensureFilterIds)({
98
+ dimensions: {
99
+ and: [{ target: { fieldId: 'orders_status' }, operator: 'equals', values: ['a'] }],
100
+ },
101
+ metrics: {
102
+ or: [{ target: { fieldId: 'orders_count' }, operator: 'greaterThan', values: [0] }],
103
+ },
104
+ });
105
+ (0, vitest_1.expect)(result.dimensions.id).toBeTruthy();
106
+ (0, vitest_1.expect)(result.dimensions.and[0].id).toBeTruthy();
107
+ (0, vitest_1.expect)(result.metrics.id).toBeTruthy();
108
+ (0, vitest_1.expect)(result.metrics.or[0].id).toBeTruthy();
109
+ });
110
+ (0, vitest_1.it)('fills tableCalculations group when present', () => {
111
+ const result = (0, ensure_filter_ids_js_1.ensureFilterIds)({
112
+ tableCalculations: {
113
+ and: [{ target: { fieldId: 'calc_1' }, operator: 'equals', values: [1] }],
114
+ },
115
+ });
116
+ (0, vitest_1.expect)(result.tableCalculations.id).toBeTruthy();
117
+ (0, vitest_1.expect)(result.tableCalculations.and[0].id).toBeTruthy();
118
+ });
119
+ (0, vitest_1.it)('leaves array-valued keys unchanged', () => {
120
+ const filters = {
121
+ dimensions: [{ target: { fieldId: 'orders_status' }, operator: 'equals' }],
122
+ };
123
+ (0, vitest_1.expect)((0, ensure_filter_ids_js_1.ensureFilterIds)(filters)).toBe(filters);
124
+ });
125
+ (0, vitest_1.it)('preserves unrelated keys', () => {
126
+ const result = (0, ensure_filter_ids_js_1.ensureFilterIds)({
127
+ dimensions: {
128
+ id: 'd1',
129
+ and: [{ id: 'r1', target: { fieldId: 'a' }, operator: 'equals' }],
130
+ },
131
+ custom: true,
132
+ });
133
+ (0, vitest_1.expect)(result.custom).toBe(true);
134
+ (0, vitest_1.expect)(result.dimensions.id).toBe('d1');
135
+ });
136
+ });
@@ -43,14 +43,35 @@ export declare function flattenExploreDimensions(explore: ApiExploreResults): {
43
43
  dimensions: DimensionLike[];
44
44
  };
45
45
  /**
46
- * Compact dimensions with compile_query fieldId `{table}_{name}`.
46
+ * Compile-ready fieldId matching Lightdash `getItemId`
47
+ * (`${table}_${name}` with every `.` in `name` → `__`; see lightdash#6320).
48
+ */
49
+ export declare function toFieldId(table: string, name: string): string;
50
+ /**
51
+ * Compact dimensions with compile_query fieldId via {@link toFieldId}.
47
52
  * When `baseTable` is set, keep only rows whose `table` equals that id (joined tables dropped).
53
+ * `name` stays the API value (may contain dots); `fieldId` is compile-ready.
48
54
  */
49
55
  export declare function summarizeDimensions(dimensions: readonly DimensionLike[], options?: {
50
56
  baseTable?: string;
51
57
  }): DimensionSummary[];
52
58
  /** True when compiled SQL has an empty projection (SELECT … FROM with no columns). */
53
59
  export declare function isEmptySelectSql(sql: string): boolean;
60
+ /**
61
+ * Collect SELECT aliases from compiled SQL (`AS \`alias\``, `AS "alias"`, or `AS alias`).
62
+ * Heuristic only (not a SQL parser): stops at the first FROM; CAST(... AS type) may
63
+ * contribute type names as extras. Prefer {@link findMissingFieldIds}, which skips the
64
+ * check when no aliases are found (inconclusive dialect/CTE parse).
65
+ */
66
+ export declare function extractSelectAliases(sql: string): string[];
67
+ /**
68
+ * Requested fieldIds that do not appear as SELECT aliases in compiled SQL.
69
+ * Returns [] when the alias extract is empty (inconclusive — e.g. CTE-truncated SELECT
70
+ * or an unsupported quote style) so compile_query does not false-fail closed.
71
+ */
72
+ export declare function findMissingFieldIds(requested: readonly string[], sql: string): string[];
73
+ /** Collect string fieldIds from metricQuery.dimensions and metricQuery.metrics. */
74
+ export declare function collectRequestedFieldIds(metricQuery: Record<string, unknown>): string[];
54
75
  /** Extract SQL text from a compile_query API payload. */
55
76
  export declare function extractCompiledSql(result: unknown): string | undefined;
56
77
  export {};
@@ -6,8 +6,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.toExploreSummary = toExploreSummary;
7
7
  exports.summarizeExplores = summarizeExplores;
8
8
  exports.flattenExploreDimensions = flattenExploreDimensions;
9
+ exports.toFieldId = toFieldId;
9
10
  exports.summarizeDimensions = summarizeDimensions;
10
11
  exports.isEmptySelectSql = isEmptySelectSql;
12
+ exports.extractSelectAliases = extractSelectAliases;
13
+ exports.findMissingFieldIds = findMissingFieldIds;
14
+ exports.collectRequestedFieldIds = collectRequestedFieldIds;
11
15
  exports.extractCompiledSql = extractCompiledSql;
12
16
  /** Map a summary explore to a compact MCP payload (drops fat explore fields). */
13
17
  function toExploreSummary(explore) {
@@ -73,8 +77,16 @@ function flattenExploreDimensions(explore) {
73
77
  return { baseTable: explore.baseTable, dimensions };
74
78
  }
75
79
  /**
76
- * Compact dimensions with compile_query fieldId `{table}_{name}`.
80
+ * Compile-ready fieldId matching Lightdash `getItemId`
81
+ * (`${table}_${name}` with every `.` in `name` → `__`; see lightdash#6320).
82
+ */
83
+ function toFieldId(table, name) {
84
+ return `${table}_${name.split('.').join('__')}`;
85
+ }
86
+ /**
87
+ * Compact dimensions with compile_query fieldId via {@link toFieldId}.
77
88
  * When `baseTable` is set, keep only rows whose `table` equals that id (joined tables dropped).
89
+ * `name` stays the API value (may contain dots); `fieldId` is compile-ready.
78
90
  */
79
91
  function summarizeDimensions(dimensions, options) {
80
92
  const baseTable = options === null || options === void 0 ? void 0 : options.baseTable;
@@ -85,7 +97,7 @@ function summarizeDimensions(dimensions, options) {
85
97
  const summary = {
86
98
  name: dim.name,
87
99
  table: dim.table,
88
- fieldId: `${dim.table}_${dim.name}`,
100
+ fieldId: toFieldId(dim.table, dim.name),
89
101
  };
90
102
  if (typeof dim.label === 'string')
91
103
  summary.label = dim.label;
@@ -100,6 +112,61 @@ function isEmptySelectSql(sql) {
100
112
  const normalized = sql.replace(/\s+/g, ' ').trim();
101
113
  return /SELECT FROM\b/i.test(normalized);
102
114
  }
115
+ /**
116
+ * Collect SELECT aliases from compiled SQL (`AS \`alias\``, `AS "alias"`, or `AS alias`).
117
+ * Heuristic only (not a SQL parser): stops at the first FROM; CAST(... AS type) may
118
+ * contribute type names as extras. Prefer {@link findMissingFieldIds}, which skips the
119
+ * check when no aliases are found (inconclusive dialect/CTE parse).
120
+ */
121
+ function extractSelectAliases(sql) {
122
+ var _a;
123
+ const normalized = sql.replace(/\s+/g, ' ').trim();
124
+ const selectMatch = /\bSELECT\b([\s\S]*?)(?:\bFROM\b|$)/i.exec(normalized);
125
+ if (!(selectMatch === null || selectMatch === void 0 ? void 0 : selectMatch[1]))
126
+ return [];
127
+ const selectList = selectMatch[1];
128
+ const aliases = [];
129
+ const quotedAs = /\bAS\s+(?:`([^`]+)`|"([^"]+)")/gi;
130
+ const plainAs = /\bAS\s+([A-Za-z_][\w$]*)/gi;
131
+ for (const match of selectList.matchAll(quotedAs)) {
132
+ const alias = (_a = match[1]) !== null && _a !== void 0 ? _a : match[2];
133
+ if (alias)
134
+ aliases.push(alias);
135
+ }
136
+ for (const match of selectList.matchAll(plainAs)) {
137
+ if (match[1])
138
+ aliases.push(match[1]);
139
+ }
140
+ return aliases;
141
+ }
142
+ /**
143
+ * Requested fieldIds that do not appear as SELECT aliases in compiled SQL.
144
+ * Returns [] when the alias extract is empty (inconclusive — e.g. CTE-truncated SELECT
145
+ * or an unsupported quote style) so compile_query does not false-fail closed.
146
+ */
147
+ function findMissingFieldIds(requested, sql) {
148
+ if (requested.length === 0)
149
+ return [];
150
+ const aliases = extractSelectAliases(sql);
151
+ if (aliases.length === 0)
152
+ return [];
153
+ const aliasSet = new Set(aliases);
154
+ return requested.filter((id) => !aliasSet.has(id));
155
+ }
156
+ /** Collect string fieldIds from metricQuery.dimensions and metricQuery.metrics. */
157
+ function collectRequestedFieldIds(metricQuery) {
158
+ const requested = [];
159
+ const batches = [metricQuery.dimensions, metricQuery.metrics];
160
+ for (const value of batches) {
161
+ if (!Array.isArray(value))
162
+ continue;
163
+ for (const entry of value) {
164
+ if (typeof entry === 'string' && entry.length > 0)
165
+ requested.push(entry);
166
+ }
167
+ }
168
+ return requested;
169
+ }
103
170
  /** Extract SQL text from a compile_query API payload. */
104
171
  function extractCompiledSql(result) {
105
172
  if (typeof result === 'string')
@@ -98,8 +98,9 @@ const explore_helpers_js_1 = require("./explore-helpers.js");
98
98
  (0, vitest_1.expect)((0, explore_helpers_js_1.summarizeExplores)(many, { search: 'e', limit: 3 })).toHaveLength(3);
99
99
  });
100
100
  });
101
- (0, vitest_1.describe)('summarizeDimensions', () => {
102
- (0, vitest_1.it)('keeps compact fields and adds fieldId as table_name', () => {
101
+ (0, vitest_1.describe)('toFieldId / summarizeDimensions', () => {
102
+ (0, vitest_1.it)('encodes flat names as table_name', () => {
103
+ (0, vitest_1.expect)((0, explore_helpers_js_1.toFieldId)('orders', 'created_at')).toBe('orders_created_at');
103
104
  (0, vitest_1.expect)((0, explore_helpers_js_1.summarizeDimensions)([
104
105
  {
105
106
  name: 'created_at',
@@ -128,6 +129,39 @@ const explore_helpers_js_1 = require("./explore-helpers.js");
128
129
  },
129
130
  ])[0]).sort()).toEqual(['fieldId', 'label', 'name', 'table', 'type']);
130
131
  });
132
+ (0, vitest_1.it)('replaces dots in nested names with double underscores (getItemId)', () => {
133
+ (0, vitest_1.expect)((0, explore_helpers_js_1.toFieldId)('orders_nested_demo', 'payments.amount')).toBe('orders_nested_demo_payments__amount');
134
+ (0, vitest_1.expect)((0, explore_helpers_js_1.summarizeDimensions)([
135
+ {
136
+ name: 'payments.amount',
137
+ table: 'orders_nested_demo',
138
+ label: 'Payments amount',
139
+ type: 'number',
140
+ },
141
+ {
142
+ name: 'customer.first_name',
143
+ table: 'orders_nested_demo',
144
+ type: 'string',
145
+ },
146
+ ])).toEqual([
147
+ {
148
+ name: 'payments.amount',
149
+ table: 'orders_nested_demo',
150
+ label: 'Payments amount',
151
+ type: 'number',
152
+ fieldId: 'orders_nested_demo_payments__amount',
153
+ },
154
+ {
155
+ name: 'customer.first_name',
156
+ table: 'orders_nested_demo',
157
+ type: 'string',
158
+ fieldId: 'orders_nested_demo_customer__first_name',
159
+ },
160
+ ]);
161
+ });
162
+ (0, vitest_1.it)('leaves names that already use __ unchanged', () => {
163
+ (0, vitest_1.expect)((0, explore_helpers_js_1.toFieldId)('orders', 'struct_col__id')).toBe('orders_struct_col__id');
164
+ });
131
165
  (0, vitest_1.it)('filters to base table when baseTable is set', () => {
132
166
  (0, vitest_1.expect)((0, explore_helpers_js_1.summarizeDimensions)([
133
167
  { name: 'a', table: 'orders' },
@@ -168,3 +202,40 @@ const explore_helpers_js_1 = require("./explore-helpers.js");
168
202
  (0, vitest_1.expect)((0, explore_helpers_js_1.extractCompiledSql)('raw')).toBe('raw');
169
203
  });
170
204
  });
205
+ (0, vitest_1.describe)('extractSelectAliases / findMissingFieldIds', () => {
206
+ const sampleSql = `
207
+ SELECT
208
+ \`orders_nested_demo\`.status AS \`orders_nested_demo_status\`,
209
+ COUNT(DISTINCT \`orders_nested_demo\`.order_id) AS \`orders_nested_demo_num_unique_order_ids\`
210
+ FROM \`analytics-dev\`.\`jaffle_shop\`.\`orders_nested_demo\` AS \`orders_nested_demo\`
211
+ GROUP BY 1
212
+ ORDER BY \`orders_nested_demo_num_unique_order_ids\` DESC
213
+ LIMIT 500`;
214
+ (0, vitest_1.it)('extracts backtick, double-quoted, and plain AS aliases from the SELECT list', () => {
215
+ (0, vitest_1.expect)((0, explore_helpers_js_1.extractSelectAliases)(sampleSql)).toEqual([
216
+ 'orders_nested_demo_status',
217
+ 'orders_nested_demo_num_unique_order_ids',
218
+ ]);
219
+ (0, vitest_1.expect)((0, explore_helpers_js_1.extractSelectAliases)('SELECT col AS plain_alias FROM t')).toEqual(['plain_alias']);
220
+ (0, vitest_1.expect)((0, explore_helpers_js_1.extractSelectAliases)('SELECT 1 AS `orders_status`')).toEqual(['orders_status']);
221
+ (0, vitest_1.expect)((0, explore_helpers_js_1.extractSelectAliases)('SELECT status AS "orders_status", COUNT(*) AS "orders_count" FROM orders')).toEqual(['orders_status', 'orders_count']);
222
+ });
223
+ (0, vitest_1.it)('reports requested fieldIds missing from SELECT aliases', () => {
224
+ (0, vitest_1.expect)((0, explore_helpers_js_1.findMissingFieldIds)([
225
+ 'orders_nested_demo_status',
226
+ 'orders_nested_demo_payments__payment_method',
227
+ 'orders_nested_demo_num_unique_order_ids',
228
+ ], sampleSql)).toEqual(['orders_nested_demo_payments__payment_method']);
229
+ (0, vitest_1.expect)((0, explore_helpers_js_1.findMissingFieldIds)(['orders_nested_demo_status', 'orders_nested_demo_num_unique_order_ids'], sampleSql)).toEqual([]);
230
+ });
231
+ (0, vitest_1.it)('skips missing-alias checks when no aliases could be parsed (CTE / inconclusive)', () => {
232
+ (0, vitest_1.expect)((0, explore_helpers_js_1.findMissingFieldIds)(['orders_status'], 'WITH x AS (SELECT 1 FROM dual) SELECT a AS `orders_status` FROM t')).toEqual([]);
233
+ });
234
+ (0, vitest_1.it)('collects string dimensions and metrics from metricQuery', () => {
235
+ (0, vitest_1.expect)((0, explore_helpers_js_1.collectRequestedFieldIds)({
236
+ dimensions: ['orders_status', 1, ''],
237
+ metrics: ['orders_count'],
238
+ sorts: [{ fieldId: 'orders_status' }],
239
+ })).toEqual(['orders_status', 'orders_count']);
240
+ });
241
+ });
@@ -11,12 +11,13 @@ const schema_fields_js_1 = require("../lib/schema-fields.js");
11
11
  const reader_tool_helpers_js_1 = require("../query/reader-tool-helpers.js");
12
12
  const shared_js_1 = require("../shared.js");
13
13
  const types_js_1 = require("../types.js");
14
+ const ensure_filter_ids_js_1 = require("./ensure-filter-ids.js");
14
15
  const explore_helpers_js_1 = require("./explore-helpers.js");
15
16
  const schema_fields_js_2 = require("./schema-fields.js");
16
17
  function registerCompileQuery(server, contextProvider) {
17
18
  (0, shared_js_1.registerToolSafe)(server, 'compile_query', {
18
19
  title: 'Compile query',
19
- description: 'Compile a metric query for an explore without executing it. Sets metricQuery.exploreName from exploreId (authoritative) and defaults missing tableCalculations to []. Empty SELECT (no columns) is returned as an error — use fieldId `{table}_{name}`, not short names. projectUuid optional when X-Lightdash-Project is set.',
20
+ description: 'Compile a metric query for an explore without executing it. Sets metricQuery.exploreName from exploreId (authoritative), defaults missing tableCalculations to [], and fills missing FilterGroup/FilterRule ids. Use fieldIds from list_dimensions (`{table}_{name}` with nested dots in name replaced by `__`). Empty SELECT or requested dimensions/metrics missing from SELECT aliases return isError. projectUuid optional when X-Lightdash-Project is set.',
20
21
  inputSchema: {
21
22
  projectUuid: (0, schema_fields_js_1.optionalProjectUuidField)(),
22
23
  exploreId: (0, schema_fields_js_2.exploreIdField)(),
@@ -26,26 +27,31 @@ function registerCompileQuery(server, contextProvider) {
26
27
  },
27
28
  annotations: shared_js_1.READ_ONLY_DEFAULT,
28
29
  }, (0, shared_js_1.wrapTool)(contextProvider, (c) => async ({ projectUuid, exploreId, metricQuery, }) => {
30
+ var _a;
29
31
  try {
30
32
  const scope = (0, project_scope_js_1.resolveProjectScope)({ projectUuid });
31
33
  // Path exploreId is authoritative; OpenAPI MetricQuery requires exploreName + tableCalculations.
32
- const body = Object.assign(Object.assign({}, metricQuery), { tableCalculations: Array.isArray(metricQuery.tableCalculations)
34
+ const body = Object.assign(Object.assign({}, metricQuery), { filters: (0, ensure_filter_ids_js_1.ensureFilterIds)((_a = metricQuery.filters) !== null && _a !== void 0 ? _a : {}), tableCalculations: Array.isArray(metricQuery.tableCalculations)
33
35
  ? metricQuery.tableCalculations
34
36
  : [], exploreName: exploreId });
35
37
  const result = await c.v1.query.compileQuery(scope.projectUuid, exploreId, body);
36
38
  const sql = (0, explore_helpers_js_1.extractCompiledSql)(result);
39
+ const sqlError = (text) => ({
40
+ content: [{ type: 'text', text }],
41
+ isError: true,
42
+ });
37
43
  if (sql && (0, explore_helpers_js_1.isEmptySelectSql)(sql)) {
38
- return {
39
- content: [
40
- {
41
- type: 'text',
42
- text: 'Error: compile_query produced an empty SELECT (no columns). ' +
43
- 'Use fieldId values like `{table}_{name}` from list_dimensions (base table), ' +
44
- 'not short field names. Re-compile after fixing metricQuery.',
45
- },
46
- ],
47
- isError: true,
48
- };
44
+ return sqlError('Error: compile_query produced an empty SELECT (no columns). ' +
45
+ 'Use fieldId values like `{table}_{name}` from list_dimensions (base table; nested dots → `__`), ' +
46
+ 'not short field names. Re-compile after fixing metricQuery.');
47
+ }
48
+ if (sql) {
49
+ const missing = (0, explore_helpers_js_1.findMissingFieldIds)((0, explore_helpers_js_1.collectRequestedFieldIds)(metricQuery), sql);
50
+ if (missing.length > 0) {
51
+ return sqlError('Error: compile_query SQL is missing SELECT aliases for requested fieldIds: ' +
52
+ `${missing.join(', ')}. ` +
53
+ 'Copy fieldIds from list_dimensions (nested name dots become `__`) and explore-local metrics; re-compile.');
54
+ }
49
55
  }
50
56
  return (0, shared_js_1.jsonToolResult)(result);
51
57
  }
@@ -131,4 +131,163 @@ function createCompileHandler(compileQuery) {
131
131
  });
132
132
  (0, vitest_1.expect)(compileQuery).toHaveBeenCalledWith(PROJECT, 'orders', vitest_1.expect.objectContaining({ tableCalculations }));
133
133
  });
134
+ (0, vitest_1.it)('returns isError when a requested dimension is missing from SELECT aliases', async () => {
135
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
136
+ query: 'SELECT COUNT(DISTINCT `orders`.order_id) AS `orders_num_unique_order_ids` FROM orders',
137
+ });
138
+ const { handler } = createCompileHandler(compileQuery);
139
+ const result = await handler({
140
+ projectUuid: PROJECT,
141
+ exploreId: 'orders',
142
+ metricQuery: {
143
+ dimensions: ['orders_payments.payment_method'],
144
+ metrics: ['orders_num_unique_order_ids'],
145
+ filters: {},
146
+ sorts: [],
147
+ limit: 50,
148
+ tableCalculations: [],
149
+ },
150
+ });
151
+ (0, vitest_1.expect)(result.isError).toBe(true);
152
+ (0, vitest_1.expect)(result.content[0].text).toContain('orders_payments.payment_method');
153
+ (0, vitest_1.expect)(result.content[0].text).toContain('missing SELECT aliases');
154
+ });
155
+ (0, vitest_1.it)('succeeds when every requested fieldId appears as a SELECT alias', async () => {
156
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
157
+ query: `
158
+ SELECT
159
+ \`orders\`.payments.payment_method AS \`orders_payments__payment_method\`,
160
+ SUM(\`orders\`.payments.amount) AS \`orders_sum_payment_amount\`
161
+ FROM orders
162
+ GROUP BY 1`,
163
+ });
164
+ const { handler } = createCompileHandler(compileQuery);
165
+ const result = await handler({
166
+ projectUuid: PROJECT,
167
+ exploreId: 'orders',
168
+ metricQuery: {
169
+ dimensions: ['orders_payments__payment_method'],
170
+ metrics: ['orders_sum_payment_amount'],
171
+ filters: {},
172
+ sorts: [],
173
+ limit: 50,
174
+ tableCalculations: [],
175
+ },
176
+ });
177
+ (0, vitest_1.expect)(result.isError).toBeUndefined();
178
+ (0, vitest_1.expect)(result.content[0].text).toContain('orders_payments__payment_method');
179
+ });
180
+ (0, vitest_1.it)('succeeds for double-quoted SELECT aliases (Postgres-style)', async () => {
181
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
182
+ query: 'SELECT status AS "orders_status", COUNT(*) AS "orders_count" FROM orders GROUP BY 1',
183
+ });
184
+ const { handler } = createCompileHandler(compileQuery);
185
+ const result = await handler({
186
+ projectUuid: PROJECT,
187
+ exploreId: 'orders',
188
+ metricQuery: {
189
+ dimensions: ['orders_status'],
190
+ metrics: ['orders_count'],
191
+ filters: {},
192
+ sorts: [],
193
+ limit: 50,
194
+ tableCalculations: [],
195
+ },
196
+ });
197
+ (0, vitest_1.expect)(result.isError).toBeUndefined();
198
+ });
199
+ (0, vitest_1.it)('does not isError when alias parse is inconclusive (CTE truncates SELECT list)', async () => {
200
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
201
+ query: 'WITH x AS (SELECT 1 FROM dual) SELECT a AS `orders_status` FROM t',
202
+ });
203
+ const { handler } = createCompileHandler(compileQuery);
204
+ const result = await handler({
205
+ projectUuid: PROJECT,
206
+ exploreId: 'orders',
207
+ metricQuery: {
208
+ dimensions: ['orders_status'],
209
+ metrics: [],
210
+ filters: {},
211
+ sorts: [],
212
+ limit: 50,
213
+ tableCalculations: [],
214
+ },
215
+ });
216
+ (0, vitest_1.expect)(result.isError).toBeUndefined();
217
+ });
218
+ (0, vitest_1.it)('injects missing FilterGroup and FilterRule ids before compile', async () => {
219
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
220
+ query: 'SELECT `orders`.status AS `orders_status` FROM orders',
221
+ });
222
+ const { handler } = createCompileHandler(compileQuery);
223
+ await handler({
224
+ projectUuid: PROJECT,
225
+ exploreId: 'orders',
226
+ metricQuery: {
227
+ dimensions: ['orders_status'],
228
+ metrics: [],
229
+ filters: {
230
+ dimensions: {
231
+ and: [
232
+ {
233
+ target: { fieldId: 'orders_status' },
234
+ operator: 'equals',
235
+ values: ['completed'],
236
+ },
237
+ ],
238
+ },
239
+ },
240
+ sorts: [],
241
+ limit: 50,
242
+ tableCalculations: [],
243
+ },
244
+ });
245
+ const body = compileQuery.mock.calls[0][2];
246
+ (0, vitest_1.expect)(body.filters.dimensions.id).toBeTruthy();
247
+ (0, vitest_1.expect)(body.filters.dimensions.and[0].id).toBeTruthy();
248
+ (0, vitest_1.expect)(body.filters.dimensions.and[0].target.fieldId).toBe('orders_status');
249
+ });
250
+ (0, vitest_1.it)('preserves existing filter ids', async () => {
251
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
252
+ query: 'SELECT `orders`.status AS `orders_status` FROM orders',
253
+ });
254
+ const { handler } = createCompileHandler(compileQuery);
255
+ await handler({
256
+ projectUuid: PROJECT,
257
+ exploreId: 'orders',
258
+ metricQuery: {
259
+ dimensions: ['orders_status'],
260
+ metrics: [],
261
+ filters: {
262
+ dimensions: {
263
+ id: 'keep-group',
264
+ and: [
265
+ {
266
+ id: 'keep-rule',
267
+ target: { fieldId: 'orders_status' },
268
+ operator: 'equals',
269
+ values: ['shipped'],
270
+ },
271
+ ],
272
+ },
273
+ },
274
+ sorts: [],
275
+ limit: 50,
276
+ tableCalculations: [],
277
+ },
278
+ });
279
+ (0, vitest_1.expect)(compileQuery).toHaveBeenCalledWith(PROJECT, 'orders', vitest_1.expect.objectContaining({
280
+ filters: {
281
+ dimensions: {
282
+ id: 'keep-group',
283
+ and: [
284
+ vitest_1.expect.objectContaining({
285
+ id: 'keep-rule',
286
+ target: { fieldId: 'orders_status' },
287
+ }),
288
+ ],
289
+ },
290
+ },
291
+ }));
292
+ });
134
293
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightdash-tools/mcp",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "MCP server for Lightdash semantic-layer, organization-audit, content-reader, content-developer, content-governance, ai-agent-ops, ai-agent-chat, and data-analyst profiles.",
5
5
  "keywords": [],
6
6
  "repository": {
@@ -24,8 +24,8 @@
24
24
  "commander": "^15.0.0",
25
25
  "hono": "^4.13.0",
26
26
  "zod": "^4.4.3",
27
- "@lightdash-tools/client": "0.22.0",
28
- "@lightdash-tools/common": "0.22.0"
27
+ "@lightdash-tools/client": "0.23.0",
28
+ "@lightdash-tools/common": "0.23.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@modelcontextprotocol/client": "2.0.0",