@lightdash-tools/mcp 0.14.0 → 0.16.1

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 (113) hide show
  1. package/README.md +30 -11
  2. package/dist/auth/oauth-broker/lightdash-token.d.ts +6 -5
  3. package/dist/auth/oauth-broker/lightdash-token.js +6 -10
  4. package/dist/auth/oauth-broker/mcp-access-token.d.ts +31 -0
  5. package/dist/auth/oauth-broker/mcp-access-token.js +109 -0
  6. package/dist/auth/oauth-broker/mcp-access-token.test.d.ts +1 -0
  7. package/dist/auth/oauth-broker/mcp-access-token.test.js +61 -0
  8. package/dist/auth/oauth-broker/pending-store.d.ts +9 -3
  9. package/dist/auth/oauth-broker/pending-store.js +5 -3
  10. package/dist/auth/oauth-broker/pending-store.test.js +28 -44
  11. package/dist/auth/oauth-broker/routes.d.ts +2 -1
  12. package/dist/auth/oauth-broker/routes.js +97 -45
  13. package/dist/auth/oauth-broker/routes.test.js +81 -13
  14. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +2 -0
  15. package/dist/auth/resource-server/lightdash-oauth-middleware.js +58 -37
  16. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +59 -57
  17. package/dist/auth/resource-server/oauth-protected-resource.js +2 -2
  18. package/dist/bin.js +33 -7
  19. package/dist/config/env.d.ts +5 -0
  20. package/dist/config/env.js +6 -1
  21. package/dist/config/load-mcp-config.d.ts +12 -1
  22. package/dist/config/load-mcp-config.js +17 -8
  23. package/dist/config/load-mcp-config.test.js +20 -0
  24. package/dist/config/prompt-context-policy.d.ts +18 -0
  25. package/dist/config/prompt-context-policy.js +40 -0
  26. package/dist/config/prompt-context-policy.test.d.ts +4 -0
  27. package/dist/config/prompt-context-policy.test.js +35 -0
  28. package/dist/config/test-mcp-http-config.js +1 -1
  29. package/dist/governance/mcp-post-factory-context.d.ts +2 -0
  30. package/dist/http.d.ts +7 -1
  31. package/dist/http.integration.test.js +57 -22
  32. package/dist/http.js +10 -1
  33. package/dist/index.d.ts +6 -1
  34. package/dist/index.js +6 -3
  35. package/dist/policy/content-developer.d.ts +5 -0
  36. package/dist/policy/content-developer.js +25 -1
  37. package/dist/policy/content-developer.test.js +29 -0
  38. package/dist/profiles/ai-agent-ops/v1/invariants.d.ts +27 -0
  39. package/dist/profiles/ai-agent-ops/v1/invariants.js +39 -0
  40. package/dist/profiles/ai-agent-ops/v1/prompts.d.ts +3 -2
  41. package/dist/profiles/ai-agent-ops/v1/prompts.js +67 -41
  42. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.d.ts +2 -1
  43. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.js +10 -3
  44. package/dist/profiles/content-developer/v1/invariants.d.ts +69 -0
  45. package/dist/profiles/content-developer/v1/invariants.js +95 -0
  46. package/dist/profiles/content-developer/v1/prompt-specs.d.ts +32 -0
  47. package/dist/profiles/content-developer/v1/prompt-specs.js +56 -0
  48. package/dist/profiles/content-developer/v1/prompts.d.ts +4 -3
  49. package/dist/profiles/content-developer/v1/prompts.js +65 -71
  50. package/dist/profiles/content-developer/v1/prompts.test.js +61 -7
  51. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +1 -0
  52. package/dist/profiles/content-developer/v1/resources/playbooks/index.md +11 -8
  53. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/dashboard-diff.md +15 -0
  54. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-required.md +14 -0
  55. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-stale.md +21 -0
  56. package/dist/profiles/content-developer/v1/resources/playbooks.d.ts +3 -2
  57. package/dist/profiles/content-developer/v1/resources/playbooks.js +35 -22
  58. package/dist/profiles/content-governance/v1/invariants.d.ts +27 -0
  59. package/dist/profiles/content-governance/v1/invariants.js +39 -0
  60. package/dist/profiles/content-governance/v1/prompts.d.ts +4 -2
  61. package/dist/profiles/content-governance/v1/prompts.js +31 -19
  62. package/dist/profiles/content-governance/v1/resources/playbooks.d.ts +2 -1
  63. package/dist/profiles/content-governance/v1/resources/playbooks.js +8 -9
  64. package/dist/profiles/content-reader/v1/invariants.d.ts +33 -0
  65. package/dist/profiles/content-reader/v1/invariants.js +47 -0
  66. package/dist/profiles/content-reader/v1/prompt-specs.d.ts +18 -0
  67. package/dist/profiles/content-reader/v1/prompt-specs.js +33 -0
  68. package/dist/profiles/content-reader/v1/prompts.d.ts +3 -2
  69. package/dist/profiles/content-reader/v1/prompts.js +69 -76
  70. package/dist/profiles/content-reader/v1/resources/playbooks.d.ts +2 -1
  71. package/dist/profiles/content-reader/v1/resources/playbooks.js +10 -11
  72. package/dist/profiles/data-analyst/v1/invariants.d.ts +21 -0
  73. package/dist/profiles/data-analyst/v1/invariants.js +31 -0
  74. package/dist/profiles/data-analyst/v1/prompts.d.ts +3 -2
  75. package/dist/profiles/data-analyst/v1/prompts.js +17 -9
  76. package/dist/profiles/data-analyst/v1/resources/playbooks.d.ts +2 -1
  77. package/dist/profiles/data-analyst/v1/resources/playbooks.js +6 -7
  78. package/dist/profiles/lib/playbook-resources.d.ts +16 -34
  79. package/dist/profiles/lib/playbook-resources.js +55 -76
  80. package/dist/profiles/lib/prompt-context.d.ts +71 -0
  81. package/dist/profiles/lib/prompt-context.js +205 -0
  82. package/dist/profiles/lib/prompt-context.test.d.ts +4 -0
  83. package/dist/profiles/lib/prompt-context.test.js +154 -0
  84. package/dist/profiles/lib/prompt-invariants.d.ts +20 -0
  85. package/dist/profiles/lib/prompt-invariants.js +54 -0
  86. package/dist/profiles/organization-audit/v1/invariants.d.ts +24 -0
  87. package/dist/profiles/organization-audit/v1/invariants.js +35 -0
  88. package/dist/profiles/organization-audit/v1/prompts.d.ts +3 -2
  89. package/dist/profiles/organization-audit/v1/prompts.js +44 -28
  90. package/dist/profiles/organization-audit/v1/resources/playbooks.d.ts +2 -1
  91. package/dist/profiles/organization-audit/v1/resources/playbooks.js +10 -3
  92. package/dist/profiles/semantic-layer/v1/invariants.d.ts +27 -0
  93. package/dist/profiles/semantic-layer/v1/invariants.js +39 -0
  94. package/dist/profiles/semantic-layer/v1/prompts.d.ts +3 -2
  95. package/dist/profiles/semantic-layer/v1/prompts.js +37 -26
  96. package/dist/profiles/semantic-layer/v1/resources/playbooks.d.ts +2 -4
  97. package/dist/profiles/semantic-layer/v1/resources/playbooks.js +8 -7
  98. package/dist/profiles/test-support/prompt-context-budget.test.d.ts +5 -0
  99. package/dist/profiles/test-support/prompt-context-budget.test.js +72 -0
  100. package/dist/profiles/types.d.ts +6 -1
  101. package/dist/server/capabilities.d.ts +3 -0
  102. package/dist/server/capabilities.js +4 -2
  103. package/dist/tools/lib/schema-fields.d.ts +4 -0
  104. package/dist/tools/lib/schema-fields.js +8 -1
  105. package/dist/tools/project/developer-content-preview.js +1 -1
  106. package/dist/tools/project/developer-content.js +2 -2
  107. package/dist/tools/query/reader-tool-helpers.d.ts +2 -2
  108. package/dist/tools/query/reader-tool-helpers.js +2 -2
  109. package/dist/tools/query/reader-tool-helpers.test.js +1 -0
  110. package/dist/tools/shared.d.ts +6 -1
  111. package/dist/tools/shared.js +12 -2
  112. package/dist/transports/streamable-http.js +10 -3
  113. package/package.json +3 -3
