@lightdash-tools/mcp 0.23.0 → 0.25.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.
Files changed (87) hide show
  1. package/README.md +2 -2
  2. package/dist/auth/oauth-broker/as-metadata.d.ts +1 -0
  3. package/dist/auth/oauth-broker/as-metadata.js +5 -1
  4. package/dist/auth/oauth-broker/client-crypto.d.ts +12 -0
  5. package/dist/auth/oauth-broker/client-crypto.js +80 -0
  6. package/dist/auth/oauth-broker/client-directory.d.ts +39 -0
  7. package/dist/auth/oauth-broker/client-directory.js +104 -0
  8. package/dist/auth/oauth-broker/client-directory.test.d.ts +1 -0
  9. package/dist/auth/oauth-broker/client-directory.test.js +134 -0
  10. package/dist/auth/oauth-broker/lightdash-token.d.ts +8 -0
  11. package/dist/auth/oauth-broker/lightdash-token.js +72 -8
  12. package/dist/auth/oauth-broker/mcp-access-token.d.ts +3 -0
  13. package/dist/auth/oauth-broker/mcp-access-token.js +9 -1
  14. package/dist/auth/oauth-broker/pending-store.d.ts +16 -4
  15. package/dist/auth/oauth-broker/pending-store.js +40 -18
  16. package/dist/auth/oauth-broker/refresh-crypto.d.ts +19 -0
  17. package/dist/auth/oauth-broker/refresh-crypto.js +70 -0
  18. package/dist/auth/oauth-broker/refresh-crypto.test.d.ts +1 -0
  19. package/dist/auth/oauth-broker/refresh-crypto.test.js +40 -0
  20. package/dist/auth/oauth-broker/refresh-flow.test.d.ts +1 -0
  21. package/dist/auth/oauth-broker/refresh-flow.test.js +350 -0
  22. package/dist/auth/oauth-broker/refresh-grant.d.ts +46 -0
  23. package/dist/auth/oauth-broker/refresh-grant.js +288 -0
  24. package/dist/auth/oauth-broker/refresh-store.conformance.test.d.ts +1 -0
  25. package/dist/auth/oauth-broker/refresh-store.conformance.test.js +254 -0
  26. package/dist/auth/oauth-broker/refresh-store.d.ts +61 -0
  27. package/dist/auth/oauth-broker/refresh-store.js +124 -0
  28. package/dist/auth/oauth-broker/routes.d.ts +6 -4
  29. package/dist/auth/oauth-broker/routes.js +114 -51
  30. package/dist/auth/oauth-broker/routes.test.js +48 -0
  31. package/dist/auth/oauth-broker/stores/client-kv.d.ts +46 -0
  32. package/dist/auth/oauth-broker/stores/client-kv.js +182 -0
  33. package/dist/auth/oauth-broker/stores/firestore.d.ts +29 -0
  34. package/dist/auth/oauth-broker/stores/firestore.js +201 -0
  35. package/dist/auth/oauth-broker/stores/open-client-directory.d.ts +4 -0
  36. package/dist/auth/oauth-broker/stores/open-client-directory.js +30 -0
  37. package/dist/auth/oauth-broker/stores/open-refresh-store.d.ts +4 -0
  38. package/dist/auth/oauth-broker/stores/open-refresh-store.js +24 -0
  39. package/dist/auth/oauth-broker/stores/postgres.d.ts +13 -0
  40. package/dist/auth/oauth-broker/stores/postgres.js +193 -0
  41. package/dist/auth/oauth-broker/stores/redis.d.ts +25 -0
  42. package/dist/auth/oauth-broker/stores/redis.js +337 -0
  43. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +1 -1
  44. package/dist/config/env.d.ts +13 -0
  45. package/dist/config/env.js +14 -1
  46. package/dist/config/load-mcp-config.d.ts +20 -0
  47. package/dist/config/load-mcp-config.js +53 -1
  48. package/dist/config/load-mcp-config.test.js +53 -0
  49. package/dist/config/oauth-store-key.d.ts +2 -0
  50. package/dist/config/oauth-store-key.js +17 -0
  51. package/dist/policy/content-developer.d.ts +4 -1
  52. package/dist/policy/content-developer.js +7 -3
  53. package/dist/policy/preview-ledger.d.ts +11 -1
  54. package/dist/policy/preview-ledger.js +29 -3
  55. package/dist/policy/rename-rejected.d.ts +9 -0
  56. package/dist/policy/rename-rejected.js +15 -0
  57. package/dist/profiles/content-developer/v1/index.js +6 -0
  58. package/dist/profiles/content-developer/v1/prompt-specs.d.ts +1 -1
  59. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +15 -0
  60. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-stale.md +1 -0
  61. package/dist/profiles/content-reader/v1/prompt-specs.d.ts +1 -1
  62. package/dist/profiles/semantic-layer/v1/prompts.js +3 -3
  63. package/dist/profiles/semantic-layer/v1/resources/playbooks/compose-compile.md +6 -3
  64. package/dist/profiles/semantic-layer/v1/resources/playbooks/core.md +1 -1
  65. package/dist/server/capabilities.d.ts +1 -1
  66. package/dist/stdio.process.test.js +3 -1
  67. package/dist/tools/project/content.js +8 -1
  68. package/dist/tools/project/developer-content.js +1 -1
  69. package/dist/tools/project/developer-helpers.d.ts +1 -0
  70. package/dist/tools/project/developer-helpers.test.js +1 -0
  71. package/dist/tools/project/developer-rename.d.ts +13 -0
  72. package/dist/tools/project/developer-rename.js +319 -0
  73. package/dist/tools/project/developer-rename.test.d.ts +5 -0
  74. package/dist/tools/project/developer-rename.test.js +296 -0
  75. package/dist/tools/project/reader-content.js +10 -3
  76. package/dist/tools/project/rename-instruction.d.ts +58 -0
  77. package/dist/tools/project/rename-instruction.js +104 -0
  78. package/dist/tools/query/reader-tool-helpers.d.ts +1 -1
  79. package/dist/tools/query/reader-tool-helpers.js +4 -0
  80. package/dist/tools/registry.d.ts +1 -1
  81. package/dist/tools/semantic/explore-helpers.d.ts +6 -0
  82. package/dist/tools/semantic/explore-helpers.js +43 -0
  83. package/dist/tools/semantic/explore-helpers.test.js +17 -0
  84. package/dist/tools/semantic/query.js +9 -19
  85. package/dist/tools/semantic/query.test.js +71 -0
  86. package/dist/transports/streamable-http.js +33 -7
  87. package/package.json +13 -9
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Rename instructions bound by content-developer preview tokens (ADR-0036).
3
+ * The server rewrites chart references. This module only checks the instruction
4
+ * before a token is minted or a rename is posted.
5
+ */
6
+ import { RenameRejectedError } from '../../policy/rename-rejected.js';
7
+ import type { RenameImpactBaseline } from '../../policy/preview-ledger.js';
8
+ import type { components } from '@lightdash-tools/common';
9
+ export { RenameRejectedError };
10
+ export type RenameKind = 'field' | 'model';
11
+ export type ChartRenameInstruction = {
12
+ scope: 'chart';
13
+ chartUuid: string;
14
+ type: RenameKind;
15
+ from: string;
16
+ to: string;
17
+ };
18
+ export type DashboardFilterRenameInstruction = {
19
+ scope: 'dashboard-filter';
20
+ dashboardUuid: string;
21
+ type: RenameKind;
22
+ from: string;
23
+ to: string;
24
+ };
25
+ export type ProjectRenameInstruction = {
26
+ scope: 'project';
27
+ type: RenameKind;
28
+ from: string;
29
+ to: string;
30
+ model: string | null;
31
+ };
32
+ export type RenameInstruction = ChartRenameInstruction | DashboardFilterRenameInstruction | ProjectRenameInstruction;
33
+ type RenameChangeList = components['schemas']['ApiRenameResponse']['results'];
34
+ /**
35
+ * Upstream chart rename compiles `from` into a regular expression.
36
+ * Names stay on the identifier alphabet the CLI already allows, plus digits.
37
+ */
38
+ export declare function assertRenameToken(value: string, label: string): void;
39
+ /** Reject a no-op rename before a preview token is minted. */
40
+ export declare function assertRenameNamesDiffer(from: string, to: string): void;
41
+ /**
42
+ * The replacement must be an id the field dropdown returned.
43
+ * Joined tables are included. The missing id (`from`) often is not.
44
+ */
45
+ export declare function assertListedFieldId(fields: Readonly<Record<string, readonly string[]>>, to: string): void;
46
+ /** Apply tools write. A dry run belongs on preview_rename. */
47
+ export declare function assertApplyIsNotDryRun(dryRun: boolean | undefined): void;
48
+ export declare function projectRenameResourceKey(instruction: Pick<ProjectRenameInstruction, 'from' | 'model' | 'to' | 'type'>): string;
49
+ /**
50
+ * `POST /rename/preview` with a model treats `from` and `to` as full field ids.
51
+ * `POST /rename` looks the field up by short name on that explore's base table.
52
+ * The job body is the short name. The preview body keeps the full id.
53
+ */
54
+ export declare function projectFieldShortName(model: string, fieldId: string): string;
55
+ export declare function projectRenameJobBody(instruction: ProjectRenameInstruction): components['schemas']['ApiRenameBody'];
56
+ export declare function projectRenameBody(instruction: ProjectRenameInstruction, dryRun?: boolean): components['schemas']['ApiRenameBody'];
57
+ /** Stable uuid lists stored on the project rename baseline. */
58
+ export declare function renameImpactFromChanges(results: RenameChangeList): RenameImpactBaseline;
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ /**
3
+ * Rename instructions bound by content-developer preview tokens (ADR-0036).
4
+ * The server rewrites chart references. This module only checks the instruction
5
+ * before a token is minted or a rename is posted.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.RenameRejectedError = void 0;
9
+ exports.assertRenameToken = assertRenameToken;
10
+ exports.assertRenameNamesDiffer = assertRenameNamesDiffer;
11
+ exports.assertListedFieldId = assertListedFieldId;
12
+ exports.assertApplyIsNotDryRun = assertApplyIsNotDryRun;
13
+ exports.projectRenameResourceKey = projectRenameResourceKey;
14
+ exports.projectFieldShortName = projectFieldShortName;
15
+ exports.projectRenameJobBody = projectRenameJobBody;
16
+ exports.projectRenameBody = projectRenameBody;
17
+ exports.renameImpactFromChanges = renameImpactFromChanges;
18
+ const rename_rejected_js_1 = require("../../policy/rename-rejected.js");
19
+ Object.defineProperty(exports, "RenameRejectedError", { enumerable: true, get: function () { return rename_rejected_js_1.RenameRejectedError; } });
20
+ const RENAME_NAME = /^[a-z0-9_]+$/;
21
+ /**
22
+ * Upstream chart rename compiles `from` into a regular expression.
23
+ * Names stay on the identifier alphabet the CLI already allows, plus digits.
24
+ */
25
+ function assertRenameToken(value, label) {
26
+ if (!RENAME_NAME.test(value)) {
27
+ throw new rename_rejected_js_1.RenameRejectedError('RENAME_TARGET', `${label} must contain only lowercase letters, digits, and underscores`);
28
+ }
29
+ }
30
+ /** Reject a no-op rename before a preview token is minted. */
31
+ function assertRenameNamesDiffer(from, to) {
32
+ assertRenameToken(from, 'from');
33
+ assertRenameToken(to, 'to');
34
+ if (from === to) {
35
+ throw new rename_rejected_js_1.RenameRejectedError('RENAME_UNCHANGED', 'from and to are the same, so there is nothing to rename');
36
+ }
37
+ }
38
+ /**
39
+ * The replacement must be an id the field dropdown returned.
40
+ * Joined tables are included. The missing id (`from`) often is not.
41
+ */
42
+ function assertListedFieldId(fields, to) {
43
+ const listed = Object.values(fields).some((ids) => ids.includes(to));
44
+ if (!listed) {
45
+ throw new rename_rejected_js_1.RenameRejectedError('RENAME_FIELD_UNLISTED', 'The new field id must be one returned by list_rename_fields');
46
+ }
47
+ }
48
+ /** Apply tools write. A dry run belongs on preview_rename. */
49
+ function assertApplyIsNotDryRun(dryRun) {
50
+ if (dryRun === true) {
51
+ throw new rename_rejected_js_1.RenameRejectedError('RENAME_DRY_RUN', 'dryRun does not apply a rename. Call preview_rename.');
52
+ }
53
+ }
54
+ function projectRenameResourceKey(instruction) {
55
+ var _a;
56
+ return `project:${instruction.type}:${(_a = instruction.model) !== null && _a !== void 0 ? _a : ''}:${instruction.from}:${instruction.to}`;
57
+ }
58
+ /**
59
+ * `POST /rename/preview` with a model treats `from` and `to` as full field ids.
60
+ * `POST /rename` looks the field up by short name on that explore's base table.
61
+ * The job body is the short name. The preview body keeps the full id.
62
+ */
63
+ function projectFieldShortName(model, fieldId) {
64
+ const prefix = `${model}_`;
65
+ if (!fieldId.startsWith(prefix) || fieldId.length === prefix.length) {
66
+ throw new rename_rejected_js_1.RenameRejectedError('RENAME_TARGET', `A project field id must start with "${prefix}"`);
67
+ }
68
+ const shortName = fieldId.slice(prefix.length);
69
+ assertRenameToken(shortName, 'field name');
70
+ return shortName;
71
+ }
72
+ function projectRenameJobBody(instruction) {
73
+ if (instruction.type === 'model') {
74
+ return Object.assign({ type: instruction.type, from: instruction.from, to: instruction.to }, (instruction.model == null ? {} : { model: instruction.model }));
75
+ }
76
+ if (instruction.type === 'field') {
77
+ if (instruction.model == null) {
78
+ throw new rename_rejected_js_1.RenameRejectedError('RENAME_TARGET', 'A project field rename needs model set to the explore name, plus full field ids');
79
+ }
80
+ return {
81
+ type: 'field',
82
+ model: instruction.model,
83
+ from: projectFieldShortName(instruction.model, instruction.from),
84
+ to: projectFieldShortName(instruction.model, instruction.to),
85
+ };
86
+ }
87
+ const unhandled = instruction.type;
88
+ throw new rename_rejected_js_1.RenameRejectedError('RENAME_TARGET', `Unknown rename type '${String(unhandled)}'`);
89
+ }
90
+ function projectRenameBody(instruction, dryRun) {
91
+ return Object.assign(Object.assign({ type: instruction.type, from: instruction.from, to: instruction.to }, (instruction.model == null ? {} : { model: instruction.model })), (dryRun === undefined ? {} : { dryRun }));
92
+ }
93
+ function sortedUuids(items) {
94
+ return items.map((item) => item.uuid).sort();
95
+ }
96
+ /** Stable uuid lists stored on the project rename baseline. */
97
+ function renameImpactFromChanges(results) {
98
+ return {
99
+ alerts: sortedUuids(results.alerts),
100
+ charts: sortedUuids(results.charts),
101
+ dashboardSchedulers: sortedUuids(results.dashboardSchedulers),
102
+ dashboards: sortedUuids(results.dashboards),
103
+ };
104
+ }
@@ -2,9 +2,9 @@
2
2
  * Shared error/warning helpers for pin-scoped and bounded-query MCP tools
