@lightdash-tools/mcp 0.13.0 → 0.13.2

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 (27) hide show
  1. package/README.md +35 -7
  2. package/dist/config/load-mcp-config.js +16 -22
  3. package/dist/config/obsolete-env.js +2 -8
  4. package/dist/config/read-env.d.ts +4 -0
  5. package/dist/config/read-env.js +13 -0
  6. package/dist/notifications/operation-reporter.d.ts +13 -0
  7. package/dist/notifications/operation-reporter.js +45 -0
  8. package/dist/notifications/operation-reporter.test.d.ts +1 -0
  9. package/dist/notifications/operation-reporter.test.js +79 -0
  10. package/dist/profiles/content-developer/v1/prompts.js +3 -2
  11. package/dist/profiles/content-developer/v1/prompts.test.js +8 -0
  12. package/dist/profiles/content-developer/v1/resources/playbooks/chart-types.md +2 -0
  13. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +17 -16
  14. package/dist/profiles/content-developer/v1/resources/playbooks/dashboards.md +1 -1
  15. package/dist/profiles/content-developer/v1/resources/playbooks/index.md +8 -7
  16. package/dist/profiles/content-developer/v1/resources/playbooks/table-calculations.md +119 -0
  17. package/dist/profiles/content-developer/v1/resources/playbooks.d.ts +1 -1
  18. package/dist/profiles/content-developer/v1/resources/playbooks.js +7 -1
  19. package/dist/profiles/content-reader/v1/resources/playbooks/core.md +11 -11
  20. package/dist/profiles/content-reader/v1/resources/playbooks/explain-run.md +1 -1
  21. package/dist/tools/project/reader-content.d.ts +2 -0
  22. package/dist/tools/project/reader-content.js +33 -5
  23. package/dist/tools/project/reader-content.test.d.ts +4 -0
  24. package/dist/tools/project/reader-content.test.js +64 -0
  25. package/dist/tools/shared.d.ts +3 -0
  26. package/dist/tools/shared.js +4 -1
  27. package/package.json +3 -3
package/README.md CHANGED
@@ -79,17 +79,17 @@ Prefer `LIGHTDASH_TOOLS_*` env from the parent process. Avoid plaintext `.env` w
79
79
 
80
80
  ### Stdio
81
81
 
