@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
@@ -5,6 +5,8 @@
5
5
  import type { ProfileId } from '../types.js';
6
6
  import type { McpServer } from '@modelcontextprotocol/server';
7
7
  export declare const PLAYBOOK_MIME: "text/markdown";
8
+ /** Long TTL for static shipped playbooks (package deploy changes content). */
9
+ export declare const STATIC_PLAYBOOK_CACHE_TTL_MS = 86400000;
8
10
  export type PlaybookResourceSpec = {
9
11
  /** MCP resource name (stable id for resources/list). */
10
12
  name: string;
@@ -13,49 +15,35 @@ export type PlaybookResourceSpec = {
13
15
  title: string;
14
16
  description: string;
15
17
  getMarkdown: () => string;
18
+ /** MCP resource priority annotation (0–1). */
19
+ priority?: number;
16
20
  };
17
21
  export type EmbeddedPlaybook = {
18
22
  uri: string;
19
- mimeType?: string;
23
+ /** Short description for manifests (core playbook). */
24
+ description?: string;
20
25
  getMarkdown: () => string;
21
26
  };
22
- declare function embedResource(playbook: EmbeddedPlaybook): {
23
- type: "resource";
24
- resource: {
25
- uri: string;
26
- mimeType: string;
27
- text: string;
28
- };
29
- };
30
- type PromptUserMessage = {
31
- role: 'user';
32
- content: ReturnType<typeof embedResource> | {
33
- type: 'text';
34
- text: string;
35
- };
36
- };
37
- /**
38
- * Build prompt message helpers that embed core, and optionally one or more topic
39
- * playbooks, after the user text message. When `topicId` is omitted, only core is
40
- * embedded.
41
- */
42
- export declare function createPromptPlaybookEmbedder<TopicId extends string>(options: {
43
- core: EmbeddedPlaybook;
44
- topics: Readonly<Record<TopicId, EmbeddedPlaybook>>;
45
- }): (text: string, topicId?: TopicId | readonly TopicId[]) => {
46
- messages: PromptUserMessage[];
27
+ export type PromptTopicMeta = {
28
+ description: string;
29
+ useWhen?: string;
47
30
  };
31
+ /** Canonical playbook topic URI (shared by registration and tool recovery hints). */
32
+ export declare function playbookTopicUri(profileId: ProfileId, topicId: string): string;
48
33
  export type ProfilePlaybookTopicDef<TopicId extends string = string> = {
49
34
  id: TopicId;
50
35
  title: string;
51
36
  description: string;
52
37
  /** Filename under `playbooks/`, e.g. `dashboards.md`. */
53
38
  file: string;
39
+ /** MCP resource priority (default 0.7; recovery ~0.3; core ~0.9). */
40
+ priority?: number;
41
+ /** Short "use when" for prompt manifests. */
42
+ useWhen?: string;
54
43
  };
55
44
  export type DefineProfilePlaybooksOptions<TopicId extends string> = {
56
45
  profileId: ProfileId;
57
46
  moduleDir: string;
58
- hardBans: string;
59
47
  topics: readonly ProfilePlaybookTopicDef<TopicId>[];
60
48
  indexTitle?: string;
61
49
  indexDescription?: string;
@@ -67,15 +55,9 @@ export type DefineProfilePlaybooksOptions<TopicId extends string> = {
67
55
  * Callers re-export the returned fields under profile-specific names.
68
56
  */
69
57
  export declare function defineProfilePlaybooks<TopicId extends string>(options: DefineProfilePlaybooksOptions<TopicId>): {
70
- URIs: {
71
- index: string;
72
- core: string;
73
- topics: Readonly<Record<TopicId, string>>;
74
- };
75
- HARD_BANS: string;
76
58
  getAllPlaybookMarkdown: () => string;
77
59
  CORE_PLAYBOOK: EmbeddedPlaybook;
78
60
  TOPIC_PLAYBOOKS: Readonly<Record<TopicId, EmbeddedPlaybook>>;
61
+ TOPIC_META: Readonly<Record<TopicId, PromptTopicMeta>>;
79
62
  registerPlaybooks: (server: McpServer) => void;
80
63
  };
81
- export {};
@@ -4,12 +4,14 @@
4
4
  * embedding core + topic playbooks into prompt messages.
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.PLAYBOOK_MIME = void 0;
8
- exports.createPromptPlaybookEmbedder = createPromptPlaybookEmbedder;
7
+ exports.STATIC_PLAYBOOK_CACHE_TTL_MS = exports.PLAYBOOK_MIME = void 0;
8
+ exports.playbookTopicUri = playbookTopicUri;
9
9
  exports.defineProfilePlaybooks = defineProfilePlaybooks;
10
10
  const node_fs_1 = require("node:fs");
11
11
  const node_path_1 = require("node:path");
12
12
  exports.PLAYBOOK_MIME = 'text/markdown';
13
+ /** Long TTL for static shipped playbooks (package deploy changes content). */
14
+ exports.STATIC_PLAYBOOK_CACHE_TTL_MS = 86400000; // 24h
13
15
  const markdownCache = new Map();
14
16
  /**
15
17
  * Load a playbook markdown file from a directory adjacent to the compiled module.
@@ -27,12 +29,22 @@ function loadPlaybookMarkdown(moduleDir, relativePath) {
27
29
  return text;
28
30
  }
29
31
  function registerMarkdownPlaybooks(server, specs) {
32
+ var _a;
30
33
  for (const spec of specs) {
31
34
  const markdown = spec.getMarkdown();
35
+ const priority = (_a = spec.priority) !== null && _a !== void 0 ? _a : 0.7;
32
36
  server.registerResource(spec.name, spec.uri, {
33
37
  title: spec.title,
34
38
  description: spec.description,
35
39
  mimeType: exports.PLAYBOOK_MIME,
40
+ annotations: {
41
+ audience: ['assistant'],
42
+ priority,
43
+ },
44
+ cacheHint: {
45
+ cacheScope: 'public',
46
+ ttlMs: exports.STATIC_PLAYBOOK_CACHE_TTL_MS,
47
+ },
36
48
  }, async (uri) => ({
37
49
  contents: [
38
50
  {
@@ -44,52 +56,9 @@ function registerMarkdownPlaybooks(server, specs) {
44
56
  }));
45
57
  }
46
58
  }
47
- function embedResource(playbook) {
48
- var _a;
49
- return {
50
- type: 'resource',
51
- resource: {
52
- uri: playbook.uri,
53
- mimeType: (_a = playbook.mimeType) !== null && _a !== void 0 ? _a : exports.PLAYBOOK_MIME,
54
- text: playbook.getMarkdown(),
55
- },
56
- };
57
- }
58
- /**
59
- * Build prompt message helpers that embed core, and optionally one or more topic
60
- * playbooks, after the user text message. When `topicId` is omitted, only core is
61
- * embedded.
62
- */
63
- function createPromptPlaybookEmbedder(options) {
64
- const { core, topics } = options;
65
- return (text, topicId) => {
66
- const messages = [
67
- {
68
- role: 'user',
69
- content: { type: 'text', text },
70
- },
71
- {
72
- role: 'user',
73
- content: embedResource(core),
74
- },
75
- ];
76
- if (topicId === undefined) {
77
- return { messages };
78
- }
79
- const topicIds = typeof topicId === 'string' ? [topicId] : topicId;
80
- for (const id of topicIds) {
81
- // eslint-disable-next-line security/detect-object-injection -- topic ids from profile prompt constants
82
- const topic = topics[id];
83
- if (!topic) {
84
- throw new Error(`Unknown playbook topic '${id}'`);
85
- }
86
- messages.push({
87
- role: 'user',
88
- content: embedResource(topic),
89
- });
90
- }
91
- return { messages };
92
- };
59
+ /** Canonical playbook topic URI (shared by registration and tool recovery hints). */
60
+ function playbookTopicUri(profileId, topicId) {
61
+ return `lightdash://playbooks/${profileId}/${topicId}`;
93
62
  }
94
63
  /** Title-case the first segment only: `content-developer` → `Content-developer`. */
95
64
  function titleCaseProfile(profileId) {
@@ -104,28 +73,32 @@ function titleCaseProfile(profileId) {
104
73
  * Callers re-export the returned fields under profile-specific names.
105
74
  */
106
75
  function defineProfilePlaybooks(options) {
107
- const { profileId, moduleDir, hardBans, topics, indexTitle = `${titleCaseProfile(profileId)} playbooks`, indexDescription = `Index of ${profileId} workflow playbooks (core + topics)`, coreTitle = `${titleCaseProfile(profileId)} core playbook`, coreDescription = 'Hard bans, tools, and operating rules', } = options;
76
+ const { profileId, moduleDir, topics, indexTitle = `${titleCaseProfile(profileId)} playbooks`, indexDescription = `Index of ${profileId} workflow playbooks (core + topics)`, coreTitle = `${titleCaseProfile(profileId)} core playbook`, coreDescription = 'Hard bans, tools, and operating rules', } = options;
108
77
  const indexUri = `lightdash://playbooks/${profileId}`;
109
- const coreUri = `lightdash://playbooks/${profileId}/core`;
78
+ const coreUri = playbookTopicUri(profileId, 'core');
110
79
  const namePrefix = profileId.split('-').join('_');
111
80
  const load = (relativePath) => loadPlaybookMarkdown(moduleDir, relativePath);
112
81
  const getIndexPlaybookMarkdown = () => load('playbooks/index.md');
113
82
  const getCorePlaybookMarkdown = () => load('playbooks/core.md');
114
- const topicUris = {};
115
83
  const topicPlaybooks = {};
84
+ const topicMeta = {};
116
85
  const topicMarkdownGetters = [];
117
86
  for (const topic of topics) {
118
- const uri = `lightdash://playbooks/${profileId}/${topic.id}`;
119
- topicUris[topic.id] = uri;
87
+ const uri = playbookTopicUri(profileId, topic.id);
120
88
  const getMarkdown = () => load(`playbooks/${topic.file}`);
121
89
  topicMarkdownGetters.push(getMarkdown);
122
90
  topicPlaybooks[topic.id] = {
123
91
  uri,
124
92
  getMarkdown,
125
93
  };
94
+ topicMeta[topic.id] = {
95
+ description: topic.description,
96
+ useWhen: topic.useWhen,
97
+ };
126
98
  }
127
99
  const CORE_PLAYBOOK = {
128
100
  uri: coreUri,
101
+ description: coreDescription,
129
102
  getMarkdown: getCorePlaybookMarkdown,
130
103
  };
131
104
  const getAllPlaybookMarkdown = () => [
@@ -133,37 +106,43 @@ function defineProfilePlaybooks(options) {
133
106
  getCorePlaybookMarkdown(),
134
107
  ...topicMarkdownGetters.map((g) => g()),
135
108
  ].join('\n');
136
- const registerPlaybooks = (server) => {
137
- registerMarkdownPlaybooks(server, [
138
- {
139
- name: `${namePrefix}_playbook_index`,
140
- uri: indexUri,
141
- title: indexTitle,
142
- description: indexDescription,
143
- getMarkdown: getIndexPlaybookMarkdown,
144
- },
145
- {
146
- name: `${namePrefix}_playbook_core`,
147
- uri: coreUri,
148
- title: coreTitle,
149
- description: coreDescription,
150
- getMarkdown: getCorePlaybookMarkdown,
151
- },
152
- ...topics.map((topic) => ({
153
- name: `${namePrefix}_playbook_${String(topic.id).split('-').join('_')}`,
154
- uri: topicUris[topic.id],
109
+ const resourceSpecs = [
110
+ {
111
+ name: `${namePrefix}_playbook_index`,
112
+ uri: indexUri,
113
+ title: indexTitle,
114
+ description: indexDescription,
115
+ getMarkdown: getIndexPlaybookMarkdown,
116
+ priority: 0.85,
117
+ },
118
+ {
119
+ name: `${namePrefix}_playbook_core`,
120
+ uri: coreUri,
121
+ title: coreTitle,
122
+ description: coreDescription,
123
+ getMarkdown: getCorePlaybookMarkdown,
124
+ priority: 0.95,
125
+ },
126
+ ...topics.map((topic) => {
127
+ var _a;
128
+ return ({
129
+ name: `${namePrefix}_playbook_${String(topic.id).split('/').join('_').split('-').join('_')}`,
130
+ uri: topicPlaybooks[topic.id].uri,
155
131
  title: topic.title,
156
132
  description: topic.description,
157
133
  getMarkdown: topicPlaybooks[topic.id].getMarkdown,
158
- })),
159
- ]);
134
+ priority: (_a = topic.priority) !== null && _a !== void 0 ? _a : (String(topic.id).startsWith('recovery/') ? 0.35 : 0.7),
135
+ });
136
+ }),
137
+ ];
138
+ const registerPlaybooks = (server) => {
139
+ registerMarkdownPlaybooks(server, resourceSpecs);
160
140
  };
161
141
  return {
162
- URIs: { index: indexUri, core: coreUri, topics: topicUris },
163
- HARD_BANS: hardBans,
164
142
  getAllPlaybookMarkdown,
165
143
  CORE_PLAYBOOK,
166
144
  TOPIC_PLAYBOOKS: topicPlaybooks,
145
+ TOPIC_META: topicMeta,
167
146
  registerPlaybooks,
168
147
  };
169
148
  }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Progressive-disclosure prompt context composer (RFC: token-efficient MCP prompts).
3
+ */
4
+ import { type PromptContextPolicy } from '../../config/prompt-context-policy.js';
5
+ import { type EmbeddedPlaybook, type PromptTopicMeta } from './playbook-resources.js';
6
+ import { type PromptInvariant } from './prompt-invariants.js';
7
+ export declare const MANIFEST_HEADER: "Detailed resources:";
8
+ export type PromptContextSpec<TopicId extends string> = {
9
+ task: string;
10
+ invariantIds: readonly string[];
11
+ /** Embedded under compatible + embedded; listed in compact manifest. */
12
+ requiredTopics?: readonly TopicId[];
13
+ conditionalTopics?: readonly {
14
+ topic: TopicId;
15
+ when?: string;
16
+ }[];
17
+ recoveryTopics?: readonly {
18
+ topic: TopicId;
19
+ when?: string;
20
+ }[];
21
+ };
22
+ type PromptTextContent = {
23
+ type: 'text';
24
+ text: string;
25
+ };
26
+ type PromptResourceContent = {
27
+ type: 'resource';
28
+ resource: {
29
+ uri: string;
30
+ mimeType: string;
31
+ text: string;
32
+ };
33
+ };
34
+ export type PromptUserMessage = {
35
+ role: 'user';
36
+ content: PromptResourceContent | PromptTextContent;
37
+ };
38
+ /**
39
+ * Build a prompts/get composer for a profile under a fixed context policy.
40
+ */
41
+ export declare function createPromptContextComposer<TopicId extends string>(options: {
42
+ policy: PromptContextPolicy;
43
+ invariants: readonly PromptInvariant[];
44
+ core: EmbeddedPlaybook;
45
+ topics: Readonly<Record<TopicId, EmbeddedPlaybook>>;
46
+ topicMeta: Readonly<Record<TopicId, PromptTopicMeta>>;
47
+ }): (spec: PromptContextSpec<TopicId>) => {
48
+ messages: PromptUserMessage[];
49
+ };
50
+ /** Profile-local binder: `const compose = bindProfilePromptContext(deps)(policy)`. */
51
+ export declare function bindProfilePromptContext<TopicId extends string>(deps: {
52
+ invariants: readonly PromptInvariant[];
53
+ core: EmbeddedPlaybook;
54
+ topics: Readonly<Record<TopicId, EmbeddedPlaybook>>;
55
+ topicMeta: Readonly<Record<TopicId, PromptTopicMeta>>;
56
+ }): (policy?: PromptContextPolicy) => (spec: PromptContextSpec<TopicId>) => {
57
+ messages: PromptUserMessage[];
58
+ };
59
+ /** Approx token estimate: ceil(chars / 4). */
60
+ export declare function approxTokensFromChars(chars: number): number;
61
+ export type PromptContextMetrics = {
62
+ taskChars: number;
63
+ invariantChars: number;
64
+ manifestChars: number;
65
+ embeddedResourceChars: number;
66
+ totalChars: number;
67
+ approxTotalTokens: number;
68
+ embeddedResourceCount: number;
69
+ };
70
+ export declare function measurePromptMessages(messages: readonly PromptUserMessage[]): PromptContextMetrics;
71
+ export {};
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ /**
3
+ * Progressive-disclosure prompt context composer (RFC: token-efficient MCP prompts).
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MANIFEST_HEADER = void 0;
7
+ exports.createPromptContextComposer = createPromptContextComposer;
8
+ exports.bindProfilePromptContext = bindProfilePromptContext;
9
+ exports.approxTokensFromChars = approxTokensFromChars;
10
+ exports.measurePromptMessages = measurePromptMessages;
11
+ const prompt_context_policy_js_1 = require("../../config/prompt-context-policy.js");
12
+ const playbook_resources_js_1 = require("./playbook-resources.js");
13
+ const prompt_invariants_js_1 = require("./prompt-invariants.js");
14
+ exports.MANIFEST_HEADER = 'Detailed resources:';
15
+ function embedResource(playbook) {
16
+ return {
17
+ type: 'resource',
18
+ resource: {
19
+ uri: playbook.uri,
20
+ mimeType: playbook_resources_js_1.PLAYBOOK_MIME,
21
+ text: playbook.getMarkdown(),
22
+ },
23
+ };
24
+ }
25
+ function formatManifestSection(title, entries) {
26
+ if (entries.length === 0) {
27
+ return '';
28
+ }
29
+ const sorted = [...entries].sort((a, b) => String(a.topic).localeCompare(String(b.topic)));
30
+ const lines = sorted.map((e) => `- ${e.uri} — ${e.when}`);
31
+ return [title, ...lines].join('\n');
32
+ }
33
+ function topicWhenEntries(list, topics, topicMeta) {
34
+ return list.map((entry) => {
35
+ var _a, _b;
36
+ const meta = topicMeta[entry.topic];
37
+ return {
38
+ topic: entry.topic,
39
+ when: (_b = (_a = entry.when) !== null && _a !== void 0 ? _a : meta.useWhen) !== null && _b !== void 0 ? _b : meta.description,
40
+ uri: topics[entry.topic].uri,
41
+ };
42
+ });
43
+ }
44
+ function buildManifestText(options) {
45
+ var _a;
46
+ const { core, requiredTopics, conditionalTopics, recoveryTopics, topics, topicMeta } = options;
47
+ const requiredEntries = requiredTopics.map((topic) => {
48
+ var _a;
49
+ // eslint-disable-next-line security/detect-object-injection -- topic ids from prompt constants
50
+ const meta = topicMeta[topic];
51
+ // eslint-disable-next-line security/detect-object-injection -- topic ids from prompt constants
52
+ const playbook = topics[topic];
53
+ return {
54
+ topic,
55
+ when: (_a = meta.useWhen) !== null && _a !== void 0 ? _a : meta.description,
56
+ uri: playbook.uri,
57
+ };
58
+ });
59
+ const parts = [
60
+ `- ${core.uri} — ${(_a = core.description) !== null && _a !== void 0 ? _a : 'Profile core playbook'}`,
61
+ formatManifestSection('Required detailed resources:', requiredEntries),
62
+ formatManifestSection('Conditional detailed resources:', topicWhenEntries(conditionalTopics, topics, topicMeta)),
63
+ formatManifestSection('Recovery resources:', topicWhenEntries(recoveryTopics, topics, topicMeta)),
64
+ ].filter((p) => p.length > 0);
65
+ return [exports.MANIFEST_HEADER, ...parts].join('\n\n');
66
+ }
67
+ function requireTopic(topics, id) {
68
+ // eslint-disable-next-line security/detect-object-injection -- topic ids from prompt constants
69
+ const topic = topics[id];
70
+ if (!topic) {
71
+ throw new Error(`Unknown playbook topic '${String(id)}'`);
72
+ }
73
+ return topic;
74
+ }
75
+ function buildComposerText(options) {
76
+ return [options.task.trim(), options.invariantText, options.manifestText]
77
+ .filter((p) => p.length > 0)
78
+ .join('\n\n');
79
+ }
80
+ function appendTopicResources(messages, topics, requiredTopics) {
81
+ for (const id of requiredTopics) {
82
+ messages.push({
83
+ role: 'user',
84
+ content: embedResource(requireTopic(topics, id)),
85
+ });
86
+ }
87
+ }
88
+ /**
89
+ * Build a prompts/get composer for a profile under a fixed context policy.
90
+ */
91
+ function createPromptContextComposer(options) {
92
+ const { policy, invariants, core, topics, topicMeta } = options;
93
+ (0, prompt_invariants_js_1.assertUniqueInvariantIds)(invariants);
94
+ const byId = (0, prompt_invariants_js_1.invariantIndex)(invariants);
95
+ return (spec) => {
96
+ var _a, _b, _c;
97
+ const requiredTopics = [...new Set((_a = spec.requiredTopics) !== null && _a !== void 0 ? _a : [])];
98
+ const conditionalTopics = (_b = spec.conditionalTopics) !== null && _b !== void 0 ? _b : [];
99
+ const recoveryTopics = (_c = spec.recoveryTopics) !== null && _c !== void 0 ? _c : [];
100
+ for (const id of requiredTopics) {
101
+ requireTopic(topics, id);
102
+ }
103
+ for (const entry of conditionalTopics) {
104
+ requireTopic(topics, entry.topic);
105
+ }
106
+ for (const entry of recoveryTopics) {
107
+ requireTopic(topics, entry.topic);
108
+ }
109
+ const includeManifest = policy !== 'embedded';
110
+ const text = buildComposerText({
111
+ task: spec.task,
112
+ invariantText: (0, prompt_invariants_js_1.formatInvariantCapsule)((0, prompt_invariants_js_1.resolveInvariants)(byId, spec.invariantIds)),
113
+ manifestText: includeManifest
114
+ ? buildManifestText({
115
+ core,
116
+ requiredTopics,
117
+ conditionalTopics,
118
+ recoveryTopics,
119
+ topics,
120
+ topicMeta,
121
+ })
122
+ : '',
123
+ });
124
+ const messages = [
125
+ {
126
+ role: 'user',
127
+ content: { type: 'text', text },
128
+ },
129
+ ];
130
+ switch (policy) {
131
+ case 'compact':
132
+ return { messages };
133
+ case 'compatible':
134
+ appendTopicResources(messages, topics, requiredTopics);
135
+ return { messages };
136
+ case 'embedded':
137
+ // Legacy parity: core + required topics (caller lists former embed set as required)
138
+ messages.push({
139
+ role: 'user',
140
+ content: embedResource(core),
141
+ });
142
+ appendTopicResources(messages, topics, requiredTopics);
143
+ return { messages };
144
+ default: {
145
+ const _exhaustive = policy;
146
+ return _exhaustive;
147
+ }
148
+ }
149
+ };
150
+ }
151
+ /** Profile-local binder: `const compose = bindProfilePromptContext(deps)(policy)`. */
152
+ function bindProfilePromptContext(deps) {
153
+ const composers = new Map();
154
+ return (policy = prompt_context_policy_js_1.DEFAULT_PROMPT_CONTEXT_POLICY) => {
155
+ const cached = composers.get(policy);
156
+ if (cached) {
157
+ return cached;
158
+ }
159
+ const composer = createPromptContextComposer(Object.assign({ policy }, deps));
160
+ composers.set(policy, composer);
161
+ return composer;
162
+ };
163
+ }
164
+ /** Approx token estimate: ceil(chars / 4). */
165
+ function approxTokensFromChars(chars) {
166
+ return Math.ceil(chars / 4);
167
+ }
168
+ function measureTextSections(text) {
169
+ const invIdx = text.indexOf(prompt_invariants_js_1.INVARIANT_CAPSULE_HEADER);
170
+ const manIdx = text.indexOf(exports.MANIFEST_HEADER);
171
+ const sectionStart = invIdx >= 0 ? invIdx : manIdx >= 0 ? manIdx : text.length;
172
+ const invariantChars = invIdx >= 0 ? Math.max(0, (manIdx >= 0 ? manIdx : text.length) - invIdx) : 0;
173
+ const manifestChars = manIdx >= 0 ? text.length - manIdx : 0;
174
+ return { taskChars: sectionStart, invariantChars, manifestChars };
175
+ }
176
+ function measurePromptMessages(messages) {
177
+ let taskChars = 0;
178
+ let invariantChars = 0;
179
+ let manifestChars = 0;
180
+ let embeddedResourceChars = 0;
181
+ let embeddedResourceCount = 0;
182
+ let totalChars = 0;
183
+ for (const message of messages) {
184
+ if (message.content.type === 'text') {
185
+ const measured = measureTextSections(message.content.text);
186
+ taskChars += measured.taskChars;
187
+ invariantChars += measured.invariantChars;
188
+ manifestChars += measured.manifestChars;
189
+ totalChars += message.content.text.length;
190
+ continue;
191
+ }
192
+ embeddedResourceCount += 1;
193
+ embeddedResourceChars += message.content.resource.text.length;
194
+ totalChars += message.content.resource.text.length;
195
+ }
196
+ return {
197
+ taskChars,
198
+ invariantChars,
199
+ manifestChars,
200
+ embeddedResourceChars,
201
+ totalChars,
202
+ approxTotalTokens: approxTokensFromChars(totalChars),
203
+ embeddedResourceCount,
204
+ };
205
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Prompt context composer unit tests.
3
+ */
4
+ export {};