3
3
  * (content-reader, content-developer, data-analyst, semantic discovery).
4
4
  */
5
- import type { NormalizedQueryResult } from './result-normalizer.js';
6
5
  import type { ContentReaderWarning } from '../../policy/envelope.js';
7
6
  import type { TextContent, ToolErrorExtras } from '../shared.js';
7
+ import type { NormalizedQueryResult } from './result-normalizer.js';
8
8
  export declare function codedErrorResult(code: string, message: string, extras?: ToolErrorExtras): TextContent;
9
9
  /** Map ProjectScopeError to a tool error result; rethrow anything else. */
10
10
  export declare function projectScopeErrorResult(err: unknown): TextContent;
@@ -31,6 +31,10 @@ const BLOCKED_POLICY_CODES = new Set([
31
31
  'PREVIEW_NOT_VALIDATED',
32
32
  'PREVIEW_NOT_OWNED',
33
33
  'CHART_SLUG_EXISTS',
34
+ 'RENAME_DRY_RUN',
35
+ 'RENAME_FIELD_UNLISTED',
36
+ 'RENAME_TARGET',
37
+ 'RENAME_UNCHANGED',
34
38
  ]);
35
39
  function codedErrorResult(code, message, extras) {
36
40
  const result = (0, shared_js_1.toolErrorResult)(code, message, extras);
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Register profile-mounted ToolModules (orchestration only).
3
3
  */
4
- import type { ToolModule } from './types.js';
5
4
  import type { McpContextProvider } from '../server/request-context.js';
5
+ import type { ToolModule } from './types.js';
6
6
  import type { McpServer } from '@modelcontextprotocol/server';
7
7
  export type { ToolModule } from './types.js';
8
8
  /** Register profile-mounted tool modules (deterministic order = array order). */
@@ -57,6 +57,10 @@ export declare function summarizeDimensions(dimensions: readonly DimensionLike[]
57
57
  }): DimensionSummary[];
