@lightdash-tools/mcp 0.14.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +43 -14
  2. package/dist/auth/oauth-broker/as-metadata.d.ts +6 -2
  3. package/dist/auth/oauth-broker/as-metadata.js +8 -4
  4. package/dist/auth/oauth-broker/invoke-origins.d.ts +16 -0
  5. package/dist/auth/oauth-broker/invoke-origins.js +112 -0
  6. package/dist/auth/oauth-broker/invoke-origins.test.d.ts +1 -0
  7. package/dist/auth/oauth-broker/invoke-origins.test.js +82 -0
  8. package/dist/auth/oauth-broker/lightdash-token.d.ts +6 -5
  9. package/dist/auth/oauth-broker/lightdash-token.js +6 -10
  10. package/dist/auth/oauth-broker/mcp-access-token.d.ts +31 -0
  11. package/dist/auth/oauth-broker/mcp-access-token.js +109 -0
  12. package/dist/auth/oauth-broker/mcp-access-token.test.d.ts +1 -0
  13. package/dist/auth/oauth-broker/mcp-access-token.test.js +61 -0
  14. package/dist/auth/oauth-broker/pending-store.d.ts +9 -3
  15. package/dist/auth/oauth-broker/pending-store.js +5 -3
  16. package/dist/auth/oauth-broker/pending-store.test.js +28 -44
  17. package/dist/auth/oauth-broker/routes.d.ts +2 -1
  18. package/dist/auth/oauth-broker/routes.js +124 -48
  19. package/dist/auth/oauth-broker/routes.test.js +191 -16
  20. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +3 -1
  21. package/dist/auth/resource-server/lightdash-oauth-middleware.js +65 -41
  22. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +95 -59
  23. package/dist/auth/resource-server/oauth-protected-resource.d.ts +2 -2
  24. package/dist/auth/resource-server/oauth-protected-resource.js +8 -11
  25. package/dist/auth/resource-server/www-authenticate.test.js +3 -3
  26. package/dist/bin.js +33 -7
  27. package/dist/config/env.d.ts +10 -0
  28. package/dist/config/env.js +11 -1
  29. package/dist/config/load-mcp-config.d.ts +14 -1
  30. package/dist/config/load-mcp-config.js +35 -8
  31. package/dist/config/load-mcp-config.test.js +49 -0
  32. package/dist/config/prompt-context-policy.d.ts +18 -0
  33. package/dist/config/prompt-context-policy.js +40 -0
  34. package/dist/config/prompt-context-policy.test.d.ts +4 -0
  35. package/dist/config/prompt-context-policy.test.js +35 -0
  36. package/dist/config/test-mcp-http-config.js +1 -1
  37. package/dist/governance/mcp-post-factory-context.d.ts +2 -0
  38. package/dist/http.d.ts +7 -1
  39. package/dist/http.integration.helpers.d.ts +50 -0
  40. package/dist/http.integration.helpers.js +190 -0
  41. package/dist/http.integration.test.js +81 -187
  42. package/dist/http.invoke-origin.integration.test.d.ts +1 -0
  43. package/dist/http.invoke-origin.integration.test.js +108 -0
  44. package/dist/http.js +10 -1
  45. package/dist/index.d.ts +6 -1
  46. package/dist/index.js +6 -3
  47. package/dist/policy/content-developer.d.ts +5 -0
  48. package/dist/policy/content-developer.js +25 -1
  49. package/dist/policy/content-developer.test.js +29 -0
  50. package/dist/profiles/ai-agent-ops/v1/invariants.d.ts +27 -0
  51. package/dist/profiles/ai-agent-ops/v1/invariants.js +39 -0
  52. package/dist/profiles/ai-agent-ops/v1/prompts.d.ts +3 -2
  53. package/dist/profiles/ai-agent-ops/v1/prompts.js +67 -41
  54. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.d.ts +2 -1
  55. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.js +10 -3
  56. package/dist/profiles/content-developer/v1/invariants.d.ts +69 -0
  57. package/dist/profiles/content-developer/v1/invariants.js +95 -0
  58. package/dist/profiles/content-developer/v1/prompt-specs.d.ts +32 -0
  59. package/dist/profiles/content-developer/v1/prompt-specs.js +56 -0
  60. package/dist/profiles/content-developer/v1/prompts.d.ts +4 -3
  61. package/dist/profiles/content-developer/v1/prompts.js +65 -71
  62. package/dist/profiles/content-developer/v1/prompts.test.js +61 -7
  63. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +1 -0
  64. package/dist/profiles/content-developer/v1/resources/playbooks/index.md +11 -8
  65. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/dashboard-diff.md +15 -0
  66. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-required.md +14 -0
  67. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-stale.md +21 -0
  68. package/dist/profiles/content-developer/v1/resources/playbooks.d.ts +3 -2
  69. package/dist/profiles/content-developer/v1/resources/playbooks.js +35 -22
  70. package/dist/profiles/content-governance/v1/invariants.d.ts +27 -0
  71. package/dist/profiles/content-governance/v1/invariants.js +39 -0
  72. package/dist/profiles/content-governance/v1/prompts.d.ts +4 -2
  73. package/dist/profiles/content-governance/v1/prompts.js +31 -19
  74. package/dist/profiles/content-governance/v1/resources/playbooks.d.ts +2 -1
  75. package/dist/profiles/content-governance/v1/resources/playbooks.js +8 -9
  76. package/dist/profiles/content-reader/v1/invariants.d.ts +33 -0
  77. package/dist/profiles/content-reader/v1/invariants.js +47 -0
  78. package/dist/profiles/content-reader/v1/prompt-specs.d.ts +18 -0
  79. package/dist/profiles/content-reader/v1/prompt-specs.js +33 -0
  80. package/dist/profiles/content-reader/v1/prompts.d.ts +3 -2
  81. package/dist/profiles/content-reader/v1/prompts.js +69 -76
  82. package/dist/profiles/content-reader/v1/resources/playbooks.d.ts +2 -1
  83. package/dist/profiles/content-reader/v1/resources/playbooks.js +10 -11
  84. package/dist/profiles/data-analyst/v1/invariants.d.ts +21 -0
  85. package/dist/profiles/data-analyst/v1/invariants.js +31 -0
  86. package/dist/profiles/data-analyst/v1/prompts.d.ts +3 -2
  87. package/dist/profiles/data-analyst/v1/prompts.js +17 -9
  88. package/dist/profiles/data-analyst/v1/resources/playbooks.d.ts +2 -1
  89. package/dist/profiles/data-analyst/v1/resources/playbooks.js +6 -7
  90. package/dist/profiles/lib/playbook-resources.d.ts +16 -34
  91. package/dist/profiles/lib/playbook-resources.js +55 -76
  92. package/dist/profiles/lib/prompt-context.d.ts +71 -0
  93. package/dist/profiles/lib/prompt-context.js +205 -0
  94. package/dist/profiles/lib/prompt-context.test.d.ts +4 -0
  95. package/dist/profiles/lib/prompt-context.test.js +154 -0
  96. package/dist/profiles/lib/prompt-invariants.d.ts +20 -0
  97. package/dist/profiles/lib/prompt-invariants.js +54 -0
  98. package/dist/profiles/organization-audit/v1/invariants.d.ts +24 -0
  99. package/dist/profiles/organization-audit/v1/invariants.js +35 -0
  100. package/dist/profiles/organization-audit/v1/prompts.d.ts +3 -2
  101. package/dist/profiles/organization-audit/v1/prompts.js +44 -28
  102. package/dist/profiles/organization-audit/v1/resources/playbooks.d.ts +2 -1
  103. package/dist/profiles/organization-audit/v1/resources/playbooks.js +10 -3
  104. package/dist/profiles/semantic-layer/v1/invariants.d.ts +27 -0
  105. package/dist/profiles/semantic-layer/v1/invariants.js +39 -0
  106. package/dist/profiles/semantic-layer/v1/prompts.d.ts +3 -2
  107. package/dist/profiles/semantic-layer/v1/prompts.js +37 -26
  108. package/dist/profiles/semantic-layer/v1/resources/playbooks.d.ts +2 -4
  109. package/dist/profiles/semantic-layer/v1/resources/playbooks.js +8 -7
  110. package/dist/profiles/test-support/prompt-context-budget.test.d.ts +5 -0
  111. package/dist/profiles/test-support/prompt-context-budget.test.js +72 -0
  112. package/dist/profiles/types.d.ts +6 -1
  113. package/dist/server/capabilities.d.ts +3 -0
  114. package/dist/server/capabilities.js +4 -2
  115. package/dist/tools/lib/schema-fields.d.ts +4 -0
  116. package/dist/tools/lib/schema-fields.js +8 -1
  117. package/dist/tools/project/developer-content-preview.js +1 -1
  118. package/dist/tools/project/developer-content.js +2 -2
  119. package/dist/tools/query/reader-tool-helpers.d.ts +2 -2
  120. package/dist/tools/query/reader-tool-helpers.js +2 -2
  121. package/dist/tools/query/reader-tool-helpers.test.js +1 -0
  122. package/dist/tools/shared.d.ts +6 -1
  123. package/dist/tools/shared.js +12 -2
  124. package/dist/transports/streamable-http.js +13 -4
  125. package/dist/transports/streamable-http.test.js +8 -3
  126. package/package.json +3 -3
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const client_1 = require("@lightdash-tools/client");
3
4
  const vitest_1 = require("vitest");