82
- | Required | Optional |
83
- | :----------------------------------- | :-------------------------------------------------------------------------------------------- |
84
- | `LIGHTDASH_URL`, `LIGHTDASH_API_KEY` | `LIGHTDASH_TOOLS_AUDIT_LOG` (file; else stderr JSON), `LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS` |
82
+ | Required | Optional |
83
+ | :----------------------------------- | :------------------------------------------------------------------------------------------------------------------ |
84
+ | `LIGHTDASH_URL`, `LIGHTDASH_API_KEY` | `LIGHTDASH_TOOLS_AUDIT_LOG` (file; else stderr JSON), [`LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS`](#project-allowlist) |
85
85
 
86
86
  Do **not** set OAuth client secrets for stdio. MCP ignores CLI `SAFETY_MODE` / `DRY_RUN`.
87
87
 
88
88
  ### HTTP OAuth (primary)
89
89
 
90
- | Required | Common optional |
91
- | :-------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------- |
92
- | `LIGHTDASH_URL`, `LIGHTDASH_TOOLS_MCP_PUBLIC_URL`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_ID`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET` | port, `ALLOWED_ORIGINS`, `ALLOWED_PROJECT_UUIDS`, token cache TTL |
90
+ | Required | Common optional |
91
+ | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ |
92
+ | `LIGHTDASH_URL`, `LIGHTDASH_TOOLS_MCP_PUBLIC_URL`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_ID`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET` | port, `ALLOWED_ORIGINS`, [`LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS`](#project-allowlist), token cache TTL |
93
93
 
94
94
  On Cloud Run / hosted HTTP, leave `LIGHTDASH_TOOLS_AUDIT_LOG` unset — tool audits are stderr JSON (`channel: "audit"`) → Cloud Logging. See [cloud-run.md](../../docs/operators/cloud-run.md).
95
95
 
@@ -110,6 +110,34 @@ Governance soft-delete needs client form elicitation; missing capability → `EL
110
110
  | Shared-key | `LIGHTDASH_API_KEY` + `LIGHTDASH_TOOLS_MCP_SHARED_KEY` |
111
111
  | Local none | `NODE_ENV=development` (not `production`) |
112
112
 
113
+ ### Project allowlist
114
+
115
+ Optional deployment ceiling shared with the CLI. Unset or empty → unrestricted beyond RBAC, HTTP pin, and tool `projectUuid`. Non-empty → hard allowlist for all profiles.
116
+
117
+ **Format**
118
+
119
+ - Comma-separated Lightdash project UUIDs (RFC 4122)
120
+ - Whitespace around commas is ignored
121
+ - No empty segments (double commas are rejected)
122
+ - Invalid UUIDs fail at process startup
123
+ - Input is case-insensitive; values are normalized to lowercase
124
+
125
+ ```bash
126
+ # Single project
127
+ export LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS="aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
128
+
129
+ # Multiple (spaces optional)
130
+ export LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS="aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa, bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
131
+ ```
132
+
133
+ **Semantics**
134
+
135
+ - Ceiling only — not a default project; tools still need `projectUuid` or an HTTP `X-Lightdash-Project` pin
136
+ - When restricted, HTTP pin and every tool `projectUuid` must be in the set
137
+ - `list_projects` returns only allowlisted projects; cross-project promote requires upstream targets in the set
138
+
139
+ Architecture: [ADR-0008](../../docs/adr/0008-mcp-request-scope-and-hardening.md).
140
+
113
141
  Obsolete vars (`AUTH_MODE`, `EXPERIMENTAL_*`, `DANGEROUSLY_*`, `INSECURE_DEV`, `MCP_STORE`, `MCP_REDIS_URL`, free-form `MCP_PATH`) are **rejected**. See [ADR-0019](../../docs/adr/0019-mcp-stateless-protocol-core-without-redis-ephemeral-store.md).
114
142
 
115
143
  ## Profiles at a glance
@@ -147,7 +175,7 @@ Unsaved Explore-style metric queries (`run_metric_query`) with explore discovery
147
175
  - **Off MCP:** irrecoverable admin deletes, permanent content purge, broad org mutations — use `@lightdash-tools/client` or the CLI ([ADR-0004](../../docs/adr/0004-agent-safe-exposure-mcp-cli-vs-client-only.md)).
148
176
  - **Writes:** only on `content-developer` (preview gate). Soft-delete / promote: only on `content-governance` (form elicitation).
149
177
  - **Redaction:** emails masked unless `includeEmail=true`; scheduler destinations redacted unless `revealDestinations=true`; warehouse/dbt connection secrets never on MCP ([ADR-0011](../../docs/adr/0011-mcp-tool-response-sensitivity-classes.md)).
150
- - **Project scope:** optional HTTP pin `X-Lightdash-Project`, else tool `projectUuid`; optional ceiling `LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS`.
178
+ - **Project scope:** optional HTTP pin `X-Lightdash-Project`, else tool `projectUuid`; optional ceiling [`LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS`](#project-allowlist).
151
179
 
152
180
  Profile tool allowlists are the capability surface — not CLI safety-mode.
153
181
 
@@ -11,6 +11,7 @@ const env_js_1 = require("./env.js");
11
11
  const normalize_url_js_1 = require("./normalize-url.js");
12
12
  const obsolete_env_js_1 = require("./obsolete-env.js");
13
13
  const public_url_js_1 = require("./public-url.js");
14
+ const read_env_js_1 = require("./read-env.js");
14
15
  const DEFAULT_SCOPES_SUPPORTED = ['read', 'write', 'mcp:read', 'mcp:write'];
15
16
  const warnedAliases = new Set();
16
17
  function warnDeprecatedAlias(oldName, newName) {
@@ -19,13 +20,6 @@ function warnDeprecatedAlias(oldName, newName) {
19
20
  warnedAliases.add(oldName);
20
21
  console.warn(`Warning: ${oldName} is deprecated. Use ${newName}.`);
21
22
  }
22
- function readEnv(name, env) {
23
- // eslint-disable-next-line security/detect-object-injection -- env var names are fixed constants in this module
24
- const value = env[name];
25
- if (value === undefined || value === '')
26
- return undefined;
27
- return value;
28
- }
29
23
  function parsePositiveIntegerEnv(name, value) {
30
24
  const parsed = Number(value);
31
25
  if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 0) {
@@ -36,19 +30,19 @@ function parsePositiveIntegerEnv(name, value) {
36
30
  function readNumberEnv(env, primary, aliases, defaultValue,
37
31
  /** Silent fallback (e.g. Cloud Run `PORT`); read only when primary/aliases unset. */
38
32
  silentFallback) {
39
- const primaryValue = readEnv(primary, env);
33
+ const primaryValue = (0, read_env_js_1.readEnv)(primary, env);
40
34
  if (primaryValue !== undefined) {
41
35
  return parsePositiveIntegerEnv(primary, primaryValue);
42
36
  }
43
37
  for (const alias of aliases) {
44
- const aliasValue = readEnv(alias.name, env);
38
+ const aliasValue = (0, read_env_js_1.readEnv)(alias.name, env);
45
39
  if (aliasValue !== undefined) {
46
40
  warnDeprecatedAlias(alias.name, alias.newName);
47
41
  return parsePositiveIntegerEnv(alias.name, aliasValue);
48
42
  }
49
43
  }
50
44
  if (silentFallback !== undefined) {
51
- const fallbackValue = readEnv(silentFallback, env);
45
+ const fallbackValue = (0, read_env_js_1.readEnv)(silentFallback, env);
52
46
  if (fallbackValue !== undefined) {
53
47
  return parsePositiveIntegerEnv(silentFallback, fallbackValue);
54
48
  }
@@ -56,11 +50,11 @@ silentFallback) {
56
50
  return defaultValue;
57
51
  }
58
52
  function readStringEnv(env, primary, aliases) {
59
- const primaryValue = readEnv(primary, env);
53
+ const primaryValue = (0, read_env_js_1.readEnv)(primary, env);
60
54
  if (primaryValue !== undefined)
61
55
  return primaryValue;
62
56
  for (const alias of aliases) {
63
- const aliasValue = readEnv(alias.name, env);
57
+ const aliasValue = (0, read_env_js_1.readEnv)(alias.name, env);
64
58
  if (aliasValue !== undefined) {
65
59
  warnDeprecatedAlias(alias.name, alias.newName);
66
60
  return aliasValue;
@@ -101,7 +95,7 @@ function inferAuthMode(params) {
101
95
  if (sharedKeyRaw) {
102
96
  return auth_mode_js_1.MCP_AUTH_MODE_SHARED_KEY;
103
97
  }
104
- const legacyEnabled = readEnv(env_js_1.ENV_MCP_AUTH_ENABLED, env);
98
+ const legacyEnabled = (0, read_env_js_1.readEnv)(env_js_1.ENV_MCP_AUTH_ENABLED, env);
105
99
  if (legacyEnabled === '1' || legacyEnabled === 'true' || legacyEnabled === 'yes') {
106
100
  warnDeprecatedAlias(env_js_1.ENV_MCP_AUTH_ENABLED, `${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_SHARED_KEY} (+ LIGHTDASH_API_KEY)`);
107
101
  return auth_mode_js_1.MCP_AUTH_MODE_SHARED_KEY;
@@ -186,12 +180,12 @@ function emitMcpHttpSecurityWarnings(config) {
186
180
  emitCorsSecurityWarnings(config);
187
181
  }
188
182
  function readScopeList(env, primary, fallback) {
189
- const parsed = parseCsv(readEnv(primary, env));
183
+ const parsed = parseCsv((0, read_env_js_1.readEnv)(primary, env));
190
184
  return parsed.length > 0 ? parsed : fallback;
191
185
  }
192
186
  function readHttpAuthInputs(env) {
193
- const oauthClientId = readEnv(env_js_1.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_ID, env);
194
- const oauthClientSecretRaw = readEnv(env_js_1.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET, env);
187
+ const oauthClientId = (0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_ID, env);
188
+ const oauthClientSecretRaw = (0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET, env);
195
189
  const publicUrlRaw = readStringEnv(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL, [
196
190
  { name: env_js_1.ENV_MCP_PUBLIC_URL, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL },
197
191
  ]);
@@ -223,11 +217,11 @@ function resolveOAuthCredentials(authMode, oauthClientId, oauthClientSecretRaw)
223
217
  }
224
218
  function loadMcpHttpConfig(env = process.env) {
225
219
  var _a;
226
- const lightdashUrlRaw = readEnv(client_1.ENV_LIGHTDASH_URL, env);
220
+ const lightdashUrlRaw = (0, read_env_js_1.readEnv)(client_1.ENV_LIGHTDASH_URL, env);
227
221
  if (!lightdashUrlRaw) {
228
222
  throw new Error(`${client_1.ENV_LIGHTDASH_URL} is required.`);
229
223
  }
230
- if (readEnv(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PATH, env) !== undefined) {
224
+ if ((0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PATH, env) !== undefined) {
231
225
  throw new Error(`${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PATH} is unused and rejected. ` +
232
226
  `The MCP endpoint path is profile-owned (${(0, index_js_1.getDefaultProfile)().path}); leave this variable unset.`);
233
227
  }
@@ -241,16 +235,16 @@ function loadMcpHttpConfig(env = process.env) {
241
235
  { name: env_js_1.ENV_MCP_ALLOWED_ORIGINS, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_ALLOWED_ORIGINS },
242
236
  ]);
243
237
  const allowedOrigins = parseCsv(allowedOriginsRaw);
244
- const proxyAuth = readEnv(client_1.ENV_LIGHTDASH_PROXY_AUTHORIZATION, env);
238
+ const proxyAuth = (0, read_env_js_1.readEnv)(client_1.ENV_LIGHTDASH_PROXY_AUTHORIZATION, env);
245
239
  const mcpPath = (0, index_js_1.getDefaultProfile)().path;
246
240
  const publicUrl = publicUrlRaw ? (0, normalize_url_js_1.normalizePublicUrl)(publicUrlRaw, (0, index_js_1.listProfilePaths)()) : undefined;
247
241
  assertPublicUrlSecurity(authMode, publicUrl);
248
- const validateToken = parseBooleanEnv(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN, readEnv(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN, env), authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH);
242
+ const validateToken = parseBooleanEnv(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN, (0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN, env), authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH);
249
243
  assertValidateTokenPolicy(authMode, validateToken, env);
250
244
  const requiredScopes = readScopeList(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_REQUIRED_SCOPES, []);
251
- const scopesSupportedEnvSet = readEnv(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_SCOPES_SUPPORTED, env) !== undefined;
245
+ const scopesSupportedEnvSet = (0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_SCOPES_SUPPORTED, env) !== undefined;
252
246
  assertLightdashOAuthScopePolicy(authMode, requiredScopes, scopesSupportedEnvSet);
253
- return Object.assign(Object.assign({ lightdashUrl: (0, normalize_url_js_1.normalizeLightdashUrl)(lightdashUrlRaw), proxyAuthorization: proxyAuth ? new client_1.SecretString(proxyAuth) : undefined, host: (_a = readEnv(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST, env)) !== null && _a !== void 0 ? _a : '0.0.0.0', port: readNumberEnv(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT, [
247
+ return Object.assign(Object.assign({ lightdashUrl: (0, normalize_url_js_1.normalizeLightdashUrl)(lightdashUrlRaw), proxyAuthorization: proxyAuth ? new client_1.SecretString(proxyAuth) : undefined, host: (_a = (0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST, env)) !== null && _a !== void 0 ? _a : '0.0.0.0', port: readNumberEnv(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT, [
254
248
  { name: env_js_1.ENV_MCP_HTTP_PORT, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT },
255
249
  { name: env_js_1.ENV_MCP_SERVER_PORT, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT },
256
250
  ], 3100, env_js_1.ENV_PLATFORM_PORT), publicUrl,
@@ -5,6 +5,7 @@
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.assertObsoleteEnvRejected = assertObsoleteEnvRejected;
7
7
  const env_js_1 = require("./env.js");
8
+ const read_env_js_1 = require("./read-env.js");
8
9
  const OBSOLETE_ENV_VARS = [
9
10
  env_js_1.ENV_LIGHTDASH_TOOLS_MCP_AUTH_MODE,
10
11
  env_js_1.ENV_LIGHTDASH_TOOLS_MCP_EXPERIMENTAL_IDENTITY_OAUTH,
@@ -17,17 +18,10 @@ const OBSOLETE_ENV_VARS = [
17
18
  env_js_1.ENV_LIGHTDASH_TOOLS_MCP_STORE,
18
19
  env_js_1.ENV_LIGHTDASH_TOOLS_MCP_REDIS_URL,
19
20
  ];
20
- function readEnv(name, env) {
21
- // eslint-disable-next-line security/detect-object-injection -- env var names are fixed constants
22
- const value = env[name];
23
- if (value === undefined || value === '')
24
- return undefined;
25
- return value;
26
- }
27
21
  /** Fail closed when operators still set removed MCP env vars. */
28
22
  function assertObsoleteEnvRejected(env = process.env) {
29
23
  for (const name of OBSOLETE_ENV_VARS) {
30
- if (readEnv(name, env) !== undefined) {
24
+ if ((0, read_env_js_1.readEnv)(name, env) !== undefined) {
31
25
  if (name === env_js_1.ENV_LIGHTDASH_TOOLS_MCP_STORE || name === env_js_1.ENV_LIGHTDASH_TOOLS_MCP_REDIS_URL) {
32
26
  throw new Error(`${name} is removed (ADR-0019). ` +
33
27
  `MCP HTTP is now stateless (sessionless) and has no Redis ephemeral store. ` +
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Read a process env value, treating empty string as unset.
3
+ */
4
+ export declare function readEnv(name: string, env: NodeJS.ProcessEnv): string | undefined;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ /**
3
+ * Read a process env value, treating empty string as unset.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readEnv = readEnv;
7
+ function readEnv(name, env) {
8
+ // eslint-disable-next-line security/detect-object-injection -- env var names are fixed constants at call sites
9
+ const value = env[name];
10
+ if (value === undefined || value === '')
11
+ return undefined;
12
+ return value;
13
+ }
@@ -0,0 +1,13 @@
1
+ import type { ServerContext } from '@modelcontextprotocol/server';
2
+ export type OperationPhase = 'calling-service' | 'completed' | 'preparing' | 'processing-response' | 'waiting';
3
+ export type OperationPhaseEvent = {
4
+ phase: OperationPhase;
5
+ operation: string;
6
+ message: string;
7
+ completedUnits?: number;
8
+ totalUnits?: number;
9
+ };
10
+ export interface OperationReporter {
11
+ phase(event: OperationPhaseEvent): Promise<void>;
12
+ }
13
+ export declare function createOperationReporter(context: ServerContext | undefined): OperationReporter;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createOperationReporter = createOperationReporter;
4
+ class NoopOperationReporter {
5
+ async phase() {
6
+ // Intentionally empty when the client did not opt in to progress notifications.
7
+ }
8
+ }
9
+ class McpProgressOperationReporter {
10
+ constructor(token, notify) {
11
+ this.token = token;
12
+ this.notify = notify;
13
+ this.current = 0;
14
+ }
15
+ async phase(event) {
16
+ var _a;
17
+ const requestedProgress = (_a = event.completedUnits) !== null && _a !== void 0 ? _a : this.current + 1;
18
+ this.current = Math.max(this.current + 1, requestedProgress);
19
+ const params = {
20
+ progressToken: this.token,
21
+ progress: this.current,
22
+ message: event.message,
23
+ };
24
+ if (event.totalUnits !== undefined) {
25
+ params.total = event.totalUnits;
26
+ }
27
+ try {
28
+ await this.notify({ method: 'notifications/progress', params });
29
+ }
30
+ catch (_b) {
31
+ // Progress reporting is best-effort and must never fail the tool invocation.
32
+ }
33
+ }
34
+ }
35
+ function createOperationReporter(context) {
36
+ var _a;
37
+ const progressContext = context;
38
+ const mcpReq = progressContext === null || progressContext === void 0 ? void 0 : progressContext.mcpReq;
39
+ const token = (_a = mcpReq === null || mcpReq === void 0 ? void 0 : mcpReq._meta) === null || _a === void 0 ? void 0 : _a.progressToken;
40
+ const notify = mcpReq === null || mcpReq === void 0 ? void 0 : mcpReq.notify;
41
+ if (token === undefined || notify === undefined) {
42
+ return new NoopOperationReporter();
43
+ }
44
+ return new McpProgressOperationReporter(token, notify.bind(mcpReq));
45
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const operation_reporter_js_1 = require("./operation-reporter.js");
5
+ (0, vitest_1.describe)('createOperationReporter', () => {
6
+ (0, vitest_1.it)('is a no-op when the client did not provide a progress token', async () => {
7
+ const notify = vitest_1.vi.fn();
8
+ const reporter = (0, operation_reporter_js_1.createOperationReporter)({
9
+ mcpReq: { notify },
10
+ });
11
+ await reporter.phase({
12
+ phase: 'preparing',
13
+ operation: 'list explores',
14
+ message: 'Preparing to list explores',
15
+ });
16
+ (0, vitest_1.expect)(notify).not.toHaveBeenCalled();
17
+ });
18
+ (0, vitest_1.it)('is a no-op when notify is missing even if a progress token is present', async () => {
19
+ const reporter = (0, operation_reporter_js_1.createOperationReporter)({
20
+ mcpReq: { _meta: { progressToken: 'progress-1' } },
21
+ });
22
+ await (0, vitest_1.expect)(reporter.phase({
23
+ phase: 'preparing',
24
+ operation: 'list explores',
25
+ message: 'Preparing to list explores',
26
+ })).resolves.toBeUndefined();
27
+ });
28
+ (0, vitest_1.it)('sends monotonic progress notifications for a request-scoped token', async () => {
29
+ const notify = vitest_1.vi.fn().mockResolvedValue(undefined);
30
+ const reporter = (0, operation_reporter_js_1.createOperationReporter)({
31
+ mcpReq: { _meta: { progressToken: 'progress-1' }, notify },
32
+ });
33
+ await reporter.phase({
34
+ phase: 'preparing',
35
+ operation: 'list explores',
36
+ message: 'Preparing to list explores',
37
+ completedUnits: 1,
38
+ totalUnits: 4,
39
+ });
40
+ await reporter.phase({
41
+ phase: 'calling-service',
42
+ operation: 'list explores',
43
+ message: 'Loading explores from Lightdash',
44
+ completedUnits: 1,
45
+ totalUnits: 4,
46
+ });
47
+ (0, vitest_1.expect)(notify).toHaveBeenNthCalledWith(1, {
48
+ method: 'notifications/progress',
49
+ params: {
50
+ progressToken: 'progress-1',
51
+ progress: 1,
52
+ total: 4,
53
+ message: 'Preparing to list explores',
54
+ },
55
+ });
56
+ (0, vitest_1.expect)(notify).toHaveBeenNthCalledWith(2, {
57
+ method: 'notifications/progress',
58
+ params: {
59
+ progressToken: 'progress-1',
60
+ progress: 2,
61
+ total: 4,
62
+ message: 'Loading explores from Lightdash',
63
+ },
64
+ });
65
+ });
66
+ (0, vitest_1.it)('does not fail the operation when notification delivery fails', async () => {
67
+ const reporter = (0, operation_reporter_js_1.createOperationReporter)({
68
+ mcpReq: {
69
+ _meta: { progressToken: 7 },
70
+ notify: vitest_1.vi.fn().mockRejectedValue(new Error('disconnected')),
71
+ },
72
+ });
73
+ await (0, vitest_1.expect)(reporter.phase({
74
+ phase: 'waiting',
75
+ operation: 'run query',
76
+ message: 'Waiting for Lightdash',
77
+ })).resolves.toBeUndefined();
78
+ });
79
+ });
@@ -21,6 +21,7 @@ const PROJECT_UUID_HINT = '(pass on every tool, or use HTTP pin — else PROJECT
21
21
  const TOPIC_DASHBOARDS = 'dashboards';
22
22
  const TOPIC_DASHBOARD_DESIGN = 'dashboard-design';
23
23
  const TOPIC_CHART_TYPES = 'chart-types';
24
+ const TOPIC_TABLE_CALCULATIONS = 'table-calculations';
24
25
  const DASHBOARD_CHART_TOPIC_IDS = [
25
26
  TOPIC_DASHBOARDS,
26
27
  TOPIC_DASHBOARD_DESIGN,
@@ -114,9 +115,9 @@ Dashboard slug: ${dashboardSlug !== null && dashboardSlug !== void 0 ? dashboard
114
115
 
115
116
  ${playbooks_js_1.CONTENT_DEVELOPER_HARD_BANS}
116
117
 
117
- Follow core + chart-types (clone via get_chart_as_code; preview with top-level slug; keep customDimensions when needed; tile if dashboardSlug set).
118
+ Follow core + chart-types + table-calculations (clone via get_chart_as_code; preview with top-level slug; keep customDimensions when needed; tile if dashboardSlug set).
118
119
  When dashboardSlug is set, the chart must serve a **board insight** from the approved Design Spec — do not invent a viz type for its own sake.
119
- Report UUID/slug from charts[0].data; note this profile cannot run_chart / prove UI render.`, TOPIC_CHART_TYPES));
120
+ Report UUID/slug from charts[0].data; note this profile cannot run_chart / prove UI render.`, [TOPIC_CHART_TYPES, TOPIC_TABLE_CALCULATIONS]));
120
121
  server.registerPrompt('move_content', {
121
122
  title: 'Move content',
122
123
  description: 'Move charts/dashboards into an existing space (no space create/update)',
@@ -56,6 +56,7 @@ const playbooks_js_1 = require("./resources/playbooks.js");
56
56
  (0, vitest_1.expect)(md).toContain('encode');
57
57
  (0, vitest_1.expect)(md).toMatch(/xref/);
58
58
  (0, vitest_1.expect)(md).toContain('chart-types');
59
+ (0, vitest_1.expect)(md).toContain('table-calculations');
59
60
  (0, vitest_1.expect)(md).not.toMatch(/`create_space`/);
60
61
  (0, vitest_1.expect)(md).not.toMatch(/`update_space`/);
61
62
  const toolIds = (0, index_js_1.listToolIds)((0, index_js_1.getProfile)('content-developer'));
@@ -189,6 +190,7 @@ const playbooks_js_1 = require("./resources/playbooks.js");
189
190
  const promptArgs = [];
190
191
  let publishText = '';
191
192
  let authorText = '';
193
+ let authorUris = [];
192
194
  let refactorText = '';
193
195
  const server = {
194
196
  registerPrompt: (name, _meta, handler) => {
@@ -223,6 +225,9 @@ const playbooks_js_1 = require("./resources/playbooks.js");
223
225
  .map((m) => { var _a; return (_a = m.content.text) !== null && _a !== void 0 ? _a : ''; })
224
226
  .join('\n')
225
227
  .toLowerCase();
228
+ authorUris = messages
229
+ .filter((m) => m.content.type === 'resource')
230
+ .map((m) => { var _a; return (_a = m.content.resource) === null || _a === void 0 ? void 0 : _a.uri; });
226
231
  }
227
232
  if (name === 'refactor_dashboard') {
228
233
  const messages = handler({
@@ -279,6 +284,9 @@ const playbooks_js_1 = require("./resources/playbooks.js");
279
284
  (0, vitest_1.expect)(publishText).toMatch(/untiled|leftover/);
280
285
  (0, vitest_1.expect)(publishText).toContain('content-governance');
281
286
  (0, vitest_1.expect)(authorText).toContain('board insight');
287
+ (0, vitest_1.expect)(authorText).toContain('table-calculations');
288
+ (0, vitest_1.expect)(authorUris).toContain('lightdash://playbooks/content-developer/chart-types');
289
+ (0, vitest_1.expect)(authorUris).toContain('lightdash://playbooks/content-developer/table-calculations');
282
290
  (0, vitest_1.expect)(refactorText).toMatch(/approved spec|user request allows/);
283
291
  (0, vitest_1.expect)(refactorText).not.toMatch(/unless explicitly requested/);
284
292
  });
@@ -4,6 +4,8 @@ URI: `lightdash://playbooks/content-developer/chart-types`
4
4
 