58
58
  /** True when compiled SQL has an empty projection (SELECT … FROM with no columns). */
59
59
  export declare function isEmptySelectSql(sql: string): boolean;
60
+ /** Body of the first Lightdash ERROR block comment (`ERROR:…`), if present. */
61
+ export declare function extractCompileSqlErrorComment(sql: string): string | undefined;
62
+ /** True when Lightdash embedded a compile failure comment (e.g. unknown filter fieldId). */
63
+ export declare function hasCompileSqlErrorComment(sql: string): boolean;
60
64
  /**
61
65
  * Collect SELECT aliases from compiled SQL (`AS \`alias\``, `AS "alias"`, or `AS alias`).
62
66
  * Heuristic only (not a SQL parser): stops at the first FROM; CAST(... AS type) may
@@ -72,6 +76,8 @@ export declare function extractSelectAliases(sql: string): string[];
72
76
  export declare function findMissingFieldIds(requested: readonly string[], sql: string): string[];
73
77
  /** Collect string fieldIds from metricQuery.dimensions and metricQuery.metrics. */
74
78
  export declare function collectRequestedFieldIds(metricQuery: Record<string, unknown>): string[];
79
+ /** Diagnose post-compile SQL for agents. Returns error text, or undefined when OK. */
80
+ export declare function diagnoseCompiledSql(sql: string | undefined, requestedFieldIds: readonly string[]): string | undefined;
75
81
  /** Extract SQL text from a compile_query API payload. */