@@ -1,35 +1,42 @@
1
1
  "use strict";
2
2
  /**
3
- * MCP prompts for semantic-layer discovery and compile workflows.
3
+ * MCP prompts for semantic-layer discovery and compile workflows (progressive-disclosure context).
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.registerSemanticLayerPrompts = registerSemanticLayerPrompts;
7
+ /* eslint-disable @typescript-eslint/no-deprecated -- matches content-reader prompt registration pattern */
7
8
  const zod_1 = require("zod");
8
9
  const schema_fields_js_1 = require("../../../tools/lib/schema-fields.js");
9
10
  const schema_fields_js_2 = require("../../../tools/semantic/schema-fields.js");
10
- const playbook_resources_js_1 = require("../../lib/playbook-resources.js");
11
+ const prompt_context_js_1 = require("../../lib/prompt-context.js");
12
+ const invariants_js_1 = require("./invariants.js");
11
13
  const playbooks_js_1 = require("./resources/playbooks.js");
12
- const userMessages = (0, playbook_resources_js_1.createPromptPlaybookEmbedder)({
14
+ const TOPIC_EXPLORE = 'explore';
15
+ const TOPIC_COMPOSE_COMPILE = 'compose-compile';
16
+ const bindPromptContext = (0, prompt_context_js_1.bindProfilePromptContext)({
17
+ invariants: invariants_js_1.SEMANTIC_LAYER_INVARIANTS,
13
18
  core: playbooks_js_1.SEMANTIC_LAYER_CORE_PLAYBOOK,
14
19
  topics: playbooks_js_1.SEMANTIC_LAYER_TOPIC_PLAYBOOKS,
20
+ topicMeta: playbooks_js_1.SEMANTIC_LAYER_TOPIC_META,
15
21
  });
16
- function registerSemanticLayerPrompts(server) {
22
+ function registerSemanticLayerPrompts(server, options) {
23
+ const promptContext = bindPromptContext(options === null || options === void 0 ? void 0 : options.promptContextPolicy);
24
+ const invariantIds = invariants_js_1.SEMANTIC_LAYER_DEFAULT_INVARIANT_IDS;
17
25
  server.registerPrompt('lightdash_semantic_explore', {
18
26
  title: 'Explore semantic layer',
19
27
  description: 'Locate explores, metrics, and dimensions for a question without running warehouse queries',
20
- argsSchema: zod_1.z.object({
28
+ argsSchema: {
21
29
  projectUuid: (0, schema_fields_js_1.projectUuidField)(),
22
30
  question: zod_1.z.string().optional().describe('Natural-language question or topic'),
23
- }),
31
+ },
24
32
  }, async ({ projectUuid, question }) => {
25
33
  const topic = question ? `Question/topic: ${question}.` : '';
26
- return userMessages(`Discover the Lightdash semantic layer for this project. Compile is out of scope unless asked.
34
+ return promptContext({
35
+ task: `Discover the Lightdash semantic layer for this project. Compile is out of scope unless asked.
27
36
 
28
37
  Project UUID (required on every tool): ${projectUuid}.
29
38
  ${topic}
30
39
 
31
- ${playbooks_js_1.SEMANTIC_LAYER_HARD_BANS}
32
-
33
40
  Procedure:
34
41
  1. get_project once to confirm name. Do not switch projects from org-wide list_projects.
35
42
  2. list_explores with search+limit (≤15). Disambiguate: skip empty schemaName / errors; prefer exact label or name __{table}; deprioritize eda_/reporting_ unless asked.
@@ -37,61 +44,65 @@ Procedure:
37
44
  4. get_explore → tables[baseTable].metrics only (≤8 names/labels). Skip list_metrics once explore is known. Skip get_metric / get_field_lineage unless needed.
38
45
  5. Deliverable: chosen explore (name/label/schemaName/databaseName + why) + field shortlist. Never dump full explore/dimension/metric/lineage payloads.
39
46
 
40
- Follow embedded playbooks (${playbooks_js_1.SEMANTIC_LAYER_CORE_URI}, ${playbooks_js_1.SEMANTIC_LAYER_EXPLORE_URI}). Use only lightdash_* tools.`, 'explore');
47
+ Use only lightdash_* tools.`,
48
+ invariantIds,
49
+ requiredTopics: [TOPIC_EXPLORE],
50
+ });
41
51
  });
42
52
  server.registerPrompt('lightdash_semantic_compose_compile', {
43
53
  title: 'Compose and compile query',
44
54
  description: 'Build a metric query and compile it with lightdash_compile_query; never execute against the warehouse',
45
- argsSchema: zod_1.z.object({
55
+ argsSchema: {
46
56
  projectUuid: (0, schema_fields_js_1.projectUuidField)(),
47
57
  question: zod_1.z.string().optional().describe('What the query should answer'),
48
58
  exploreId: (0, schema_fields_js_2.exploreIdField)().optional(),
49
- }),
59
+ },
50
60
  }, async ({ projectUuid, question, exploreId }) => {
51
61
  const topic = question ? `Goal: ${question}.` : '';
52
62
  const explore = exploreId ? `Preferred explore: ${exploreId}.` : '';
53
- return userMessages(`Compose a Lightdash metric query and compile it with lightdash_compile_query. Do not run the query.
63
+ return promptContext({
64
+ task: `Compose a Lightdash metric query and compile it with lightdash_compile_query. Do not run the query.
54
65
 
55
66
  Project UUID: ${projectUuid}.
56
67
  ${topic}
57
68
  ${explore}
58
69
 
59
- ${playbooks_js_1.SEMANTIC_LAYER_HARD_BANS}
60
-
61
70
  Procedure:
62
71
  1. If exploreId is missing, resolve it per explore playbook (search + disambiguation). Stay on this projectUuid.
63
72
  2. Copy fieldIds from list_dimensions and {exploreId}_{metricName} from get_explore → tables[baseTable].metrics. Never invent grains.
64
73
  3. If the user asked for N insights, reuse one explore and compile N diverse cuts.
65
74
  4. Build metricQuery from the compose-compile skeleton (fieldIds only; tool sets exploreName from exploreId and defaults missing tableCalculations to []). After each compile, verify every requested fieldId appears as a SELECT alias (missing alias = failure even without isError). Prefer SELECT aliases over metric name/label. ≤2 fix retries.
66
- 5. Deliverable: insight title(s) + fieldIds + compiled SQL (or errors). Never paste full explore/dimension/metric/lineage payloads.
67
-
68
- Follow embedded playbooks (${playbooks_js_1.SEMANTIC_LAYER_CORE_URI}, ${playbooks_js_1.SEMANTIC_LAYER_COMPOSE_COMPILE_URI}).`, 'compose-compile');
75
+ 5. Deliverable: insight title(s) + fieldIds + compiled SQL (or errors). Never paste full explore/dimension/metric/lineage payloads.`,
76
+ invariantIds,
77
+ requiredTopics: [TOPIC_COMPOSE_COMPILE],
78
+ });
69
79
  });
70
80
  server.registerPrompt('lightdash_semantic_compile_debug', {
71
81
  title: 'Debug compile errors',
72
82
  description: 'Interpret lightdash_compile_query failures, adjust the metric query, and re-compile',
73
- argsSchema: zod_1.z.object({
83
+ argsSchema: {
74
84
  projectUuid: (0, schema_fields_js_1.projectUuidField)(),
75
85
  exploreId: (0, schema_fields_js_2.exploreIdField)(),
76
86
  errorText: zod_1.z.string().optional().describe('Compile error text if already known'),
77
- }),
87
+ },
78
88
  }, async ({ projectUuid, exploreId, errorText }) => {
79
89
  const err = errorText ? `Known error: ${errorText}` : '';
80
- return userMessages(`Debug a failing lightdash_compile_query call and re-compile until it succeeds or you explain blockers.
90
+ return promptContext({
91
+ task: `Debug a failing lightdash_compile_query call and re-compile until it succeeds or you explain blockers.
81
92
 
82
93
  Project UUID: ${projectUuid}
83
94
  Explore: ${exploreId}
84
95
  ${err}
85
96
 
86
- ${playbooks_js_1.SEMANTIC_LAYER_HARD_BANS}
87
-
88
97
  Checklist:
89
98
  - unknown field id / empty SELECT / missing SELECT alias → use fieldIds from list_dimensions (base table) + explore-local metrics; re-compile (≤2 retries). Prefer SELECT aliases / compiledSql over metric name/label.
90
99
  - Other OpenAPI-required keys still failing (filters, sorts, limit, …) → copy the compose-compile skeleton; MCP fills exploreName and missing tableCalculations.
91
100
  - Wrong explore → re-disambiguate (schemaName; label or name __{table}; skip empty schema / eda unless asked).
92
101
  - Metric not found / catalog empty → get_explore tables[baseTable].metrics; tableName must be the full explore id; compile as {exploreId}_{metricName}.
93
- - Verify SELECT aliases after every compile. Stop after a good compile or a clear blocker.
94
-
95
- Follow embedded playbooks (${playbooks_js_1.SEMANTIC_LAYER_CORE_URI}, ${playbooks_js_1.SEMANTIC_LAYER_COMPOSE_COMPILE_URI}).`, 'compose-compile');
102
+ - Verify SELECT aliases after every compile. Stop after a good compile or a clear blocker.`,
103
+ invariantIds,
104
+ requiredTopics: [TOPIC_COMPOSE_COMPILE],
105
+ });
96
106
  });
97
107
  }