5
5
  Pick a viz type to **answer an insight question** from the Design Spec Objective. The table below is a **reference map**, not a build order — do not walk every row unless the user explicitly asked for multi-viz / all chart types. Prefer **clone** (`get_chart_as_code` / `duplicate_chart`) over inventing viz configs. Docs: [overview](https://docs.lightdash.com/references/chart-types/overview).
6
6
 
7
+ When the insight needs period-over-period, % of total, rank, or running/rolling windows, append `metricQuery.tableCalculations` per `lightdash://playbooks/content-developer/table-calculations` (do not freestyle warehouse `OVER()` SQL).
8
+
7
9
  When the user **does** ask for all types: follow dashboards **Multi-viz batch SOP** (shell → ≤2 concurrent chart creates → one tile update), split the board into a decision-oriented section plus a visualization-validation appendix (see `dashboards` / `dashboard-design`), and check every candidate type against the **semantic fit gate** below before adding it.
8
10
 
9
11
  ## Semantic fit gate
@@ -28,7 +28,7 @@ this profile does **not** execute queries, compile explores, create spaces, or p
28
28
  - Do not reuse a **draft** token after confirm (confirm returns a **new** validated token) or after payload/baseline drift (`PREVIEW_STALE`).
29
29
  - Do not unlock with a different resource's preview — `resourceKind` / `resourceKey` must match the preview exactly.
30
30
  - Do not treat `validate_chart` / `validate_dashboard` as unlock — saved-UUID health checks only (not UI-render proof).
31
- - Do not reveal secrets, warehouse credentials, or hidden SQL.
31
+ - Do not reveal secrets, warehouse credentials, or saved SQL **chart** bodies.
32
32
 
33
33
  ## Default budgets (override when the user expands scope)
34
34
 
@@ -46,21 +46,21 @@ Record when a budget stopped you. User-requested “one of every chart type” o
46
46
 
47
47
  ## Allowed tools (`lightdash_*`)
48
48
 
49
- | Tool | Use for |
50
- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
51
- | `get_project` | Resolve project; read `developerCapabilities` (mutate yes; **execute charts/tiles = false**) |
52
- | `search_content` | Find charts/dashboards; prefer short tokens, not marketing phrases |
53
- | `list_spaces` / `get_space` | Existing spaces; pick `spaceUuid` / `spaceSlug` |
54
- | `get_dashboard` / `get_chart` | Metadata. `get_chart` arg is **`chartUuidOrSlug`** (not `chartUuid`). Tiles often omit `x/y/w/h` |
55
- | `get_chart_as_code` | **Clone** upsert-shaped `chartConfig` + `metricQuery` before create/update |
56
- | `preview_chart_changes` / `preview_dashboard_changes` / `preview_content_move` | Mint draft `previewToken` + `resourceKey` |
57
- | `confirm_preview` | Unlock; returns **new** validated token — always pass **`projectUuid`** without HTTP pin |
58
- | `create_chart` / `update_chart` / `duplicate_chart` | Semantic as-code writes (after confirm); set `dashboardSlug` |
59
- | `create_dashboard` / `update_dashboard` / `duplicate_dashboard` | Dashboard shell then tile updates |
60
- | `add_dashboard_tile` / `move_dashboard_tile` / `remove_dashboard_tile` / `resize_dashboard_tile` | Tile ops; each needs preview of the **full next tiles array** |
61
- | `move_content` | Relocate into existing spaces |
62
- | `validate_chart` / `validate_dashboard` | Optional post-apply health (`chartUuid` / dashboard UUID) |
63
- | `compare_chart_versions` / `compare_dashboard_versions` | Drift / refactor |
49
+ | Tool | Use for |
50
+ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
51
+ | `get_project` | Resolve project; read `developerCapabilities` (mutate yes; **execute charts/tiles = false**) |
52
+ | `search_content` | Find charts/dashboards; prefer short tokens, not marketing phrases |
53
+ | `list_spaces` / `get_space` | Existing spaces; pick `spaceUuid` / `spaceSlug` |
54
+ | `get_dashboard` / `get_chart` | Metadata (+ query fields when included). `get_chart` is inspect-only — no `chartConfig`; use `get_chart_as_code` to clone. Arg is **`chartUuidOrSlug`**. |
55
+ | `get_chart_as_code` | **Clone** upsert-shaped `chartConfig` + `metricQuery` before create/update |
56
+ | `preview_chart_changes` / `preview_dashboard_changes` / `preview_content_move` | Mint draft `previewToken` + `resourceKey` |
57
+ | `confirm_preview` | Unlock; returns **new** validated token — always pass **`projectUuid`** without HTTP pin |
58
+ | `create_chart` / `update_chart` / `duplicate_chart` | Semantic as-code writes (after confirm); set `dashboardSlug` |
59
+ | `create_dashboard` / `update_dashboard` / `duplicate_dashboard` | Dashboard shell then tile updates |
60
+ | `add_dashboard_tile` / `move_dashboard_tile` / `remove_dashboard_tile` / `resize_dashboard_tile` | Tile ops; each needs preview of the **full next tiles array** |
61
+ | `move_content` | Relocate into existing spaces |
62
+ | `validate_chart` / `validate_dashboard` | Optional post-apply health (`chartUuid` / dashboard UUID) |
63
+ | `compare_chart_versions` / `compare_dashboard_versions` | Drift / refactor |
64
64
 
65
65
  ## Phase 0 — Resolve project
66
66
 
@@ -107,3 +107,4 @@ Record when a budget stopped you. User-requested “one of every chart type” o
107
107
  - Tile shape: `{ type: 'saved_chart', x, y, w, h, properties: { savedChartUuid, title? } }` — use the UUID from `create_chart` / `duplicate_chart` (36-column grid; half-width ≈ `w: 18`). Optional `chartSlug` is metadata only; do not omit `savedChartUuid`.
108
108
  - `create_chart` response: extract UUID from `charts[0].data.uuid` (not a bare chart object).
109
109
  - Viz shapes: `lightdash://playbooks/content-developer/chart-types`.
110
+ - PoP / % of total / rank / running or rolling windows on `metricQuery.tableCalculations`: `lightdash://playbooks/content-developer/table-calculations`.
@@ -41,7 +41,7 @@ Semantic as-code only. Prefer clone, not invent.
41
41
  1. Prefer **reuse** of an existing chart as a tile when it already fits.
42
42
  2. Else `search_content` / `get_space` → pick a **rendering** seed on the same `tableName` (same explore).
43
43
  3. `get_chart_as_code` (or `duplicate_chart`) → **keep `chartConfig` structure** (layout + series encode); edit only `name`, `slug`, and `metricQuery` fields that exist on the explore; set `dashboardSlug` = dashboard slug from step 1.
44
- 4. Viz type / encode details: `lightdash://playbooks/content-developer/chart-types`.
44
+ 4. Viz type / encode details: `lightdash://playbooks/content-developer/chart-types`. PoP / % of total / rank / windows on `metricQuery.tableCalculations`: `lightdash://playbooks/content-developer/table-calculations`.
45
45
 
46
46
  Then:
47
47
 
@@ -4,12 +4,13 @@ URI: `lightdash://playbooks/content-developer`
4
4
 
5
5
  Workflow-scoped playbooks (always load **core** plus one topic with a prompt):
6
6
 
7
- | Topic | URI |
8
- | ------------------------------------------------------------ | ---------------------------------------------------------- |
9
- | Core (gates & bans) | `lightdash://playbooks/content-developer/core` |
10
- | Dashboards & dashboard-owned charts | `lightdash://playbooks/content-developer/dashboards` |
11
- | Dashboard design (Design Spec + layout / markdown / filters) | `lightdash://playbooks/content-developer/dashboard-design` |
12
- | Chart types (cartesian + pie/funnel/…) | `lightdash://playbooks/content-developer/chart-types` |
13
- | Content move | `lightdash://playbooks/content-developer/content-move` |
7
+ | Topic | URI |
8
+ | ------------------------------------------------------------ | ------------------------------------------------------------ |
9
+ | Core (gates & bans) | `lightdash://playbooks/content-developer/core` |
10
+ | Dashboards & dashboard-owned charts | `lightdash://playbooks/content-developer/dashboards` |
11
+ | Dashboard design (Design Spec + layout / markdown / filters) | `lightdash://playbooks/content-developer/dashboard-design` |
12
+ | Chart types (cartesian + pie/funnel/…) | `lightdash://playbooks/content-developer/chart-types` |
13
+ | Table calculations (template / formula / sql) | `lightdash://playbooks/content-developer/table-calculations` |
14
+ | Content move | `lightdash://playbooks/content-developer/content-move` |
14
15
 
15
16
  **Authoring order:** clarify Objective → Design Spec → approve → dashboard shell → charts with `dashboardSlug` → tiles (+ optional filters; prefer one explore or `tileTargets` exclude by tile UUID). Always pass **`projectUuid`** on `confirm_preview` and apply when there is no HTTP pin. Clone via `get_chart_as_code`; never invent fieldIds or skinny `chartConfig` (cartesian series need `encode.xRef`/`yRef`). Multi-viz / all chart types only when the user explicitly asks (batch: shell → charts ≤2 parallel → one tile update). Cap concurrent writes at ≤2 on hosted tunnels. Spaces are Terraform / out-of-band (`list_spaces` / `get_space` only).
@@ -0,0 +1,119 @@
1
+ # Content-developer — table calculations
2
+
3
+ URI: `lightdash://playbooks/content-developer/table-calculations`
4
+
5
+ Add chart-local metrics on top of explore dimensions/metrics via `metricQuery.tableCalculations`. Prefer clone (`get_chart_as_code`) then append calcs. This profile **cannot** run queries to verify row values.
6
+
7
+ Docs: [overview](https://docs.lightdash.com/guides/table-calculations) · [formula](https://docs.lightdash.com/guides/formula-table-calculations) · [SQL templates](https://docs.lightdash.com/guides/table-calculations/sql-templates) · [as-code](https://docs.lightdash.com/guides/developer/dashboards-as-code) · [row](https://docs.lightdash.com/references/table-calculation-functions/row-functions) / [pivot](https://docs.lightdash.com/references/table-calculation-functions/pivot-functions) / [aggregate](https://docs.lightdash.com/references/table-calculation-functions/aggregate-functions) functions.
8
+
9
+ ## When to use
10
+
11
+ - Chart-specific PoP, % of total, rank, running total, rolling window, pivot share.
12
+ - If the same calc is reused across many boards → put it in **dbt** / the semantic layer instead ([overview](https://docs.lightdash.com/guides/table-calculations)).
13
+
14
+ ## Preference (playbook policy)
15
+
16
+ 1. **`template`** — quick types + `window_function` (OpenAPI `TemplateTableCalculation`).
17
+ 2. **`formula`** — portable spreadsheet syntax starting with `=` ([formula docs](https://docs.lightdash.com/guides/formula-table-calculations)); column names match results headers.
18
+ 3. **`sql`** — only for `total()` / `row_total()` / real `pivot_*` helpers (`pivot_offset`, `pivot_index`, `pivot_row`, …), or when formula cannot express it. Never invent names like `pivot_row_total`.
19
+
20
+ Formula and SQL modes are **not** interconvertible — delete and recreate to switch ([formula FAQ](https://docs.lightdash.com/guides/formula-table-calculations)).
21
+
22
+ ## Intent → shape
23
+
24
+ | Intent | Prefer | OpenAPI / expression |
25
+ | ---------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
26
+ | % change from previous | `template` | `type: percent_change_from_previous` + `fieldId` + `orderBy` |
27
+ | % of previous value | `template` | `type: percent_of_previous_value` + `fieldId` + `orderBy` |
28
+ | % of column total | `template` | `type: percent_of_column_total` + `fieldId` |
29
+ | Rank in column | `template` | `type: rank_in_column` + `fieldId` |
30
+ | Running total | `template` | `type: running_total` + `fieldId` |
31
+ | Rolling / moving window | `template` or `formula` | `window_function` + `frame`, or `MOVING_AVG` / `MOVING_SUM` |
32
+ | Simple ratio / IF / date math | `formula` | e.g. `=orders_sum_order_amount / orders_num_unique_order_ids` |
33
+ | Grand % of total (correct metric re-agg) | `sql` | `${metric} / total(${metric})` ([aggregate](https://docs.lightdash.com/references/table-calculation-functions/aggregate-functions)) |
34
+ | Pivot row share | `sql` | `${metric} / row_total(${metric})` ([aggregate](https://docs.lightdash.com/references/table-calculation-functions/aggregate-functions)) — **not** `pivot_row_total` (does not exist) |
35
+ | Cross-column pivot access | `sql` | `pivot_offset` / `pivot_index` / `pivot_row` / … **only when pivoted** ([pivot](https://docs.lightdash.com/references/table-calculation-functions/pivot-functions)) |
36
+
37
+ SQL template guides: [percent change](https://docs.lightdash.com/guides/table-calculations/table-calculation-sql-templates/percent-change-from-previous), [percent of previous](https://docs.lightdash.com/guides/table-calculations/table-calculation-sql-templates/percent-of-previous-value), [percent of column](https://docs.lightdash.com/guides/table-calculations/table-calculation-sql-templates/percent-of-total-column), [percent of group/pivot](https://docs.lightdash.com/guides/table-calculations/table-calculation-sql-templates/percent-of-group-pivot-total), [rank](https://docs.lightdash.com/guides/table-calculations/table-calculation-sql-templates/rank-in-column), [running total](https://docs.lightdash.com/guides/table-calculations/table-calculation-sql-templates/running-total), [rolling window](https://docs.lightdash.com/guides/table-calculations/table-calculation-sql-templates/rolling-window).
38
+
39
+ ## Format and totals
40
+
41
+ - Percent-style calcs: set `format: { type: 'percent' }` (and `type: 'number'` when needed).
42
+ - `totalMode`: `formula` for ratios evaluated at total grain; `sum_of_rows` for windows / template windows; `none` when a total is meaningless ([totals](https://docs.lightdash.com/guides/table-calculations)).
43
+
44
+ ## JSON skeletons
45
+
46
+ Field IDs are **illustrative** — copy real `fieldId`s from the explore / seed.
47
+
48
+ ### Template (percent change)
49
+
50
+ ```json
51
+ {
52
+ "name": "amount_pct_change",
53
+ "displayName": "% change vs previous",
54
+ "type": "number",
55
+ "format": { "type": "percent" },
56
+ "totalMode": "sum_of_rows",
57
+ "template": {
58
+ "type": "percent_change_from_previous",
59
+ "fieldId": "orders_sum_order_amount",
60
+ "orderBy": [{ "fieldId": "orders_order_date_month", "order": "asc" }]
61
+ }
62
+ }
63
+ ```
64
+
65
+ ### Formula (ratio)
66
+
67
+ ```json
68
+ {
69
+ "name": "avg_order_value",
70
+ "displayName": "Average order value",
71
+ "type": "number",
72
+ "totalMode": "formula",
73
+ "formula": "=orders_sum_order_amount / orders_num_unique_order_ids"
74
+ }
75
+ ```
76
+
77
+ ### SQL (percent of grand total)
78
+
79
+ ```json
80
+ {
81
+ "name": "amount_pct_of_total",
82
+ "displayName": "% of total",
83
+ "type": "number",
84
+ "format": { "type": "percent" },
85
+ "totalMode": "formula",
86
+ "sql": "${orders.sum_order_amount} / total(${orders.sum_order_amount})"
87
+ }
88
+ ```
89
+
90
+ ### SQL (percent of pivot row — requires `pivotConfig`)
91
+
92
+ ```json
93
+ {
94
+ "name": "amount_pct_of_pivot_row",
95
+ "displayName": "% of pivot row total",
96
+ "type": "number",
97
+ "format": { "type": "percent" },
98
+ "totalMode": "formula",
99
+ "sql": "${orders.sum_order_amount} / row_total(${orders.sum_order_amount})"
100
+ }
101
+ ```
102
+
103
+ ## Authoring SOP
104
+
105
+ 1. Clone via `get_chart_as_code` (or `duplicate_chart`) — that returns upsert-shaped `chartConfig` + `metricQuery`. Append to `metricQuery.tableCalculations` (never omit the array — OpenAPI requires it). Use `get_chart` only to inspect existing calc expressions; it does **not** return `chartConfig`.
106
+ 2. Align `metricQuery.sorts` with window `orderBy` / formula `ORDER BY`.
107
+ 3. If the calc is plotted, reference its `name` in viz encode / series like any metric fieldId.
108
+ 4. `preview_chart_changes` → `confirm_preview` → `create_chart` / `update_chart` with the **identical** proposed body.
109
+ 5. Do not claim verified numbers — this profile has no `run_chart` / warehouse execute.
110
+
111
+ ## Hard bans
112
+
113
+ - Do not invent `fieldId`s or results-header column names. Copy them from `get_chart_as_code` / explore seeds — playbook skeletons are examples only.
114
+ - `preview_chart_changes` / `confirm_preview` do **not** prove template `fieldId`s or formula headers exist; inventing IDs can still preview-validate and only fail at query time.
115
+ - Do not invent SQL helpers — use `total()` / `row_total()` ([aggregate](https://docs.lightdash.com/references/table-calculation-functions/aggregate-functions)) or documented `pivot_*` ([pivot](https://docs.lightdash.com/references/table-calculation-functions/pivot-functions)). There is no `pivot_row_total`.
116
+ - Do not convert formula ↔ sql in place — recreate the calc.
117
+ - Do not use `pivot_*` / `row_total` without a pivoted dimension (`pivotConfig.columns`).
118
+ - Do not author SQL **charts** or open data-analyst / raw SQL execution to “fix” a table calc on this profile.
119
+ - Do not freestyle warehouse-specific `OVER()` SQL when a `template` or `formula` covers the intent.
@@ -2,7 +2,7 @@
2
2
  * Content-developer multi-playbook resources (core + topics + index).
3
3
  */
4
4
  import type { McpServer } from '@modelcontextprotocol/server';
5
- export type ContentDeveloperPlaybookTopic = 'chart-types' | 'content-move' | 'dashboard-design' | 'dashboards';
5
+ export type ContentDeveloperPlaybookTopic = 'chart-types' | 'content-move' | 'dashboard-design' | 'dashboards' | 'table-calculations';
6
6
  export declare const CONTENT_DEVELOPER_HARD_BANS: string;
7
7
  export declare const getAllPlaybookMarkdown: () => string;
8
8
  export declare const CONTENT_DEVELOPER_CORE_PLAYBOOK: import("../../../lib/playbook-resources.js").EmbeddedPlaybook;
@@ -27,7 +27,7 @@ Do not mutate the proposed payload after preview_* (description/name/SQL/metrics
27
27
  Do not treat validate_chart / validate_dashboard as a preview unlock — they are saved-UUID health checks only (validate_chart needs chartUuid).
28
28
  Do not reuse a draft previewToken after confirm; re-run preview if the resource drifts (PREVIEW_STALE).
29
29
  Do not use subagent-driven-development or multi-task writing-plans solely to click MCP preview/confirm/apply for lab boards (e.g. experiments) — after Design Spec approval, run Batch SOP inline in the same session.
30
- Do not reveal secrets, warehouse credentials, or hidden SQL.`,
30
+ Do not reveal secrets, warehouse credentials, or saved SQL chart bodies.`,
31
31
  coreDescription: 'Hard bans, tools, project scope, preview gate, and apply pitfalls',
32
32
  topics: [
33
33
  {
@@ -48,6 +48,12 @@ Do not reveal secrets, warehouse credentials, or hidden SQL.`,
48
48
  description: 'Insight-first viz pick; cartesian encode checklist; UI intent → as-code map',
49
49
  file: 'chart-types.md',
50
50
  },
51
+ {
52
+ id: 'table-calculations',
53
+ title: 'Content-developer table-calculations playbook',
54
+ description: 'metricQuery.tableCalculations: template → formula → sql; PoP, % of total, rank, windows',
55
+ file: 'table-calculations.md',
56
+ },
51
57
  {
52
58
  id: 'content-move',
53
59
  title: 'Content-developer content-move playbook',
@@ -41,17 +41,17 @@ Record budget / pagination / truncation stops in the answer.
41
41
 
42
42
  ## Allowed tools (`lightdash_*`)
43
43
 
44
- | Tool | Use for |
45
- | ---------------------------------------------------- | -------------------------------------------------------- |
46
- | `get_project` | Resolve project; read `readerCapabilities` + pin context |
47
- | `search_content` | Find charts/dashboards/spaces/data apps |
48
- | `list_spaces` / `get_space` | Space hierarchy + immediate content |
49
- | `get_dashboard` / `get_chart` | Structure / definition (SQL text hidden) |
50
- | `list_project_parameters` / `get_project_parameters` | Parameter defs / values |
51
- | `explain_content` | Compact metadata explanation |
52
- | `run_chart` / `run_dashboard_tile` | Bounded saved execution (numbers) |
53
- | `export_chart_image` | PNG snapshot of a saved chart (vision); needs headless |
54
- | `get_query_result` / `cancel_query` | Poll / cancel by `queryUuid` |
44
+ | Tool | Use for |
45
+ | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
46
+ | `get_project` | Resolve project; read `readerCapabilities` + pin context |
47
+ | `search_content` | Find charts/dashboards/spaces/data apps |
48
+ | `list_spaces` / `get_space` | Space hierarchy + immediate content |
49
+ | `get_dashboard` / `get_chart` | Structure / definition (saved SQL **chart** bodies hidden; semantic `tableCalculations` may appear when query is included) |
50
+ | `list_project_parameters` / `get_project_parameters` | Parameter defs / values |
51
+ | `explain_content` | Compact metadata explanation |
52
+ | `run_chart` / `run_dashboard_tile` | Bounded saved execution (numbers) |
53
+ | `export_chart_image` | PNG snapshot of a saved chart (vision); needs headless |
54
+ | `get_query_result` / `cancel_query` | Poll / cancel by `queryUuid` |
55
55
 
56
56
  ## Phase 0 — Resolve project
57
57
 
@@ -14,7 +14,7 @@ URI: `lightdash://playbooks/content-reader/explain-run`
14
14
  | Signal | Action |
15
15
  | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
16
16
  | Search `source=sql` | Do **not** call `run_chart`; explain metadata only; cite `CONTENT_NOT_EXECUTABLE` / capability |
17
- | `get_chart` → `chartType=sql` + warnings | Same — SQL text is hidden; execution disabled |
17
+ | `get_chart` → `chartType=sql` + warnings | Same — saved SQL **chart** body hidden; execution disabled |
18
18
  | Opaque API errors (e.g. “Saved query not found”) on SQL ids | Treat as non-executable; do not retry endlessly |
19
19
  | `readerCapabilities.canExecuteSqlCharts=false` | Hard stop for SQL execution |
20
20
 
@@ -4,6 +4,8 @@
4
4
  import type { McpContextProvider } from '../../server/request-context.js';
5
5
  import type { McpServer } from '@modelcontextprotocol/server';
6
6
  export declare function detectChartType(chart: Record<string, unknown>): 'semantic' | 'sql' | 'unknown';
7
+ /** Pass through OpenAPI TableCalculation fields agents need to clone. */
8
+ export declare function toReaderTableCalculation(tc: unknown): Record<string, unknown>;
7
9
  export declare function registerSearchContent(server: McpServer, contextProvider: McpContextProvider): void;
8
10
  export declare function registerGetDashboard(server: McpServer, contextProvider: McpContextProvider): void;
9
11
  export declare function registerGetChart(server: McpServer, contextProvider: McpContextProvider): void;
@@ -5,6 +5,7 @@
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getChartTool = exports.getDashboardTool = exports.searchContentTool = void 0;
7
7
  exports.detectChartType = detectChartType;
8
+ exports.toReaderTableCalculation = toReaderTableCalculation;
8
9
  exports.registerSearchContent = registerSearchContent;
9
10
  exports.registerGetDashboard = registerGetDashboard;
10
11
  exports.registerGetChart = registerGetChart;
@@ -30,6 +31,36 @@ function detectChartType(chart) {
30
31
  }
31
32
  return 'unknown';
32
33
  }
34
+ /** Pass through OpenAPI TableCalculation fields agents need to clone. */
35
+ function toReaderTableCalculation(tc) {
36
+ const row = (tc !== null && tc !== void 0 ? tc : {});
37
+ const out = {
38
+ name: row.name,
39
+ displayName: row.displayName,
40
+ };
41
+ if (row.type !== undefined) {
42
+ out.type = row.type;
43
+ }
44
+ if (row.format !== undefined) {
45
+ out.format = row.format;
46
+ }
47
+ if (row.totalMode !== undefined) {
48
+ out.totalMode = row.totalMode;
49
+ }
50
+ if (row.index !== undefined) {
51
+ out.index = row.index;
52
+ }
53
+ if (row.formula !== undefined) {
54
+ out.formula = row.formula;
55
+ }
56
+ if (row.sql !== undefined) {
57
+ out.sql = row.sql;
58
+ }
59
+ if (row.template !== undefined) {
60
+ out.template = row.template;
61
+ }
62
+ return out;
63
+ }
33
64
  /* eslint-disable-next-line sonarjs/cyclomatic-complexity -- chart shape mapping */
34
65
  function toReaderChart(chart, includeQuery) {
35
66
  var _a, _b, _c, _d;
@@ -42,10 +73,7 @@ function toReaderChart(chart, includeQuery) {
42
73
  ? metricQuery.metrics.map((fieldId) => ({ fieldId }))
43
74
  : [];
44
75
  const tableCalculations = includeQuery
45
- ? ((_b = metricQuery.tableCalculations) !== null && _b !== void 0 ? _b : []).map((tc) => {
46
- const row = tc;
47
- return { name: row.name, displayName: row.displayName };
48
- })
76
+ ? ((_b = metricQuery.tableCalculations) !== null && _b !== void 0 ? _b : []).map(toReaderTableCalculation)
49
77
  : undefined;
50
78
  return {
51
79
  uuid: chart.uuid,
@@ -185,7 +213,7 @@ function registerGetDashboard(server, contextProvider) {
185
213
  function registerGetChart(server, contextProvider) {
186
214
  (0, content_reader_js_1.registerContentReaderTool)(server, 'get_chart', {
187
215
  title: 'Get chart',
188
- description: 'Explain a saved chart definition (SQL text hidden)',
216
+ description: 'Explain a saved semantic chart definition (saved SQL chart bodies stay hidden; tableCalculations expressions included when includeQueryDefinition)',
189
217
  safety: content_reader_js_1.METADATA_SAFETY,
190
218
  inputSchema: {
191
219
  projectUuid: (0, schema_fields_js_1.projectUuidField)().optional(),
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Unit tests for get_chart table-calculation pass-through.
3
+ */
4
+ export {};
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ /**
3
+ * Unit tests for get_chart table-calculation pass-through.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const vitest_1 = require("vitest");
7
+ const reader_content_js_1 = require("./reader-content.js");
8
+ (0, vitest_1.describe)('toReaderTableCalculation', () => {
9
+ (0, vitest_1.it)('preserves formula table calculations', () => {
10
+ (0, vitest_1.expect)((0, reader_content_js_1.toReaderTableCalculation)({
11
+ name: 'revenue_running_total',
12
+ displayName: 'Running total',
13
+ type: 'number',
14
+ totalMode: 'sum_of_rows',
15
+ formula: '=RUNNING_TOTAL(orders_total_order_amount)',
16
+ index: 0,
17
+ })).toEqual({
18
+ name: 'revenue_running_total',
19
+ displayName: 'Running total',
20
+ type: 'number',
21
+ totalMode: 'sum_of_rows',
22
+ formula: '=RUNNING_TOTAL(orders_total_order_amount)',
23
+ index: 0,
24
+ });
25
+ });
26
+ (0, vitest_1.it)('preserves template table calculations', () => {
27
+ (0, vitest_1.expect)((0, reader_content_js_1.toReaderTableCalculation)({
28
+ name: 'revenue_pct_change',
29
+ displayName: '% change vs previous',
30
+ type: 'number',
31
+ format: { type: 'percent' },
32
+ totalMode: 'sum_of_rows',
33
+ template: {
34
+ type: 'percent_change_from_previous',
35
+ fieldId: 'orders_total_order_amount',
36
+ orderBy: [{ fieldId: 'orders_order_date_week', order: 'asc' }],
37
+ },
38
+ })).toEqual({
39
+ name: 'revenue_pct_change',
40
+ displayName: '% change vs previous',
41
+ type: 'number',
42
+ format: { type: 'percent' },
43
+ totalMode: 'sum_of_rows',
44
+ template: {
45
+ type: 'percent_change_from_previous',
46
+ fieldId: 'orders_total_order_amount',
47
+ orderBy: [{ fieldId: 'orders_order_date_week', order: 'asc' }],
48
+ },
49
+ });
50
+ });
51
+ (0, vitest_1.it)('preserves sql table calculations', () => {
52
+ (0, vitest_1.expect)((0, reader_content_js_1.toReaderTableCalculation)({
53
+ name: 'pct_of_total',
54
+ displayName: '% of total',
55
+ sql: '${orders.total_order_amount} / total(${orders.total_order_amount})',
56
+ format: { type: 'percent' },
57
+ })).toEqual({
58
+ name: 'pct_of_total',
59
+ displayName: '% of total',
60
+ format: { type: 'percent' },
61
+ sql: '${orders.total_order_amount} / total(${orders.total_order_amount})',
62
+ });
63
+ });
64
+ });
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * Capability surface is the profile's tools array, not process safety mode.
11
11
  */
12
+ import type { OperationReporter } from '../notifications/operation-reporter.js';
12
13
  import type { McpContextProvider } from '../server/request-context.js';
13
14
  import type { LightdashClient } from '@lightdash-tools/client';
14
15
  import type { AuditStatus, ToolAnnotations } from '@lightdash-tools/common';
@@ -86,6 +87,8 @@ export declare function withAuditStatus<T extends TextContent>(result: T, status
86
87
  export declare function registerToolSafe(server: unknown, shortName: string, options: ToolOptions, handler: ToolHandler): void;
87
88
  export type ToolExecutionContext = {
88
89
  lightdashClient: LightdashClient;
90
+ /** Request-scoped reporter backed by MCP progress notifications when available. */
91
+ operationReporter: OperationReporter;
89
92
  /** SDK ServerContext when the transport provides it (second registerTool arg). */
90
93
  serverContext: ServerContext | undefined;
91
94
  sessionId: string;
@@ -28,6 +28,7 @@ const tool_audit_context_js_1 = require("../audit/tool-audit-context.js");
28
28
  const available_projects_js_1 = require("../governance/available-projects.js");
29
29
  const mcp_client_session_js_1 = require("../governance/mcp-client-session.js");
30
30
  const project_pin_js_1 = require("../governance/project-pin.js");
31
+ const operation_reporter_js_1 = require("../notifications/operation-reporter.js");
31
32
  const upstream_errors_js_1 = require("../server/upstream-errors.js");
32
33
  /** Prefix for all MCP tool names (disambiguation when multiple servers are connected). */
33
34
  exports.TOOL_PREFIX = 'lightdash_';
@@ -239,11 +240,13 @@ function wrapToolContextual(contextProvider, fn) {
239
240
  return await (0, mcp_client_session_js_1.runWithMcpClientSessionAsync)(sessionId, async () => {
240
241
  const context = await contextProvider.getContext(extra);
241
242
  const auth = context.auth;
243
+ const serverContext = asServerContext(extra);
242
244
  return await (0, tool_audit_context_js_1.runWithToolAuditAuthAsync)({ tokenHash: auth === null || auth === void 0 ? void 0 : auth.tokenHash, subject: auth === null || auth === void 0 ? void 0 : auth.subject }, async () => {
243
245
  var _a;
244
246
  const execution = {
245
247
  lightdashClient: context.lightdashClient,
246
- serverContext: asServerContext(extra),
248
+ operationReporter: (0, operation_reporter_js_1.createOperationReporter)(serverContext),
249
+ serverContext,
247
250
  sessionId,
248
251
  subject: (_a = auth === null || auth === void 0 ? void 0 : auth.subject) !== null && _a !== void 0 ? _a : 'anonymous',
249
252
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightdash-tools/mcp",
3
- "version": "0.13.0",
3
+ "version": "0.13.2",
4
4
  "description": "MCP server for Lightdash semantic-layer, organization-audit, content-reader, content-developer, content-governance, and ai-agent-ops 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.13.0",
28
- "@lightdash-tools/common": "0.13.0"
27
+ "@lightdash-tools/client": "0.13.2",
28
+ "@lightdash-tools/common": "0.13.2"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@modelcontextprotocol/client": "2.0.0",