76
82
  export declare function extractCompiledSql(result: unknown): string | undefined;
77
83
  export {};
@@ -9,9 +9,12 @@ exports.flattenExploreDimensions = flattenExploreDimensions;
9
9
  exports.toFieldId = toFieldId;
10
10
  exports.summarizeDimensions = summarizeDimensions;
11
11
  exports.isEmptySelectSql = isEmptySelectSql;
12
+ exports.extractCompileSqlErrorComment = extractCompileSqlErrorComment;
13
+ exports.hasCompileSqlErrorComment = hasCompileSqlErrorComment;
12
14
  exports.extractSelectAliases = extractSelectAliases;
13
15
  exports.findMissingFieldIds = findMissingFieldIds;
14
16
  exports.collectRequestedFieldIds = collectRequestedFieldIds;
17
+ exports.diagnoseCompiledSql = diagnoseCompiledSql;
15
18
  exports.extractCompiledSql = extractCompiledSql;
16
19
  /** Map a summary explore to a compact MCP payload (drops fat explore fields). */
17
20
  function toExploreSummary(explore) {
@@ -112,6 +115,17 @@ function isEmptySelectSql(sql) {
112
115
  const normalized = sql.replace(/\s+/g, ' ').trim();
113
116
  return /SELECT FROM\b/i.test(normalized);
114
117
  }
118
+ /** Body of the first Lightdash ERROR block comment (`ERROR:…`), if present. */
119
+ function extractCompileSqlErrorComment(sql) {
120
+ var _a;
121
+ const match = /\/\*\s*(ERROR:[\s\S]*?)\*\//i.exec(sql);
122
+ const body = (_a = match === null || match === void 0 ? void 0 : match[1]) === null || _a === void 0 ? void 0 : _a.trim();
123
+ return body && body.length > 0 ? body : undefined;
124
+ }
125
+ /** True when Lightdash embedded a compile failure comment (e.g. unknown filter fieldId). */
126
+ function hasCompileSqlErrorComment(sql) {
127
+ return extractCompileSqlErrorComment(sql) !== undefined;
128
+ }
115
129
  /**
116
130
  * Collect SELECT aliases from compiled SQL (`AS \`alias\``, `AS "alias"`, or `AS alias`).
117
131
  * Heuristic only (not a SQL parser): stops at the first FROM; CAST(... AS type) may
@@ -167,6 +181,35 @@ function collectRequestedFieldIds(metricQuery) {
167
181
  }
168
182
  return requested;
169
183
  }
184
+ const COMPILED_SQL_FIELD_ID_HINT = 'Copy fieldIds from list_dimensions (STRUCT name dots → `__`; ARRAY via join tables with ' +
185
+ 'baseTableOnly=false) and explore-local metrics; re-compile.';
186
+ /** Diagnose post-compile SQL for agents. Returns error text, or undefined when OK. */
187
+ function diagnoseCompiledSql(sql, requestedFieldIds) {
188
+ if (!sql)
189
+ return undefined;
190
+ if (isEmptySelectSql(sql)) {
191
+ return ('Error: compile_query produced an empty SELECT (no columns). ' +
192
+ 'Use fieldId values like `{table}_{name}` from list_dimensions (base table; nested dots → `__`), ' +
193
+ 'not short field names. Re-compile after fixing metricQuery.');
194
+ }
195
+ const errorComment = extractCompileSqlErrorComment(sql);
196
+ if (errorComment) {
197
+ return ('Error: compile_query SQL contains a Lightdash `/* ERROR:` comment ' +
198
+ '(often an unknown filter fieldId). ' +
199
+ COMPILED_SQL_FIELD_ID_HINT +
200
+ '\nLightdash: /* ' +
201
+ errorComment +
202
+ ' */');
203
+ }
204
+ const missing = findMissingFieldIds(requestedFieldIds, sql);
205
+ if (missing.length > 0) {
206
+ return ('Error: compile_query SQL is missing SELECT aliases for requested fieldIds: ' +
207
+ missing.join(', ') +
208
+ '. ' +
209
+ COMPILED_SQL_FIELD_ID_HINT);
210
+ }
211
+ return undefined;
212
+ }
170
213
  /** Extract SQL text from a compile_query API payload. */
171
214
  function extractCompiledSql(result) {
172
215
  if (typeof result === 'string')
@@ -202,6 +202,23 @@ const explore_helpers_js_1 = require("./explore-helpers.js");
202
202
  (0, vitest_1.expect)((0, explore_helpers_js_1.extractCompiledSql)('raw')).toBe('raw');
203
203
  });