4
5
  const test_mcp_http_config_js_1 = require("../../config/test-mcp-http-config.js");
5
6
  const index_js_1 = require("../../profiles/organization-audit/v1/index.js");
6
7
  const index_js_2 = require("../../profiles/semantic-layer/v1/index.js");
8
+ const mcp_access_token_js_1 = require("../oauth-broker/mcp-access-token.js");
7
9
  const lightdash_oauth_middleware_js_1 = require("./lightdash-oauth-middleware.js");
8
10
  const lightdash_token_validation_js_1 = require("./lightdash-token-validation.js");
9
11
  const token_validation_error_js_1 = require("./token-validation-error.js");
@@ -11,19 +13,34 @@ vitest_1.vi.mock('./lightdash-token-validation.js', () => ({
11
13
  validateLightdashAccessToken: vitest_1.vi.fn(),
12
14
  }));
13
15
  const baseConfig = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
16
+ oauthClientId: 'ld-client',
17
+ oauthClientSecret: new client_1.SecretString('test-lightdash-confidential-client-secret'),
14
18
  requiredScopes: [],
15
19
  });
16
- function jwtWithScope(scope) {
17
- const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
18
- const payload = Buffer.from(JSON.stringify({ scope })).toString('base64url');
19
- return `${header}.${payload}.signature`;
20
- }
21
- function createRequest(authorization) {
20
+ function createRequest(authorization, headers) {
22
21
  return {
23
- headers: authorization ? { authorization } : {},
22
+ headers: Object.assign(Object.assign({}, (authorization ? { authorization } : {})), headers),
23
+ socket: {},
24
24
  };
25
25
  }
26
+ function resourceFor(path) {
27
+ return `https://mcp.example.com${path}`;
28
+ }
29
+ function mcpToken(options = {}) {
30
+ var _a, _b, _c;
31
+ const path = (_a = options.path) !== null && _a !== void 0 ? _a : index_js_2.SEMANTIC_LAYER_PROFILE_PATH;
32
+ return (0, mcp_access_token_js_1.mintMcpAccessToken)(baseConfig, {
33
+ lightdashAccessToken: (_b = options.lightdashAccessToken) !== null && _b !== void 0 ? _b : 'ld-upstream-token',
34
+ clientId: 'mcp-client-1',
35
+ resource: resourceFor(path),
36
+ scope: options.scope,
37
+ expiresAtMs: (_c = options.expiresAtMs) !== null && _c !== void 0 ? _c : Date.now() + 60000,
38
+ }).accessToken;
39
+ }
26
40
  (0, vitest_1.describe)('authenticateLightdashOAuth', () => {
41
+ (0, vitest_1.beforeEach)(() => {
42
+ vitest_1.vi.clearAllMocks();
43
+ });
27
44
  (0, vitest_1.it)('returns 401 with WWW-Authenticate resource_metadata when token is missing', async () => {
28
45
  const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
29
46
  (0, vitest_1.expect)(result.ok).toBe(false);
@@ -46,22 +63,43 @@ function createRequest(authorization) {
46
63
  (0, vitest_1.expect)(result.wwwAuthenticate).toContain('https://mcp.example.com/.well-known/oauth-protected-resource/organization-audit/v1/mcp');
47
64
  (0, vitest_1.expect)(result.wwwAuthenticate).not.toContain('semantic-layer/v1/mcp');
48
65
  });
49
- (0, vitest_1.it)('returns 401 without echoing the bearer token when validation fails', async () => {
66
+ (0, vitest_1.it)('rejects a raw downstream Lightdash bearer before calling Lightdash', async () => {
67
+ const token = 'ld-upstream-token';
68
+ const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${token}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
69
+ (0, vitest_1.expect)(result.ok).toBe(false);
70
+ if (result.ok)
71
+ return;
72
+ (0, vitest_1.expect)(result.status).toBe(401);
73
+ (0, vitest_1.expect)(result.body.error).toBe('invalid_token');
74
+ (0, vitest_1.expect)(JSON.stringify(result.body)).not.toContain(token);
75
+ (0, vitest_1.expect)(lightdash_token_validation_js_1.validateLightdashAccessToken).not.toHaveBeenCalled();
76
+ });
77
+ (0, vitest_1.it)('rejects a valid broker token at a different profile resource', async () => {
78
+ const token = mcpToken({ path: index_js_1.ORGANIZATION_AUDIT_PROFILE_PATH });
79
+ const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${token}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
80
+ (0, vitest_1.expect)(result.ok).toBe(false);
81
+ if (result.ok)
82
+ return;
83
+ (0, vitest_1.expect)(result.status).toBe(401);
84
+ (0, vitest_1.expect)(result.body.error_description).toContain('wrong-audience');
85
+ (0, vitest_1.expect)(lightdash_token_validation_js_1.validateLightdashAccessToken).not.toHaveBeenCalled();
86
+ });
87
+ (0, vitest_1.it)('returns 401 without echoing the MCP bearer when downstream validation fails', async () => {
50
88
  vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockRejectedValue(new token_validation_error_js_1.TokenValidationError('invalid_token', 'Invalid or expired Lightdash access token'));
51
- const token = 'secret-oauth-token';
89
+ const token = mcpToken();
52
90
  const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${token}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
53
91
  (0, vitest_1.expect)(result.ok).toBe(false);
54
92
  if (result.ok)
55
93
  return;
56
94
  (0, vitest_1.expect)(result.status).toBe(401);
57
95
  (0, vitest_1.expect)(result.body.error).toBe('invalid_token');
58
- (0, vitest_1.expect)(result.body.error_description).toBe('Invalid or expired Lightdash access token');
59
96
  (0, vitest_1.expect)(JSON.stringify(result.body)).not.toContain(token);
60
97
  (0, vitest_1.expect)(result.wwwAuthenticate).toContain('error="invalid_token"');
98
+ (0, vitest_1.expect)(lightdash_token_validation_js_1.validateLightdashAccessToken).toHaveBeenCalledWith(baseConfig, 'ld-upstream-token');
61
99
  });
62
100
  (0, vitest_1.it)('returns 503 when Lightdash upstream is unavailable', async () => {
63
101
  vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockRejectedValue(new token_validation_error_js_1.TokenValidationError('upstream_unavailable', 'Lightdash is temporarily unavailable'));
64
- const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest('Bearer token'), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
102
+ const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${mcpToken()}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
65
103
  (0, vitest_1.expect)(result.ok).toBe(false);
66
104
  if (result.ok)
67
105
  return;
@@ -74,78 +112,42 @@ function createRequest(authorization) {
74
112
  });
75
113
  (0, vitest_1.it)('returns 503 with Retry-After when upstream is rate limited', async () => {
76
114
  vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockRejectedValue(new token_validation_error_js_1.TokenValidationError('upstream_unavailable', 'Lightdash is temporarily unavailable', 60));
77
- const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest('Bearer token'), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
115
+ const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${mcpToken()}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
78
116
  (0, vitest_1.expect)(result.ok).toBe(false);
79
117
  if (result.ok)
80
118
  return;
81
119
  (0, vitest_1.expect)(result.status).toBe(503);
82
120
  (0, vitest_1.expect)(result.headers).toEqual({ 'Retry-After': '60' });
83
121
  });
84
- (0, vitest_1.it)('returns user context when token validation succeeds', async () => {
122
+ (0, vitest_1.it)('returns downstream user context only after broker-token validation succeeds', async () => {
85
123
  vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockResolvedValue({
86
124
  userUuid: 'user-uuid-1',
87
125
  email: 'user@example.com',
88
126
  });
89
- const token = jwtWithScope('mcp:read mcp:write');
127
+ const token = mcpToken({ scope: 'mcp:read mcp:write' });
90
128
  const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${token}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
91
129
  (0, vitest_1.expect)(result).toEqual({
92
130
  ok: true,
93
- accessToken: token,
131
+ accessToken: 'ld-upstream-token',
94
132
  user: { userUuid: 'user-uuid-1', email: 'user@example.com' },
95
133
  scopes: ['mcp:read', 'mcp:write'],
96
134
  });
97
- (0, vitest_1.expect)(lightdash_token_validation_js_1.validateLightdashAccessToken).toHaveBeenCalledWith(baseConfig, token);
98
- });
99
- (0, vitest_1.it)('accepts opaque tokens when endpoint scope requirements are unset', async () => {
100
- vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockResolvedValue({
101
- userUuid: 'user-uuid-1',
102
- email: 'user@example.com',
103
- });
104
- const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest('Bearer opaque-token'), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
105
- (0, vitest_1.expect)(result).toEqual({
106
- ok: true,
107
- accessToken: 'opaque-token',
108
- user: { userUuid: 'user-uuid-1', email: 'user@example.com' },
109
- scopes: undefined,
110
- });
135
+ (0, vitest_1.expect)(lightdash_token_validation_js_1.validateLightdashAccessToken).toHaveBeenCalledWith(baseConfig, 'ld-upstream-token');
111
136
  });
112
- (0, vitest_1.it)('accepts JWTs without scope claims when endpoint scope requirements are unset', async () => {
137
+ (0, vitest_1.it)('accepts an MCP token without scopes when endpoint scope requirements are unset', async () => {
113
138
  vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockResolvedValue({
114
139
  userUuid: 'user-uuid-1',
115
140
  email: 'user@example.com',
116
141
  });
117
- const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
118
- const payload = Buffer.from(JSON.stringify({ sub: 'user-uuid-1' })).toString('base64url');
119
- const token = `${header}.${payload}.signature`;
120
- const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${token}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
142
+ const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${mcpToken()}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
121
143
  (0, vitest_1.expect)(result.ok).toBe(true);
122
144
  if (!result.ok)
123
145
  return;
124
146
  (0, vitest_1.expect)(result.scopes).toBeUndefined();
125
147
  });
126
- (0, vitest_1.it)('returns 403 insufficient_scope when required endpoint scopes are configured and missing', async () => {
127
- vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockResolvedValue({
128
- userUuid: 'user-uuid-1',
129
- email: 'user@example.com',
130
- });
131
- const scopedConfig = Object.assign(Object.assign({}, baseConfig), { requiredScopes: ['mcp:read'] });
132
- const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest('Bearer opaque-token'), scopedConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
133
- (0, vitest_1.expect)(result.ok).toBe(false);
134
- if (result.ok)
135
- return;
136
- (0, vitest_1.expect)(result.status).toBe(403);
137
- (0, vitest_1.expect)(result.body.error).toBe('insufficient_scope');
138
- (0, vitest_1.expect)(result.wwwAuthenticate).toContain('scope="mcp:read"');
139
- });
140
- (0, vitest_1.it)('returns 403 insufficient_scope when required scopes are missing from token claims', async () => {
141
- vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockResolvedValue({
142
- userUuid: 'user-uuid-1',
143
- email: 'user@example.com',
144
- });
145
- const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
146
- const payload = Buffer.from(JSON.stringify({ scope: 'mcp:write' })).toString('base64url');
147
- const token = `${header}.${payload}.signature`;
148
+ (0, vitest_1.it)('returns 403 insufficient_scope before calling Lightdash when MCP scopes are missing', async () => {
148
149
  const scopedConfig = Object.assign(Object.assign({}, baseConfig), { requiredScopes: ['mcp:read'] });
150
+ const token = mcpToken({ scope: 'mcp:write' });
149
151
  const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${token}`), scopedConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
150
152
  (0, vitest_1.expect)(result.ok).toBe(false);
151
153
  if (result.ok)
@@ -153,18 +155,52 @@ function createRequest(authorization) {
153
155
  (0, vitest_1.expect)(result.status).toBe(403);
154
156
  (0, vitest_1.expect)(result.body.error).toBe('insufficient_scope');
155
157
  (0, vitest_1.expect)(result.wwwAuthenticate).toContain('error="insufficient_scope"');
158
+ (0, vitest_1.expect)(result.wwwAuthenticate).toContain('scope="mcp:read"');
159
+ (0, vitest_1.expect)(lightdash_token_validation_js_1.validateLightdashAccessToken).not.toHaveBeenCalled();
156
160
  });
157
161
  (0, vitest_1.it)('accepts lowercase bearer scheme prefix', async () => {
158
162
  vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockResolvedValue({
159
163
  userUuid: 'user-uuid-1',
160
164
  email: 'user@example.com',
161
165
  });
162
- const token = jwtWithScope('mcp:read mcp:write');
163
- const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`bearer ${token}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
166
+ const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`bearer ${mcpToken()}`), baseConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
164
167
  (0, vitest_1.expect)(result.ok).toBe(true);
165
168
  if (!result.ok)
166
169
  return;
167
- (0, vitest_1.expect)(result.accessToken).toBe(token);
170
+ (0, vitest_1.expect)(result.accessToken).toBe('ld-upstream-token');
171
+ });
172
+ (0, vitest_1.it)('challenges and verifies against an extra invoke-origin resource when Host matches', async () => {
173
+ const invokeOrigin = new URL('http://mcp.ilb.internal');
174
+ const invokeConfig = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
175
+ oauthClientId: 'ld-client',
176
+ oauthClientSecret: new client_1.SecretString('test-lightdash-confidential-client-secret'),
177
+ requiredScopes: [],
178
+ invokeOrigins: [invokeOrigin],
179
+ });
180
+ const invokeHeaders = {
181
+ host: 'mcp.ilb.internal',
182
+ 'x-forwarded-proto': 'http',
183
+ };
184
+ const invokeResource = `http://mcp.ilb.internal${index_js_2.SEMANTIC_LAYER_PROFILE_PATH}`;
185
+ const challenge = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(undefined, invokeHeaders), invokeConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
186
+ (0, vitest_1.expect)(challenge.ok).toBe(false);
187
+ if (challenge.ok)
188
+ return;
189
+ (0, vitest_1.expect)(challenge.wwwAuthenticate).toContain('http://mcp.ilb.internal/.well-known/oauth-protected-resource/semantic-layer/v1/mcp');
190
+ vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockResolvedValue({
191
+ userUuid: 'user-1',
192
+ email: 'user@example.com',
193
+ });
194
+ const invokeToken = (0, mcp_access_token_js_1.mintMcpAccessToken)(invokeConfig, {
195
+ lightdashAccessToken: 'ld-upstream-token',
196
+ clientId: 'mcp-client-1',
197
+ resource: invokeResource,
198
+ expiresAtMs: Date.now() + 60000,
199
+ }).accessToken;
200
+ const ok = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${invokeToken}`, invokeHeaders), invokeConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
201
+ (0, vitest_1.expect)(ok.ok).toBe(true);
202
+ const publicHostRejectsInvokeToken = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${invokeToken}`, { host: 'mcp.example.com' }), invokeConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
203
+ (0, vitest_1.expect)(publicHostRejectsInvokeToken.ok).toBe(false);
168
204
  });
169
205
  });
170
206
  (0, vitest_1.describe)('writeOAuthAuthFailure', () => {
@@ -11,10 +11,10 @@ export interface OAuthProtectedResourceMetadata {
11
11
  * Builds MCP OAuth protected-resource metadata for a profile MCP path.
12
12
  * Callers must pass an explicit profile path (root PRM uses `config.mcpPath`).
13
13
  */
14
- export declare function buildOAuthProtectedResourceMetadata(config: McpHttpConfig, mcpPath: string): OAuthProtectedResourceMetadata;
14
+ export declare function buildOAuthProtectedResourceMetadata(config: McpHttpConfig, mcpPath: string, resourceOrigin: string): OAuthProtectedResourceMetadata;
15
15
  export declare function getProtectedResourceMetadataUrl(config: McpHttpConfig): string;
16
16
  /** Path-specific PRM URL for a profile MCP endpoint. */
17
- export declare function getProtectedResourceMetadataPathUrl(config: McpHttpConfig, mcpPath: string): string;
17
+ export declare function getProtectedResourceMetadataPathUrl(config: McpHttpConfig, mcpPath: string, resourceOrigin: string): string;
18
18
  /**
19
19
  * Resolves the profile MCP path for a PRM well-known request.
20
20
  * Root PRM maps to `config.mcpPath`; path-specific PRM is served only for
@@ -18,16 +18,14 @@ exports.OAUTH_PROTECTED_RESOURCE_ROOT = '/.well-known/oauth-protected-resource';
18
18
  * Builds MCP OAuth protected-resource metadata for a profile MCP path.
19
19
  * Callers must pass an explicit profile path (root PRM uses `config.mcpPath`).
20
20
  */
21
- function buildOAuthProtectedResourceMetadata(config, mcpPath) {
22
- const publicUrl = (0, public_url_js_1.requirePublicUrl)(config, OAUTH_PROTECTED_RESOURCE_CONTEXT);
21
+ function buildOAuthProtectedResourceMetadata(config, mcpPath, resourceOrigin) {
23
22
  const path = (0, normalize_url_js_1.normalizeMcpPath)(mcpPath);
24
- // Broker mode: authorization_servers is the MCP host (PUBLIC_URL). Clients discover
25
- // AS metadata at {PUBLIC_URL}/.well-known/oauth-authorization-server and never need
26
- // the Lightdash client secret. Identity validation remains GET /api/v1/user until
27
- // upstream tokens are resource-bound.
23
+ // Broker mode: authorization_servers is the MCP host clients should use for AS
24
+ // discovery. On PUBLIC_URL that is the public origin. On an extra invoke origin
25
+ // it is that origin so private-network clients do not fetch public well-known.
28
26
  return {
29
- resource: `${publicUrl}${path}`,
30
- authorization_servers: [publicUrl],
27
+ resource: `${resourceOrigin}${path}`,
28
+ authorization_servers: [resourceOrigin],
31
29
  bearer_methods_supported: ['header'],
32
30
  scopes_supported: config.scopesSupported,
33
31
  };
@@ -36,10 +34,9 @@ function getProtectedResourceMetadataUrl(config) {
36
34
  return `${(0, public_url_js_1.requirePublicUrl)(config, OAUTH_PROTECTED_RESOURCE_CONTEXT)}${exports.OAUTH_PROTECTED_RESOURCE_ROOT}`;
37
35
  }
38
36
  /** Path-specific PRM URL for a profile MCP endpoint. */
39
- function getProtectedResourceMetadataPathUrl(config, mcpPath) {
40
- const publicUrl = (0, public_url_js_1.requirePublicUrl)(config, OAUTH_PROTECTED_RESOURCE_CONTEXT);
37
+ function getProtectedResourceMetadataPathUrl(config, mcpPath, resourceOrigin) {
41
38
  const resourcePath = (0, normalize_url_js_1.normalizeMcpPath)(mcpPath).replace(/^\//, '');
42
- return `${publicUrl}${exports.OAUTH_PROTECTED_RESOURCE_ROOT}/${resourcePath}`;
39
+ return `${resourceOrigin}${exports.OAUTH_PROTECTED_RESOURCE_ROOT}/${resourcePath}`;
43
40
  }
44
41
  /**
45
42
  * Resolves the profile MCP path for a PRM well-known request.
@@ -18,7 +18,7 @@ const baseConfig = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
18
18
  });
19
19
  (0, vitest_1.describe)('buildOAuthProtectedResourceMetadata', () => {
20
20
  (0, vitest_1.it)('includes resource and MCP host as authorization_servers', () => {
21
- const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_3.SEMANTIC_LAYER_PROFILE_PATH);
21
+ const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_3.SEMANTIC_LAYER_PROFILE_PATH, 'https://mcp.example.com');
22
22
  (0, vitest_1.expect)(metadata).toEqual({
23
23
  resource: `https://mcp.example.com${index_js_3.SEMANTIC_LAYER_PROFILE_PATH}`,
24
24
  authorization_servers: ['https://mcp.example.com'],
@@ -28,12 +28,12 @@ const baseConfig = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
28
28
  (0, vitest_1.expect)((0, oauth_protected_resource_js_1.getAuthorizationServerMetadataUrl)(metadata.authorization_servers[0])).toBe('https://mcp.example.com/.well-known/oauth-authorization-server');
29
29
  });
30
30
  (0, vitest_1.it)('builds profile-specific resource metadata for organization-audit', () => {
31
- const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_2.ORGANIZATION_AUDIT_PROFILE_PATH);
31
+ const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_2.ORGANIZATION_AUDIT_PROFILE_PATH, 'https://mcp.example.com');
32
32
  (0, vitest_1.expect)(metadata.resource).toBe(`https://mcp.example.com${index_js_2.ORGANIZATION_AUDIT_PROFILE_PATH}`);
33
33
  (0, vitest_1.expect)(metadata.authorization_servers).toEqual(['https://mcp.example.com']);
34
34
  });
35
35
  (0, vitest_1.it)('builds profile-specific resource metadata for content-reader', () => {
36
- const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_1.CONTENT_READER_PROFILE_PATH);
36
+ const metadata = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(baseConfig, index_js_1.CONTENT_READER_PROFILE_PATH, 'https://mcp.example.com');
37
37
  (0, vitest_1.expect)(metadata.resource).toBe(`https://mcp.example.com${index_js_1.CONTENT_READER_PROFILE_PATH}`);
38
38
  (0, vitest_1.expect)(metadata.authorization_servers).toEqual(['https://mcp.example.com']);
39
39
  });
package/dist/bin.js CHANGED
@@ -37,18 +37,42 @@ Object.defineProperty(exports, "__esModule", { value: true });
37
37
  const common_1 = require("@lightdash-tools/common");
38
38
  const commander_1 = require("commander");
39
39
  const cli_help_js_1 = require("./cli-help.js");
40
+ const env_js_1 = require("./config/env.js");
41
+ const prompt_context_policy_js_1 = require("./config/prompt-context-policy.js");
40
42
  const index_js_1 = require("./profiles/index.js");
41
43
  const version_js_1 = require("./server/version.js");
42
44
  const program = new commander_1.Command();
43
- function runStdio(profileId) {
45
+ function resolvePolicyOrExit(cli) {
46
+ try {
47
+ return (0, prompt_context_policy_js_1.resolvePromptContextPolicy)({
48
+ cli,
49
+ env: process.env,
50
+ });
51
+ }
52
+ catch (err) {
53
+ console.error(err instanceof Error ? err.message : err);
54
+ process.exitCode = 1;
55
+ return undefined;
56
+ }
57
+ }
58
+ function runStdio(profileId, promptContext) {
59
+ const promptContextPolicy = resolvePolicyOrExit(promptContext);
60
+ if (!promptContextPolicy)
61
+ return;
44
62
  void Promise.resolve().then(() => __importStar(require('./index.js'))).then((m) => {
45
- m.startStdio(profileId);
63
+ m.startStdio(profileId, { promptContextPolicy });
46
64
  });
47
65
  }
48
- function runHttp() {
49
- void Promise.resolve().then(() => __importStar(require('./http.js')));
66
+ function runHttp(promptContext) {
67
+ const policy = resolvePolicyOrExit(promptContext);
68
+ if (!policy)
69
+ return;
70
+ void Promise.resolve().then(() => __importStar(require('./http.js'))).then((m) => {
71
+ void m.startHttp({ promptContextPolicy: policy });
72
+ });
50
73
  }
51
74
  const profileList = common_1.PROFILE_IDS.join(', ');
75
+ const promptContextHelp = `Prompt context policy (${prompt_context_policy_js_1.PROMPT_CONTEXT_POLICIES.join('|')}; env: ${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT})`;
52
76
  program
53
77
  .name('lightdash-mcp')
54
78
  .description(`MCP server for Lightdash (${profileList}). Use \`stdio --profile <id>\` or \`http\`.`)
@@ -65,6 +89,7 @@ program
65
89
  .command('stdio')
66
90
  .description('Run MCP server on stdio')
67
91
  .requiredOption('--profile <id>', `Profile id (${profileList})`)
92
+ .option('--prompt-context <policy>', promptContextHelp)
68
93
  .addHelpText('after', cli_help_js_1.formatProfilesHelp)
69
94
  .action((opts) => {
70
95
  const id = (0, index_js_1.parseProfileId)(opts.profile);
@@ -73,13 +98,14 @@ program
73
98
  process.exitCode = 1;
74
99
  return;
75
100
  }
76
- runStdio(id);
101
+ runStdio(id, opts.promptContext);
77
102
  });
78
103
  program
79
104
  .command('http')
80
105
  .description('Run MCP server over Streamable HTTP (fixed profile paths)')
106
+ .option('--prompt-context <policy>', promptContextHelp)
81
107
  .addHelpText('after', cli_help_js_1.formatProfilesHelp)
82
- .action(() => {
83
- runHttp();
108
+ .action((opts) => {
109
+ runHttp(opts.promptContext);
84
110
  });
85
111
  program.parse(process.argv);
@@ -7,10 +7,20 @@ export declare const ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT = "LIGHTDASH_TOOLS_MCP_HT
7
7
  /** Platform listen port (Cloud Run / many PaaS). Used only when dedicated MCP port env is unset. */
8
8
  export declare const ENV_PLATFORM_PORT = "PORT";
9
9
  export declare const ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL = "LIGHTDASH_TOOLS_MCP_PUBLIC_URL";
10
+ /**
11
+ * Optional comma-separated extra invoke origins (private load balancer, internal DNS).
12
+ * On a matching Host, PRM and token/DCR advertise that origin; issuer/authorize stay on PUBLIC_URL.
13
+ */
14
+ export declare const ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS = "LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS";
10
15
  /** Rejected at config load — MCP path is profile-owned (see profiles/). */
11
16
  export declare const ENV_LIGHTDASH_TOOLS_MCP_PATH = "LIGHTDASH_TOOLS_MCP_PATH";
12
17
  /** Optional HTTP mount allowlist (comma-separated ProfileIds). Unset/empty → all. Stdio ignores. */
13
18
  export declare const ENV_LIGHTDASH_TOOLS_MCP_PROFILES = "LIGHTDASH_TOOLS_MCP_PROFILES";
19
+ /**
20
+ * Prompt playbook embedding policy: `compact` | `compatible` | `embedded`.
21
+ * Unset → package default (`compact`). Stdio `--prompt-context` overrides.
22
+ */
23
+ export declare const ENV_LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT = "LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT";
14
24
  /** Rejected — auth mode is inferred from credentials (ADR-0007). */
15
25
  export declare const ENV_LIGHTDASH_TOOLS_MCP_AUTH_MODE = "LIGHTDASH_TOOLS_MCP_AUTH_MODE";
16
26
  export declare const ENV_LIGHTDASH_TOOLS_MCP_SHARED_KEY = "LIGHTDASH_TOOLS_MCP_SHARED_KEY";
@@ -4,16 +4,26 @@
4
4
  * Legacy `MCP_*` aliases are resolved in load-mcp-config.ts.
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH = exports.OAUTH_REGISTER_PATH = exports.OAUTH_TOKEN_PATH = exports.OAUTH_AUTHORIZE_PATH = exports.OAUTH_CALLBACK_PATH = exports.ENV_MCP_MAX_BODY_BYTES = exports.ENV_MCP_ALLOWED_ORIGINS = exports.ENV_MCP_API_KEY = exports.ENV_MCP_AUTH_ENABLED = exports.ENV_MCP_PUBLIC_URL = exports.ENV_MCP_SERVER_PORT = exports.ENV_MCP_HTTP_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_ALLOW_INSECURE_PUBLIC_URL = exports.ENV_LIGHTDASH_TOOLS_MCP_EXPERIMENTAL_IDENTITY_OAUTH = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_ALLOW_ANY_ORIGIN = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_ALLOW_UNAUTHENTICATED = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_GRANT_ALL_SCOPES = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_SKIP_TOKEN_VALIDATION = exports.ENV_LIGHTDASH_TOOLS_MCP_INSECURE_DEV = exports.ENV_LIGHTDASH_TOOLS_MCP_REDIS_URL = exports.ENV_LIGHTDASH_TOOLS_MCP_STORE = exports.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET = exports.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_ID = exports.ENV_LIGHTDASH_TOOLS_MCP_TOKEN_VALIDATION_CACHE_TTL_MS = exports.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN = exports.ENV_LIGHTDASH_TOOLS_MCP_SCOPES_SUPPORTED = exports.ENV_LIGHTDASH_TOOLS_MCP_REQUIRED_SCOPES = exports.ENV_LIGHTDASH_TOOLS_MCP_MAX_BODY_BYTES = exports.ENV_LIGHTDASH_TOOLS_MCP_ALLOWED_ORIGINS = exports.ENV_LIGHTDASH_TOOLS_MCP_REQUEST_STATE_KEY = exports.ENV_LIGHTDASH_TOOLS_MCP_SHARED_KEY = exports.ENV_LIGHTDASH_TOOLS_MCP_AUTH_MODE = exports.ENV_LIGHTDASH_TOOLS_MCP_PROFILES = exports.ENV_LIGHTDASH_TOOLS_MCP_PATH = exports.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL = exports.ENV_PLATFORM_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST = void 0;
7
+ exports.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH = exports.OAUTH_REGISTER_PATH = exports.OAUTH_TOKEN_PATH = exports.OAUTH_AUTHORIZE_PATH = exports.OAUTH_CALLBACK_PATH = exports.ENV_MCP_MAX_BODY_BYTES = exports.ENV_MCP_ALLOWED_ORIGINS = exports.ENV_MCP_API_KEY = exports.ENV_MCP_AUTH_ENABLED = exports.ENV_MCP_PUBLIC_URL = exports.ENV_MCP_SERVER_PORT = exports.ENV_MCP_HTTP_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_ALLOW_INSECURE_PUBLIC_URL = exports.ENV_LIGHTDASH_TOOLS_MCP_EXPERIMENTAL_IDENTITY_OAUTH = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_ALLOW_ANY_ORIGIN = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_ALLOW_UNAUTHENTICATED = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_GRANT_ALL_SCOPES = exports.ENV_LIGHTDASH_TOOLS_MCP_DANGEROUSLY_SKIP_TOKEN_VALIDATION = exports.ENV_LIGHTDASH_TOOLS_MCP_INSECURE_DEV = exports.ENV_LIGHTDASH_TOOLS_MCP_REDIS_URL = exports.ENV_LIGHTDASH_TOOLS_MCP_STORE = exports.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET = exports.ENV_LIGHTDASH_TOOLS_OAUTH_CLIENT_ID = exports.ENV_LIGHTDASH_TOOLS_MCP_TOKEN_VALIDATION_CACHE_TTL_MS = exports.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN = exports.ENV_LIGHTDASH_TOOLS_MCP_SCOPES_SUPPORTED = exports.ENV_LIGHTDASH_TOOLS_MCP_REQUIRED_SCOPES = exports.ENV_LIGHTDASH_TOOLS_MCP_MAX_BODY_BYTES = exports.ENV_LIGHTDASH_TOOLS_MCP_ALLOWED_ORIGINS = exports.ENV_LIGHTDASH_TOOLS_MCP_REQUEST_STATE_KEY = exports.ENV_LIGHTDASH_TOOLS_MCP_SHARED_KEY = exports.ENV_LIGHTDASH_TOOLS_MCP_AUTH_MODE = exports.ENV_LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT = exports.ENV_LIGHTDASH_TOOLS_MCP_PROFILES = exports.ENV_LIGHTDASH_TOOLS_MCP_PATH = exports.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS = exports.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL = exports.ENV_PLATFORM_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT = exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST = void 0;
8
8
  exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST = 'LIGHTDASH_TOOLS_MCP_HTTP_HOST';
9
9
  exports.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT = 'LIGHTDASH_TOOLS_MCP_HTTP_PORT';
10
10
  /** Platform listen port (Cloud Run / many PaaS). Used only when dedicated MCP port env is unset. */
11
11
  exports.ENV_PLATFORM_PORT = 'PORT';
12
12
  exports.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL = 'LIGHTDASH_TOOLS_MCP_PUBLIC_URL';
13
+ /**
14
+ * Optional comma-separated extra invoke origins (private load balancer, internal DNS).
15
+ * On a matching Host, PRM and token/DCR advertise that origin; issuer/authorize stay on PUBLIC_URL.
16
+ */
17
+ exports.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS = 'LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS';
13
18
  /** Rejected at config load — MCP path is profile-owned (see profiles/). */
14
19
  exports.ENV_LIGHTDASH_TOOLS_MCP_PATH = 'LIGHTDASH_TOOLS_MCP_PATH';
15
20
  /** Optional HTTP mount allowlist (comma-separated ProfileIds). Unset/empty → all. Stdio ignores. */
16
21
  exports.ENV_LIGHTDASH_TOOLS_MCP_PROFILES = 'LIGHTDASH_TOOLS_MCP_PROFILES';
22
+ /**
23
+ * Prompt playbook embedding policy: `compact` | `compatible` | `embedded`.
24
+ * Unset → package default (`compact`). Stdio `--prompt-context` overrides.
25
+ */
26
+ exports.ENV_LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT = 'LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT';
17
27
  /** Rejected — auth mode is inferred from credentials (ADR-0007). */
18
28
  exports.ENV_LIGHTDASH_TOOLS_MCP_AUTH_MODE = 'LIGHTDASH_TOOLS_MCP_AUTH_MODE';
19
29
  exports.ENV_LIGHTDASH_TOOLS_MCP_SHARED_KEY = 'LIGHTDASH_TOOLS_MCP_SHARED_KEY';
@@ -1,5 +1,6 @@
1
1
  import { SecretString } from '@lightdash-tools/client';
2
2
  import { type EnabledProfilesPolicy } from './enabled-profiles.js';
3
+ import { type PromptContextPolicy } from './prompt-context-policy.js';
3
4
  import type { McpAuthMode } from '../auth/auth-mode.js';
4
5
  export interface McpHttpConfig {
5
6
  lightdashUrl: string;
@@ -7,9 +8,13 @@ export interface McpHttpConfig {
7
8
  host: string;
8
9
  port: number;
9
10
  publicUrl?: string;
11
+ /** Extra invoke origins. Parsed only in OAuth mode. */
12
+ invokeOrigins: URL[];
10
13
  mcpPath: string;
11
14
  /** HTTP mount allowlist. Unrestricted when LIGHTDASH_TOOLS_MCP_PROFILES is unset. */
12
15
  enabledProfiles: EnabledProfilesPolicy;
16
+ /** Progressive-disclosure prompt embedding policy (default compact). */
17
+ promptContextPolicy: PromptContextPolicy;
13
18
  authMode: McpAuthMode;
14
19
  sharedKey?: SecretString;
15
20
  /** Server-held Lightdash OAuth application client id (broker mode). */
@@ -24,6 +29,14 @@ export interface McpHttpConfig {
24
29
  tokenValidationCacheTtlMs: number;
25
30
  }
26
31
  export declare function emitMcpHttpSecurityWarnings(config: McpHttpConfig): void;
27
- export declare function loadMcpHttpConfig(env?: NodeJS.ProcessEnv): McpHttpConfig;
32
+ /**
33
+ * Load Streamable HTTP MCP config from env.
34
+ * When `options.promptContextPolicy` is set (CLI path), that value wins and
35
+ * `LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT` is not re-resolved — so invalid env
36
+ * cannot fail a start that already resolved a valid CLI policy.
37
+ */
38
+ export declare function loadMcpHttpConfig(env?: NodeJS.ProcessEnv, options?: {
39
+ promptContextPolicy?: PromptContextPolicy;
40
+ }): McpHttpConfig;
28
41
  export declare function requiresLightdashApiKey(authMode: McpAuthMode): boolean;
29
42
  export declare function getOAuthCallbackUrl(config: McpHttpConfig): string;
@@ -6,11 +6,13 @@ exports.requiresLightdashApiKey = requiresLightdashApiKey;
6
6
  exports.getOAuthCallbackUrl = getOAuthCallbackUrl;
7
7
  const client_1 = require("@lightdash-tools/client");
8
8
  const auth_mode_js_1 = require("../auth/auth-mode.js");
9
+ const invoke_origins_js_1 = require("../auth/oauth-broker/invoke-origins.js");
9
10
  const index_js_1 = require("../profiles/index.js");
10
11
  const enabled_profiles_js_1 = require("./enabled-profiles.js");
11
12
  const env_js_1 = require("./env.js");
12
13
  const normalize_url_js_1 = require("./normalize-url.js");
13
14
  const obsolete_env_js_1 = require("./obsolete-env.js");
15
+ const prompt_context_policy_js_1 = require("./prompt-context-policy.js");
14
16
  const public_url_js_1 = require("./public-url.js");
15
17
  const read_env_js_1 = require("./read-env.js");
16
18
  const DEFAULT_SCOPES_SUPPORTED = ['read', 'write', 'mcp:read', 'mcp:write'];
@@ -144,15 +146,28 @@ function emitLightdashOAuthSecurityWarnings(config) {
144
146
  if (config.authMode !== auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH) {
145
147
  return;
146
148
  }
147
- console.warn('Note: hosted OAuth uses a server-held Lightdash confidential client (OAuth broker). ' +
148
- 'Token validation confirms Lightdash user identity via GET /api/v1/user; ' +
149
- 'opaque Lightdash tokens are not fully resource/audience-bound until upstream supports it. ' +
149
+ console.warn('Note: hosted OAuth uses a dual-leg broker with a server-held Lightdash confidential client. ' +
150
+ 'MCP clients receive resource-bound broker tokens; delegated Lightdash access tokens remain ' +
151
+ 'encrypted inside the broker token and are recovered only server-side for upstream calls. ' +
150
152
  `Register redirect URI ${getOAuthCallbackUrl(config)} in Lightdash.`);
151
153
  if (!config.validateToken) {
152
- console.warn(`Warning: ${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN}=false — MCP accepts any bearer token without calling Lightdash. ` +
153
- 'Use only for local development.');
154
+ console.warn(`Warning: ${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_VALIDATE_TOKEN}=false — broker-issued MCP tokens are still authenticated and audience-bound, ` +
155
+ 'but downstream Lightdash user/token validation is skipped. Use only for local development.');
154
156
  }
155
157
  emitNgrokFreeInterstitialWarning(config.publicUrl);
158
+ emitInvokeOriginWarnings(config);
159
+ }
160
+ function emitInvokeOriginWarnings(config) {
161
+ const cleartext = config.invokeOrigins.filter((origin) => origin.protocol === 'http:' && !(0, normalize_url_js_1.isLocalHttpOrigin)(origin.origin));
162
+ if (cleartext.length === 0) {
163
+ return;
164
+ }
165
+ const listed = cleartext.map((origin) => origin.origin).join(', ');
166
+ console.warn(`Warning: ${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS} includes non-loopback http origins (${listed}). ` +
167
+ 'On those Hosts, token/DCR and PRM advertise the invoke origin while issuer/authorize stay on ' +
168
+ `${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PUBLIC_URL}. This is an intentional RFC 8414 issuer split; ` +
169
+ '@modelcontextprotocol/client v2 will reject HTTP invoke origins. Point that SDK at public HTTPS. ' +
170
+ 'Do not serve extra origins as the public VIP Host.');
156
171
  }
157
172
  /** Free ngrok serves ERR_NGROK_6024 for browser-UA GETs; Cursor's post-callback rediscovery uses Mozilla UA. */
158
173
  function emitNgrokFreeInterstitialWarning(publicUrl) {
@@ -216,8 +231,14 @@ function resolveOAuthCredentials(authMode, oauthClientId, oauthClientSecretRaw)
216
231
  : undefined,
217
232
  };
218
233
  }
219
- function loadMcpHttpConfig(env = process.env) {
220
- var _a;
234
+ /**
235
+ * Load Streamable HTTP MCP config from env.
236
+ * When `options.promptContextPolicy` is set (CLI path), that value wins and
237
+ * `LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT` is not re-resolved — so invalid env
238
+ * cannot fail a start that already resolved a valid CLI policy.
239
+ */
240
+ function loadMcpHttpConfig(env = process.env, options) {
241
+ var _a, _b;
221
242
  const lightdashUrlRaw = (0, read_env_js_1.readEnv)(client_1.ENV_LIGHTDASH_URL, env);
222
243
  if (!lightdashUrlRaw) {
223
244
  throw new Error(`${client_1.ENV_LIGHTDASH_URL} is required.`);
@@ -238,20 +259,26 @@ function loadMcpHttpConfig(env = process.env) {
238
259
  const allowedOrigins = parseCsv(allowedOriginsRaw);
239
260
  const proxyAuth = (0, read_env_js_1.readEnv)(client_1.ENV_LIGHTDASH_PROXY_AUTHORIZATION, env);
240
261
  const enabledProfiles = (0, enabled_profiles_js_1.parseEnabledProfiles)((0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_PROFILES, env));
262
+ const promptContextPolicy = (_a = options === null || options === void 0 ? void 0 : options.promptContextPolicy) !== null && _a !== void 0 ? _a : (0, prompt_context_policy_js_1.resolvePromptContextPolicy)({ env });
241
263
  const mcpPath = (0, enabled_profiles_js_1.resolveRootMcpPath)(enabledProfiles);
242
264
  const publicUrl = publicUrlRaw ? (0, normalize_url_js_1.normalizePublicUrl)(publicUrlRaw, (0, index_js_1.listProfilePaths)()) : undefined;
243
265
  assertPublicUrlSecurity(authMode, publicUrl);
266
+ const invokeOrigins = authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH
267
+ ? (0, invoke_origins_js_1.parseInvokeOrigins)((0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS, env), publicUrl)
268
+ : [];
244
269
  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);
245
270
  assertValidateTokenPolicy(authMode, validateToken, env);
246
271
  const requiredScopes = readScopeList(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_REQUIRED_SCOPES, []);
247
272
  const scopesSupportedEnvSet = (0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_SCOPES_SUPPORTED, env) !== undefined;
248
273
  assertLightdashOAuthScopePolicy(authMode, requiredScopes, scopesSupportedEnvSet);
249
- 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, [
274
+ return Object.assign(Object.assign({ lightdashUrl: (0, normalize_url_js_1.normalizeLightdashUrl)(lightdashUrlRaw), proxyAuthorization: proxyAuth ? new client_1.SecretString(proxyAuth) : undefined, host: (_b = (0, read_env_js_1.readEnv)(env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_HOST, env)) !== null && _b !== void 0 ? _b : '0.0.0.0', port: readNumberEnv(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT, [
250
275
  { name: env_js_1.ENV_MCP_HTTP_PORT, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT },
251
276
  { name: env_js_1.ENV_MCP_SERVER_PORT, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_HTTP_PORT },
252
277
  ], 3100, env_js_1.ENV_PLATFORM_PORT), publicUrl,
278
+ invokeOrigins,
253
279
  mcpPath,
254
280
  enabledProfiles,
281
+ promptContextPolicy,
255
282
  authMode, sharedKey: sharedKeyRaw ? new client_1.SecretString(sharedKeyRaw) : undefined }, resolveOAuthCredentials(authMode, oauthClientId, oauthClientSecretRaw)), { allowedOrigins, maxBodyBytes: readNumberEnv(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_MAX_BODY_BYTES, [{ name: env_js_1.ENV_MCP_MAX_BODY_BYTES, newName: env_js_1.ENV_LIGHTDASH_TOOLS_MCP_MAX_BODY_BYTES }], 1024 * 1024), requiredScopes, scopesSupported: readScopeList(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_SCOPES_SUPPORTED, authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH ? [] : [...DEFAULT_SCOPES_SUPPORTED]), validateToken, tokenValidationCacheTtlMs: readNumberEnv(env, env_js_1.ENV_LIGHTDASH_TOOLS_MCP_TOKEN_VALIDATION_CACHE_TTL_MS, [], 10000) });
256
283
  }
257
284
  function requiresLightdashApiKey(authMode) {