108
+ /* eslint-enable @typescript-eslint/no-deprecated */
@@ -3,11 +3,9 @@
3
3
  */
4
4
  import type { McpServer } from '@modelcontextprotocol/server';
5
5
  export type SemanticLayerPlaybookTopic = 'compose-compile' | 'explore';
6
- export declare const SEMANTIC_LAYER_CORE_URI: string;
7
- export declare const SEMANTIC_LAYER_EXPLORE_URI: string;
8
- export declare const SEMANTIC_LAYER_COMPOSE_COMPILE_URI: string;
9
- export declare const SEMANTIC_LAYER_HARD_BANS: string;
6
+ export { SEMANTIC_LAYER_HARD_BANS } from '../invariants.js';
10
7
  export declare const getAllPlaybookMarkdown: () => string;
11
8
  export declare const SEMANTIC_LAYER_CORE_PLAYBOOK: import("../../../lib/playbook-resources.js").EmbeddedPlaybook;
12
9
  export declare const SEMANTIC_LAYER_TOPIC_PLAYBOOKS: Readonly<Record<SemanticLayerPlaybookTopic, import("../../../lib/playbook-resources.js").EmbeddedPlaybook>>;
10
+ export declare const SEMANTIC_LAYER_TOPIC_META: Readonly<Record<SemanticLayerPlaybookTopic, import("../../../lib/playbook-resources.js").PromptTopicMeta>>;
13
11
  export declare function registerSemanticLayerPlaybook(server: McpServer): void;