204
204
  });
205
+ (0, vitest_1.describe)('hasCompileSqlErrorComment / extractCompileSqlErrorComment', () => {
206
+ (0, vitest_1.it)('detects Lightdash unknown-dimension ERROR comments in compiled SQL', () => {
207
+ const sql = `SELECT
208
+ \`orders_nested_demo\`.status AS \`orders_nested_demo_status\`
209
+ FROM orders
210
+ WHERE ((
211
+ /* ERROR: Filter has a reference to an unknown dimension: orders_nested_demo_customer.first_name */ orders_nested_demo_customer.first_name equals ("Anna")
212
+ ))
213
+ GROUP BY 1`;
214
+ (0, vitest_1.expect)((0, explore_helpers_js_1.hasCompileSqlErrorComment)(sql)).toBe(true);
215
+ (0, vitest_1.expect)((0, explore_helpers_js_1.extractCompileSqlErrorComment)(sql)).toContain('unknown dimension: orders_nested_demo_customer.first_name');
216
+ (0, vitest_1.expect)((0, explore_helpers_js_1.hasCompileSqlErrorComment)('SELECT 1 /* note */ FROM t')).toBe(false);
217
+ (0, vitest_1.expect)((0, explore_helpers_js_1.hasCompileSqlErrorComment)('SELECT 1 FROM t')).toBe(false);
218
+ (0, vitest_1.expect)((0, explore_helpers_js_1.hasCompileSqlErrorComment)('/*ERROR: bare */ SELECT 1')).toBe(true);
219
+ (0, vitest_1.expect)((0, explore_helpers_js_1.extractCompileSqlErrorComment)('/*ERROR: bare */ SELECT 1')).toBe('ERROR: bare');
220
+ });
221
+ });
205
222
  (0, vitest_1.describe)('extractSelectAliases / findMissingFieldIds', () => {
206
223
  const sampleSql = `
207
224
  SELECT
@@ -17,7 +17,7 @@ const schema_fields_js_2 = require("./schema-fields.js");
17
17
  function registerCompileQuery(server, contextProvider) {
18
18
  (0, shared_js_1.registerToolSafe)(server, 'compile_query', {
19
19
  title: 'Compile query',
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
+ description: 'Compile a metric query for an explore without executing it. Sets metricQuery.exploreName from exploreId (authoritative), defaults missing tableCalculations and sorts to [], and fills missing FilterGroup/FilterRule ids. Use fieldIds from list_dimensions (`{table}_{name}` with nested dots in name replaced by `__`). Empty SELECT, compiled SQL `/* ERROR:` comments (e.g. unknown filter fieldId), or requested dimensions/metrics missing from SELECT aliases return isError. projectUuid optional when X-Lightdash-Project is set.',
21
21
  inputSchema: {
22
22
  projectUuid: (0, schema_fields_js_1.optionalProjectUuidField)(),
23
23
  exploreId: (0, schema_fields_js_2.exploreIdField)(),
@@ -30,28 +30,18 @@ function registerCompileQuery(server, contextProvider) {
30
30
  var _a;
31
31
  try {
32
32
  const scope = (0, project_scope_js_1.resolveProjectScope)({ projectUuid });
33
- // Path exploreId is authoritative; OpenAPI MetricQuery requires exploreName + tableCalculations.
33
+ // Path exploreId is authoritative; OpenAPI MetricQuery requires exploreName + tableCalculations + sorts.
34
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)
35
35
  ? metricQuery.tableCalculations
36
- : [], exploreName: exploreId });
36
+ : [], sorts: Array.isArray(metricQuery.sorts) ? metricQuery.sorts : [], exploreName: exploreId });
37
37
  const result = await c.v1.query.compileQuery(scope.projectUuid, exploreId, body);
38
38
  const sql = (0, explore_helpers_js_1.extractCompiledSql)(result);
39
- const sqlError = (text) => ({
40
- content: [{ type: 'text', text }],
41
- isError: true,
42
- });
43
- if (sql && (0, explore_helpers_js_1.isEmptySelectSql)(sql)) {
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
- }
39
+ const diagnosis = (0, explore_helpers_js_1.diagnoseCompiledSql)(sql, (0, explore_helpers_js_1.collectRequestedFieldIds)(metricQuery));
40
+ if (diagnosis) {
41
+ return {
42
+ content: [{ type: 'text', text: diagnosis }],
43
+ isError: true,
44
+ };
55
45
  }
56
46
  return (0, shared_js_1.jsonToolResult)(result);
57
47
  }
@@ -88,6 +88,36 @@ function createCompileHandler(compileQuery) {
88
88
  (0, vitest_1.expect)(result.isError).toBe(true);
89
89
  (0, vitest_1.expect)(result.content[0].text).toContain('empty SELECT');
90
90
  });
91
+ (0, vitest_1.it)('returns isError when compiled SQL embeds an ERROR comment', async () => {
92
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
93
+ query: `SELECT
94
+ \`orders\`.status AS \`orders_status\`
95
+ FROM orders
96
+ WHERE ((
97
+ /* ERROR: Filter has a reference to an unknown dimension: orders_customer.first_name */ x
98
+ ))
99
+ GROUP BY 1`,
100
+ });
101
+ const { handler } = createCompileHandler(compileQuery);
102
+ const result = await handler({
103
+ projectUuid: PROJECT,
104
+ exploreId: 'orders',
105
+ metricQuery: {
106
+ dimensions: ['orders_status'],
107
+ metrics: [],
108
+ filters: {},
109
+ sorts: [],
110
+ limit: 50,
111
+ tableCalculations: [],
112
+ },
113
+ });
114
+ (0, vitest_1.expect)(result.isError).toBe(true);
115
+ (0, vitest_1.expect)(result.content[0].text).toContain('ERROR:');
116
+ (0, vitest_1.expect)(result.content[0].text).toContain('unknown filter fieldId');
117
+ (0, vitest_1.expect)(result.content[0].text).toContain('orders_customer.first_name');
118
+ (0, vitest_1.expect)(result.content[0].text).toContain('list_dimensions');
119
+ (0, vitest_1.expect)(result.content[0].text).not.toContain('${COMPILED_SQL_FIELD_ID_HINT}');
120
+ });
91
121
  (0, vitest_1.it)('defaults missing tableCalculations to []', async () => {
92
122
  const compileQuery = vitest_1.vi.fn().mockResolvedValue({
93
123
  query: 'SELECT `orders`.status AS `orders_status` FROM orders',
@@ -109,6 +139,47 @@ function createCompileHandler(compileQuery) {
109
139
  tableCalculations: [],
110
140
  }));
111
141
  });
142
+ (0, vitest_1.it)('defaults missing sorts to []', async () => {
143
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
144
+ query: 'SELECT `orders`.status AS `orders_status` FROM orders',
145
+ });
146
+ const { handler } = createCompileHandler(compileQuery);
147
+ await handler({
148
+ projectUuid: PROJECT,
149
+ exploreId: 'orders',
150
+ metricQuery: {
151
+ dimensions: ['orders_status'],
152
+ metrics: [],
153
+ filters: {},
154
+ limit: 50,
155
+ tableCalculations: [],
156
+ },
157
+ });
158
+ (0, vitest_1.expect)(compileQuery).toHaveBeenCalledWith(PROJECT, 'orders', vitest_1.expect.objectContaining({
159
+ exploreName: 'orders',
160
+ sorts: [],
161
+ }));
162
+ });
163
+ (0, vitest_1.it)('preserves explicit sorts', async () => {
164
+ const sorts = [{ fieldId: 'orders_status', descending: true }];
165
+ const compileQuery = vitest_1.vi.fn().mockResolvedValue({
166
+ query: 'SELECT `orders`.status AS `orders_status` FROM orders',
167
+ });
168
+ const { handler } = createCompileHandler(compileQuery);
169
+ await handler({
170
+ projectUuid: PROJECT,
171
+ exploreId: 'orders',
172
+ metricQuery: {
173
+ dimensions: ['orders_status'],
174
+ metrics: [],
175
+ filters: {},
176
+ sorts,
177
+ limit: 50,
178
+ tableCalculations: [],
179
+ },
180
+ });
181
+ (0, vitest_1.expect)(compileQuery).toHaveBeenCalledWith(PROJECT, 'orders', vitest_1.expect.objectContaining({ sorts }));
182
+ });
112
183
  (0, vitest_1.it)('preserves explicit tableCalculations', async () => {
113
184
  const tableCalculations = [
114
185
  { name: 'ratio', displayName: 'Ratio', sql: '${orders_sum_order_amount} / 100' },
@@ -9,7 +9,10 @@ const audit_js_1 = require("../audit/audit.js");
9
9
  const tool_audit_context_js_1 = require("../audit/tool-audit-context.js");
10
10
  const auth_mode_js_1 = require("../auth/auth-mode.js");
11
11
  const invoke_origins_js_1 = require("../auth/oauth-broker/invoke-origins.js");
12
+ const pending_store_js_1 = require("../auth/oauth-broker/pending-store.js");
12
13
  const routes_js_1 = require("../auth/oauth-broker/routes.js");
14
+ const open_client_directory_js_1 = require("../auth/oauth-broker/stores/open-client-directory.js");
15
+ const open_refresh_store_js_1 = require("../auth/oauth-broker/stores/open-refresh-store.js");
13
16
  const bearer_context_provider_js_1 = require("../auth/providers/bearer-context-provider.js");
14
17
  const env_context_provider_js_1 = require("../auth/providers/env-context-provider.js");
15
18
  const request_state_key_js_1 = require("../auth/request-state-key.js");
@@ -180,7 +183,7 @@ async function handleMcpPost(ctx) {
180
183
  }, () => (0, tool_audit_context_js_1.runWithToolAuditAuthAsync)(auditAuth, () => nodeHandler(req, res, body)));
181
184
  }
182
185
  async function createStreamableHttpServer(config) {
183
- var _a;
186
+ var _a, _b, _c;
184
187
  const inputConfig = config !== null && config !== void 0 ? config : (0, load_mcp_config_js_1.loadMcpHttpConfig)();
185
188
  (0, load_mcp_config_js_1.emitMcpHttpSecurityWarnings)(inputConfig);
186
189
  (0, runtime_js_1.warnIgnoredCliGuardrailEnvVars)();
@@ -191,6 +194,12 @@ async function createStreamableHttpServer(config) {
191
194
  (0, audit_js_1.initAuditLog)((0, runtime_js_1.getAuditLogPath)());
192
195
  let httpConfig = inputConfig;
193
196
  let oauthBroker;
197
+ const refreshStore = await (0, open_refresh_store_js_1.openRefreshStore)(inputConfig);
198
+ const clientDirectory = await (0, open_client_directory_js_1.openClientDirectory)(inputConfig).catch(async (error) => {
199
+ var _a;
200
+ await ((_a = refreshStore === null || refreshStore === void 0 ? void 0 : refreshStore.close) === null || _a === void 0 ? void 0 : _a.call(refreshStore).catch(() => undefined));
201
+ throw error;
202
+ });
194
203
  const mcpHttpHandler = createProcessMcpHttpHandler();
195
204
  const mcpNodeHandler = (0, node_1.toNodeHandler)(mcpHttpHandler, { onerror: reportMcpHttpError });
196
205
  const server = (0, node_http_1.createServer)((req, res) => {
@@ -201,22 +210,30 @@ async function createStreamableHttpServer(config) {
201
210
  }
202
211
  });
203
212
  });
204
- await listen(server, inputConfig.port, inputConfig.host);
213
+ try {
214
+ await listen(server, inputConfig.port, inputConfig.host);
215
+ }
216
+ catch (error) {
217
+ await ((_a = refreshStore === null || refreshStore === void 0 ? void 0 : refreshStore.close) === null || _a === void 0 ? void 0 : _a.call(refreshStore).catch(() => undefined));
218
+ await ((_b = clientDirectory === null || clientDirectory === void 0 ? void 0 : clientDirectory.close) === null || _b === void 0 ? void 0 : _b.call(clientDirectory).catch(() => undefined));
219
+ throw error;
220
+ }
205
221
  const address = server.address();
206
222
  const port = typeof address === 'object' && address !== null ? address.port : inputConfig.port;
207
223
  httpConfig = resolveHttpConfig(inputConfig, port);
208
- const baseUrl = (_a = httpConfig.publicUrl) !== null && _a !== void 0 ? _a : `http://${resolveListenHost(httpConfig.host)}:${port}`;
224
+ const baseUrl = (_c = httpConfig.publicUrl) !== null && _c !== void 0 ? _c : `http://${resolveListenHost(httpConfig.host)}:${port}`;
209
225
  if (httpConfig.authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH) {
210
- oauthBroker = (0, routes_js_1.createOAuthBroker)(httpConfig);
226
+ const brokerStore = clientDirectory
227
+ ? new pending_store_js_1.InMemoryOAuthBrokerStore({ clientDirectory })
228
+ : undefined;
229
+ oauthBroker = (0, routes_js_1.createOAuthBroker)(httpConfig, brokerStore, refreshStore);
211
230
  }
212
231
  return {
213
232
  port,
214
233
  baseUrl,
215
234
  config: httpConfig,
216
235
  close: async () => {
217
- await mcpHttpHandler.close().catch((err) => {
218
- reportMcpHttpError(err);
219
- });
236
+ var _a, _b;
220
237
  await new Promise((resolve, reject) => {
221
238
  server.close((err) => {
222
239
  if (err)
@@ -225,6 +242,15 @@ async function createStreamableHttpServer(config) {
225
242
  resolve();
226
243
  });
227
244
  });
245
+ await mcpHttpHandler.close().catch((err) => {
246
+ reportMcpHttpError(err);
247
+ });
248
+ await ((_a = refreshStore === null || refreshStore === void 0 ? void 0 : refreshStore.close) === null || _a === void 0 ? void 0 : _a.call(refreshStore).catch((err) => {
249
+ reportMcpHttpError(err);
250
+ }));
251
+ await ((_b = clientDirectory === null || clientDirectory === void 0 ? void 0 : clientDirectory.close) === null || _b === void 0 ? void 0 : _b.call(clientDirectory).catch((err) => {
252
+ reportMcpHttpError(err);
253
+ }));
228
254
  },
229
255
  };
230
256
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightdash-tools/mcp",
3
- "version": "0.23.0",
3
+ "version": "0.25.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": {
@@ -19,17 +19,21 @@
19
19
  "dist"
20
20
  ],
21
21
  "dependencies": {
22
- "@modelcontextprotocol/node": "2.0.0",
23
- "@modelcontextprotocol/server": "2.0.0",
22
+ "@google-cloud/firestore": "^9.4.1",
23
+ "@modelcontextprotocol/node": "2.1.2",
24
+ "@modelcontextprotocol/server": "2.4.0",
24
25
  "commander": "^15.0.0",
25
- "hono": "^4.13.0",
26
- "zod": "^4.4.3",
27
- "@lightdash-tools/client": "0.23.0",
28
- "@lightdash-tools/common": "0.23.0"
26
+ "ioredis": "^6.1.0",
27
+ "pg": "^8.23.1",
28
+ "zod": "4.6.7",
29
+ "@lightdash-tools/client": "0.25.0",
30
+ "@lightdash-tools/common": "0.25.0"
29
31
  },
30
32
  "devDependencies": {
31
- "@modelcontextprotocol/client": "2.0.0",
32
- "@types/node": "^25.9.3"
33
+ "@electric-sql/pglite": "^0.6.0",
34
+ "@modelcontextprotocol/client": "2.4.0",
35
+ "@types/node": "^25.9.3",
36
+ "@types/pg": "^8.23.1"
33
37
  },
34
38
  "publishConfig": {
35
39
  "access": "public"