@@ -3,14 +3,12 @@
3
3
  * Semantic-layer multi-playbook resources (core + topics + index).
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SEMANTIC_LAYER_TOPIC_PLAYBOOKS = exports.SEMANTIC_LAYER_CORE_PLAYBOOK = exports.getAllPlaybookMarkdown = exports.SEMANTIC_LAYER_HARD_BANS = exports.SEMANTIC_LAYER_COMPOSE_COMPILE_URI = exports.SEMANTIC_LAYER_EXPLORE_URI = exports.SEMANTIC_LAYER_CORE_URI = void 0;
6
+ exports.SEMANTIC_LAYER_TOPIC_META = exports.SEMANTIC_LAYER_TOPIC_PLAYBOOKS = exports.SEMANTIC_LAYER_CORE_PLAYBOOK = exports.getAllPlaybookMarkdown = exports.SEMANTIC_LAYER_HARD_BANS = void 0;
7
7
  exports.registerSemanticLayerPlaybook = registerSemanticLayerPlaybook;
8
8
  const playbook_resources_js_1 = require("../../../lib/playbook-resources.js");
9
9
  const playbooks = (0, playbook_resources_js_1.defineProfilePlaybooks)({
10
10
  profileId: 'semantic-layer',
11
11
  moduleDir: __dirname,
12
- /** Shared hard-ban text for prompts (keep in sync with playbooks/core.md Hard bans section). */
13
- hardBans: 'Do not run metric/SQL/chart queries, use SQL runner, trigger validation jobs, mutate content, switch away from the given projectUuid, invent fieldIds, dump full explore/metric/lineage payloads, or call AI/identity tools. Those are not available on this server.',
14
12
  coreDescription: 'Hard bans, budgets, allowed tools, project scope, and stop criteria',
15
13
  topics: [
16
14
  {
@@ -18,22 +16,25 @@ const playbooks = (0, playbook_resources_js_1.defineProfilePlaybooks)({
18
16
  title: 'Semantic-layer explore playbook',
19
17
  description: 'Explore discovery, disambiguation, and field shortlisting',
20
18
  file: 'explore.md',
19
+ useWhen: 'Discovering explores, metrics, and dimensions for a question',
20
+ priority: 0.8,
21
21
  },
22
22
  {
23
23
  id: 'compose-compile',
24
24
  title: 'Semantic-layer compose/compile playbook',
25
25
  description: 'Compose metric queries and compile without warehouse execution',
26
26
  file: 'compose-compile.md',
27
+ useWhen: 'Composing or debugging a metric query compile',
28
+ priority: 0.75,
27
29
  },
28
30
  ],
29
31
  });
30
- exports.SEMANTIC_LAYER_CORE_URI = playbooks.URIs.core;
31
- exports.SEMANTIC_LAYER_EXPLORE_URI = playbooks.URIs.topics.explore;
32
- exports.SEMANTIC_LAYER_COMPOSE_COMPILE_URI = playbooks.URIs.topics['compose-compile'];
33
- exports.SEMANTIC_LAYER_HARD_BANS = playbooks.HARD_BANS;
32
+ var invariants_js_1 = require("../invariants.js");
33
+ Object.defineProperty(exports, "SEMANTIC_LAYER_HARD_BANS", { enumerable: true, get: function () { return invariants_js_1.SEMANTIC_LAYER_HARD_BANS; } });
34
34
  exports.getAllPlaybookMarkdown = playbooks.getAllPlaybookMarkdown;
35
35
  exports.SEMANTIC_LAYER_CORE_PLAYBOOK = playbooks.CORE_PLAYBOOK;
36
36
  exports.SEMANTIC_LAYER_TOPIC_PLAYBOOKS = playbooks.TOPIC_PLAYBOOKS;
37
+ exports.SEMANTIC_LAYER_TOPIC_META = playbooks.TOPIC_META;
37
38
  function registerSemanticLayerPlaybook(server) {
38
39
  playbooks.registerPlaybooks(server);
39
40
  }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Cross-profile prompt-context budget gates (deterministic; RFC).
3
+ * Specs come from production builders — not abbreviated stubs.
4
+ */
5
+ export {};
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ /**
3
+ * Cross-profile prompt-context budget gates (deterministic; RFC).
4
+ * Specs come from production builders — not abbreviated stubs.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const vitest_1 = require("vitest");
8
+ const invariants_js_1 = require("../content-developer/v1/invariants.js");
9
+ const prompt_specs_js_1 = require("../content-developer/v1/prompt-specs.js");
10
+ const playbooks_js_1 = require("../content-developer/v1/resources/playbooks.js");
11
+ const invariants_js_2 = require("../content-reader/v1/invariants.js");
12
+ const prompt_specs_js_2 = require("../content-reader/v1/prompt-specs.js");
13
+ const playbooks_js_2 = require("../content-reader/v1/resources/playbooks.js");
14
+ const prompt_context_js_1 = require("../lib/prompt-context.js");
15
+ const SCENARIOS = [
16
+ {
17
+ profile: 'content-reader',
18
+ prompt: 'find_content',
19
+ invariants: invariants_js_2.CONTENT_READER_INVARIANTS,
20
+ core: playbooks_js_2.CONTENT_READER_CORE_PLAYBOOK,
21
+ topics: playbooks_js_2.CONTENT_READER_TOPIC_PLAYBOOKS,
22
+ topicMeta: playbooks_js_2.CONTENT_READER_TOPIC_META,
23
+ spec: (0, prompt_specs_js_2.buildFindContentPromptSpec)({
24
+ question: 'revenue by region',
25
+ projectUuid: 'pin',
26
+ verifiedOnly: false,
27
+ }),
28
+ },
29
+ {
30
+ profile: 'content-developer',
31
+ prompt: 'create_dashboard',
32
+ invariants: invariants_js_1.CONTENT_DEVELOPER_INVARIANTS,
33
+ core: playbooks_js_1.CONTENT_DEVELOPER_CORE_PLAYBOOK,
34
+ topics: playbooks_js_1.CONTENT_DEVELOPER_TOPIC_PLAYBOOKS,
35
+ topicMeta: playbooks_js_1.CONTENT_DEVELOPER_TOPIC_META,
36
+ spec: (0, prompt_specs_js_1.buildCreateDashboardPromptSpec)({
37
+ goal: 'executive revenue overview',
38
+ projectUuid: 'pin',
39
+ }),
40
+ },
41
+ ];
42
+ function metricsForScenario(scenario) {
43
+ const bind = (0, prompt_context_js_1.bindProfilePromptContext)({
44
+ invariants: scenario.invariants,
45
+ core: scenario.core,
46
+ topics: scenario.topics,
47
+ topicMeta: scenario.topicMeta,
48
+ });
49
+ const byPolicy = {};
50
+ for (const policy of ['compact', 'compatible', 'embedded']) {
51
+ byPolicy[policy] = (0, prompt_context_js_1.measurePromptMessages)(bind(policy)(scenario.spec).messages);
52
+ }
53
+ return byPolicy;
54
+ }
55
+ (0, vitest_1.describe)('prompt context budgets', () => {
56
+ for (const scenario of SCENARIOS) {
57
+ (0, vitest_1.it)(`${scenario.profile}/${scenario.prompt}: compact has no embeds and beats embedded by ≥40%`, () => {
58
+ const { compact, embedded } = metricsForScenario(scenario);
59
+ (0, vitest_1.expect)(compact.embeddedResourceCount).toBe(0);
60
+ (0, vitest_1.expect)(embedded.embeddedResourceCount).toBeGreaterThan(0);
61
+ const reduction = 1 - compact.totalChars / embedded.totalChars;
62
+ (0, vitest_1.expect)(reduction).toBeGreaterThanOrEqual(0.4);
63
+ (0, vitest_1.expect)((0, prompt_context_js_1.approxTokensFromChars)(compact.totalChars)).toBeLessThanOrEqual(1500);
64
+ });
65
+ (0, vitest_1.it)(`${scenario.profile}/${scenario.prompt}: compatible embeds only required topics`, () => {
66
+ var _a, _b;
67
+ const { compatible, embedded } = metricsForScenario(scenario);
68
+ (0, vitest_1.expect)(compatible.embeddedResourceCount).toBe((_b = (_a = scenario.spec.requiredTopics) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0);
69
+ (0, vitest_1.expect)(compatible.totalChars).toBeLessThan(embedded.totalChars);
70
+ });
71
+ }
72
+ });
@@ -1,10 +1,15 @@
1
1
  /**
2
2
  * Profile packaging types — tools are ToolModules imported by each profile.
3
3
  */
4
+ import type { PromptContextPolicy } from '../config/prompt-context-policy.js';
4
5
  import type { ToolModule } from '../tools/types.js';
5
6
  import type { ProfileId } from '@lightdash-tools/common';
6
7
  import type { McpServer } from '@modelcontextprotocol/server';
7
8
  export type { ProfileId };
9
+ export type RegisterPromptsOptions = {
10
+ /** Progressive-disclosure playbook embedding policy. */
11
+ promptContextPolicy?: PromptContextPolicy;
12
+ };
8
13
  export type ProfileDefinition = {
9
14
  id: ProfileId;
10
15
  /** Fixed Streamable HTTP MCP endpoint path for this profile. */
@@ -18,6 +23,6 @@ export type ProfileDefinition = {
18
23
  * Mounted tools for this profile (import ToolModules; array order is tools/list order).
19
24
  */
20
25
  tools: readonly ToolModule[];
21
- registerPrompts: (server: McpServer) => void;
26
+ registerPrompts: (server: McpServer, options?: RegisterPromptsOptions) => void;
22
27
  registerResources: (server: McpServer) => void;
23
28
  };
@@ -1,12 +1,15 @@
1
1
  /**
2
2
  * Registers MCP capabilities for a profile.
3
3
  */
4
+ import { type PromptContextPolicy } from '../config/prompt-context-policy.js';
4
5
  import type { McpContextProvider } from './request-context.js';
5
6
  import type { ProfileDefinition } from '../profiles/types.js';
6
7
  import type { McpServer } from '@modelcontextprotocol/server';
7
8
  export type RegisterCapabilitiesOptions = {
8
9
  /** Profile to register (defaults to {@link getDefaultProfile}). */
9
10
  profile?: ProfileDefinition;
11
+ /** Progressive-disclosure prompt context policy (defaults to package default). */
12
+ promptContextPolicy?: PromptContextPolicy;
10
13
  };
11
14
  /**
12
15
  * Registers MCP capabilities for the given profile.
@@ -5,6 +5,7 @@
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.registerCapabilities = registerCapabilities;
7
7
  const server_profile_js_1 = require("../audit/server-profile.js");
8
+ const prompt_context_policy_js_1 = require("../config/prompt-context-policy.js");
8
9
  const index_js_1 = require("../profiles/index.js");
9
10
  const registry_js_1 = require("../tools/registry.js");
10
11
  /**
@@ -12,10 +13,11 @@ const registry_js_1 = require("../tools/registry.js");
12
13
  * Tools come from profile.tools (ToolModule imports).
13
14
  */
14
15
  function registerCapabilities(server, contextProvider, options) {
15
- var _a;
16
+ var _a, _b;
16
17
  const profile = (_a = options === null || options === void 0 ? void 0 : options.profile) !== null && _a !== void 0 ? _a : (0, index_js_1.getDefaultProfile)();
18
+ const promptContextPolicy = (_b = options === null || options === void 0 ? void 0 : options.promptContextPolicy) !== null && _b !== void 0 ? _b : prompt_context_policy_js_1.DEFAULT_PROMPT_CONTEXT_POLICY;
17
19
  (0, server_profile_js_1.bindServerProfile)(server, profile.id);
18
20
  (0, registry_js_1.registerTools)(server, contextProvider, profile.tools);
19
- profile.registerPrompts(server);
21
+ profile.registerPrompts(server, { promptContextPolicy });
20
22
  profile.registerResources(server);
21
23
  }
@@ -1,5 +1,9 @@
1
1
  import { z } from 'zod';
2
2
  export declare const PROJECT_UUID_DESC = "Project UUID";
3
+ /** Prompt-body hint when projectUuid arg is omitted (HTTP pin or PROJECT_SCOPE_REQUIRED). */
4
+ export declare const PROMPT_PROJECT_UUID_HINT: "(pass on every tool, or use HTTP pin \u2014 else PROJECT_SCOPE_REQUIRED)";
5
+ /** Eager prompt line for optional projectUuid (HTTP pin or ask). */
6
+ export declare function formatPromptProjectUuidLine(projectUuid?: string): string;
3
7
  export declare const projectUuidField: () => z.ZodString;
4
8
  /** Optional projectUuid when HTTP pin (`X-Lightdash-Project`) can resolve scope. */
5
9
  export declare const optionalProjectUuidField: () => z.ZodOptional<z.ZodString>;
@@ -1,8 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.allowedEmailDomainsField = exports.includeEmailField = exports.uuidOrSlugField = exports.optionalProjectUuidField = exports.projectUuidField = exports.PROJECT_UUID_DESC = void 0;
3
+ exports.allowedEmailDomainsField = exports.includeEmailField = exports.uuidOrSlugField = exports.optionalProjectUuidField = exports.projectUuidField = exports.PROMPT_PROJECT_UUID_HINT = exports.PROJECT_UUID_DESC = void 0;
4
+ exports.formatPromptProjectUuidLine = formatPromptProjectUuidLine;
4
5
  const zod_1 = require("zod");
5
6
  exports.PROJECT_UUID_DESC = 'Project UUID';
7
+ /** Prompt-body hint when projectUuid arg is omitted (HTTP pin or PROJECT_SCOPE_REQUIRED). */
8
+ exports.PROMPT_PROJECT_UUID_HINT = '(pass on every tool, or use HTTP pin — else PROJECT_SCOPE_REQUIRED)';
9
+ /** Eager prompt line for optional projectUuid (HTTP pin or ask). */
10
+ function formatPromptProjectUuidLine(projectUuid) {
11
+ return `Project UUID: ${projectUuid !== null && projectUuid !== void 0 ? projectUuid : exports.PROMPT_PROJECT_UUID_HINT}.`;
12
+ }
6
13
  const projectUuidField = () => zod_1.z.string().describe(exports.PROJECT_UUID_DESC);
7
14
  exports.projectUuidField = projectUuidField;
8
15
  /** Optional projectUuid when HTTP pin (`X-Lightdash-Project`) can resolve scope. */
@@ -257,7 +257,7 @@ function registerPreviewContentMove(server, contextProvider) {
257
257
  isNotFound: api_errors_js_1.isNotFoundError,
258
258
  });
259
259
  if (resolved.kind === 'error') {
260
- return (0, reader_tool_helpers_js_1.codedErrorResult)(resolved.error.code, resolved.error.message);
260
+ return (0, content_developer_js_1.developerCodedErrorResult)(resolved.error.code, resolved.error.message);
261
261
  }
262
262
  const resourceKey = (0, developer_helpers_js_1.buildMoveContentResourceKey)(args.itemUuids);
263
263
  const proposed = (0, developer_helpers_js_1.buildMoveContentProposal)({
@@ -283,7 +283,7 @@ function registerDuplicateChart(server, contextProvider) {
283
283
  }
284
284
  const sourceBaseline = (0, developer_helpers_js_1.baselineFromResource)(sourceRecordAfter);
285
285
  if ((sourceBaselineBefore === null || sourceBaselineBefore === void 0 ? void 0 : sourceBaselineBefore.updatedAt) !== (sourceBaseline === null || sourceBaseline === void 0 ? void 0 : sourceBaseline.updatedAt)) {
286
- return (0, reader_tool_helpers_js_1.codedErrorResult)('PREVIEW_STALE', `Source chart '${args.sourceChartUuidOrSlug}' changed while reading as-code; re-run preview -> confirm`);
286
+ return (0, content_developer_js_1.developerCodedErrorResult)('PREVIEW_STALE', `Source chart '${args.sourceChartUuidOrSlug}' changed while reading as-code; re-run preview -> confirm`);
287
287
  }
288
288
  const targetBaseline = await (0, developer_helpers_js_1.fetchChartBaselineOptional)({
289
289
  chartUuidOrSlug: args.newSlug,
@@ -550,7 +550,7 @@ function registerMoveContent(server, contextProvider) {
550
550
  isNotFound: api_errors_js_1.isNotFoundError,
551
551
  });
552
552
  if (resolved.kind === 'error') {
553
- return (0, reader_tool_helpers_js_1.codedErrorResult)(resolved.error.code, resolved.error.message);
553
+ return (0, content_developer_js_1.developerCodedErrorResult)(resolved.error.code, resolved.error.message);
554
554
  }
555
555
  const resourceKey = (0, developer_helpers_js_1.buildMoveContentResourceKey)(args.itemUuids);
556
556
  const proposed = (0, developer_helpers_js_1.buildMoveContentProposal)({
@@ -4,8 +4,8 @@
4
4
  */
5
5
  import type { NormalizedQueryResult } from './result-normalizer.js';
6
6
  import type { ContentReaderWarning } from '../../policy/envelope.js';
7
- import type { TextContent } from '../shared.js';
8
- export declare function codedErrorResult(code: string, message: string): TextContent;
7
+ import type { TextContent, ToolErrorExtras } from '../shared.js';
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;
11
11
  export declare function warningFromNormalizedMessage(message: string): ContentReaderWarning;
@@ -32,8 +32,8 @@ const BLOCKED_POLICY_CODES = new Set([
32
32
  'PREVIEW_NOT_OWNED',
33
33
  'CHART_SLUG_EXISTS',
34
34
  ]);
35
- function codedErrorResult(code, message) {
36
- const result = (0, shared_js_1.toolErrorResult)(code, message);
35
+ function codedErrorResult(code, message, extras) {
36
+ const result = (0, shared_js_1.toolErrorResult)(code, message, extras);
37
37
  if (BLOCKED_POLICY_CODES.has(code)) {
38
38
  return (0, shared_js_1.withLightdashBlockedMarker)(result);
39
39
  }
@@ -28,6 +28,7 @@ const reader_tool_helpers_js_1 = require("./reader-tool-helpers.js");
28
28
  'QUERY_BUDGET_EXCEEDED',
29
29
  'ROW_LIMIT_EXCEEDED',
30
30
  'CHART_SLUG_EXISTS',
31
+ 'PREVIEW_STALE',
31
32
  ]) {
32
33
  const result = (0, reader_tool_helpers_js_1.codedErrorResult)(code, 'denied');
33
34
  (0, vitest_1.expect)(result.isError).toBe(true);
@@ -35,8 +35,13 @@ export type TextContent = {
35
35
  export type ToolResult = InputRequiredResult | TextContent;
36
36
  /** Builds a tool result with JSON text and matching structuredContent. */
37
37
  export declare function jsonToolResult(data: unknown): TextContent;
38
+ /** Optional additive fields on structured tool errors (RFC progressive-disclosure recovery). */
39
+ export type ToolErrorExtras = {
40
+ recovery?: string;
41
+ playbookUri?: string;
42
+ };
38
43
  /** Tool execution error with structured `{ error: { code, message } }` (not policy-blocked). */
39
- export declare function toolErrorResult(code: string, message: string): TextContent;
44
+ export declare function toolErrorResult(code: string, message: string, extras?: ToolErrorExtras): TextContent;
40
45
  /**
41
46
  * MCP ImageContent + metadata text. structuredContent holds meta only (no base64).
42
47
  * Spec: https://modelcontextprotocol.io/specification/2025-11-25/server/tools
@@ -47,8 +47,18 @@ function jsonToolResult(data) {
47
47
  };
48
48
  }
49
49
  /** Tool execution error with structured `{ error: { code, message } }` (not policy-blocked). */
50
- function toolErrorResult(code, message) {
51
- return Object.assign(Object.assign({}, jsonToolResult({ error: { code, message } })), { isError: true });
50
+ function toolErrorResult(code, message, extras) {
51
+ const error = {
52
+ code,
53
+ message,
54
+ };
55
+ if ((extras === null || extras === void 0 ? void 0 : extras.recovery) !== undefined) {
56
+ error.recovery = extras.recovery;
57
+ }
58
+ if ((extras === null || extras === void 0 ? void 0 : extras.playbookUri) !== undefined) {
59
+ error.playbookUri = extras.playbookUri;
60
+ }
61
+ return Object.assign(Object.assign({}, jsonToolResult({ error })), { isError: true });
52
62
  }
53
63
  /**
54
64
  * MCP ImageContent + metadata text. structuredContent holds meta only (no base64).
@@ -35,7 +35,10 @@ function createProcessMcpHttpHandler() {
35
35
  if (!store) {
36
36
  throw new Error('MCP request factory context is missing');
37
37
  }
38
- return (0, server_js_1.createLightdashMcpServer)(store.contextProvider, { profile: store.profile });
38
+ return (0, server_js_1.createLightdashMcpServer)(store.contextProvider, {
39
+ profile: store.profile,
40
+ promptContextPolicy: store.promptContextPolicy,
41
+ });
39
42
  }, { legacy: 'stateless', onerror: reportMcpHttpError });
40
43
  }
41
44
  function listen(server, port, host) {
@@ -168,7 +171,11 @@ async function handleMcpPost(ctx) {
168
171
  }
169
172
  const contextProvider = createContextProviderForRequest(config, req);
170
173
  const auditAuth = getOAuthAuditContext(req);
171
- await (0, mcp_post_factory_context_js_1.runWithMcpPostFactoryAsync)({ contextProvider, profile }, () => (0, tool_audit_context_js_1.runWithToolAuditAuthAsync)(auditAuth, () => nodeHandler(req, res, body)));
174
+ await (0, mcp_post_factory_context_js_1.runWithMcpPostFactoryAsync)({
175
+ contextProvider,
176
+ profile,
177
+ promptContextPolicy: config.promptContextPolicy,
178
+ }, () => (0, tool_audit_context_js_1.runWithToolAuditAuthAsync)(auditAuth, () => nodeHandler(req, res, body)));
172
179
  }
173
180
  async function createStreamableHttpServer(config) {
174
181
  var _a;
@@ -225,7 +232,7 @@ function startStreamableHttpServer(config) {
225
232
  const paths = (0, enabled_profiles_js_1.listEnabledProfilePaths)(httpConfig.enabledProfiles)
226
233
  .map((p) => `${baseUrl}${p}`)
227
234
  .join(', ');
228
- console.error(`Lightdash MCP server listening on ${paths} (auth: ${httpConfig.authMode})`);
235
+ console.error(`Lightdash MCP server listening on ${paths} (auth: ${httpConfig.authMode}; prompt-context=${httpConfig.promptContextPolicy})`);
229
236
  if (httpConfig.authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH) {
230
237
  console.error(`OAuth PRM: ${(0, oauth_protected_resource_js_1.getProtectedResourceMetadataUrl)(httpConfig)}`);
231
238
  console.error(`OAuth callback (register in Lightdash): ${(0, load_mcp_config_js_1.getOAuthCallbackUrl)(httpConfig)}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightdash-tools/mcp",
3
- "version": "0.14.0",
3
+ "version": "0.16.1",
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.14.0",
28
- "@lightdash-tools/common": "0.14.0"
27
+ "@lightdash-tools/client": "0.16.1",
28
+ "@lightdash-tools/common": "0.16.1"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@modelcontextprotocol/client": "2.0.0",