@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
package/README.md CHANGED
@@ -68,10 +68,19 @@ npx @lightdash-tools/mcp http
68
68
 
69
69
  Profile MCP endpoints accept **POST** only ([Streamable HTTP 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http); no protocol sessions). Default listen port: `3100` (`LIGHTDASH_TOOLS_MCP_HTTP_PORT`). On Cloud Run / containers, when that env is unset, the platform `PORT` is used.
70
70
 
71
+ HTTP process probes (unauthenticated, not MCP tools; always mounted even when `LIGHTDASH_TOOLS_MCP_PROFILES` restricts profile paths). Stdio has no health paths.
72
+
73
+ | Path | Typical use | Success | Failure |
74
+ | :------------------ | :------------------------------------- | :---------------------------- | :-------------------------------- |
75
+ | `GET /health/live` | Liveness / Compose / Cloud Run startup | `200` `{ "status": "ok" }` | process down |
76
+ | `GET /health/ready` | Readiness (shared-key / local `none`) | `200` `{ "status": "ready" }` | `503` `{ "status": "not ready" }` |
77
+
78
+ `/health/ready` only checks that a Lightdash API client can be constructed when the process uses an API key. Hosted OAuth mode does not require a key, so ready ≈ live — it does **not** ping upstream Lightdash. Probe recipe: [cloud-run.md](../../docs/operators/cloud-run.md).
79
+
71
80
  - Hosted OAuth (Cursor URL-only): [docs/operators/cursor-claude.md](../../docs/operators/cursor-claude.md)
72
81
  - Operator guide: [docs/operators/mcp-oauth.md](../../docs/operators/mcp-oauth.md)
73
82
 
74
- Local Compose smoke: `docker compose -f docker-compose.dev.yml up --build` → `http://localhost:8080/semantic-layer/v1/mcp`.
83
+ Local Compose smoke: `docker compose -f docker-compose.dev.yml up --build` → `http://localhost:8080/semantic-layer/v1/mcp` (Compose healthcheck is `GET /health/live`).
75
84
 
76
85
  ## Configuration
77
86
 
@@ -127,6 +136,25 @@ export LIGHTDASH_TOOLS_MCP_PROFILES="content-reader,content-developer"
127
136
 
128
137
  Architecture: [ADR-0024](../../docs/adr/0024-mcp-http-profile-mount-allowlist-via-env.md).
129
138
 
139
+ ### Prompt context policy
140
+
141
+ Controls how much playbook markdown is embedded into `prompts/get` (progressive disclosure; [ADR-0025](../../docs/adr/0025-mcp-progressive-disclosure-prompt-context-policies.md)).
142
+
143
+ | Value | Behavior |
144
+ | :------------------ | :-------------------------------------------------- |
145
+ | `compact` (default) | Task + critical invariants + resource manifest only |
146
+ | `compatible` | Also embeds required topic playbooks |
147
+ | `embedded` | Legacy: embeds core + required topics (rollback) |
148
+
149
+ ```bash
150
+ export LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT=compatible
151
+ # or
152
+ lightdash-mcp stdio --profile content-reader --prompt-context embedded
153
+ lightdash-mcp http --prompt-context compact
154
+ ```
155
+
156
+ Invalid values fail at startup. Do not infer policy from MCP client names.
157
+
130
158
  ### Project allowlist
131
159
 
132
160
  Optional deployment ceiling shared with the CLI. Unset or empty → unrestricted beyond RBAC, HTTP pin, and tool `projectUuid`. Non-empty → hard allowlist for all profiles.
@@ -215,20 +243,11 @@ When a tool handler throws (for example a Lightdash HTTP/API failure), MCP retur
215
243
 
216
244
  Intentional API upgrades still go through the pinned OpenAPI sync (`config/lightdash-openapi-ref.txt`). This layer only makes runtime drift fail safely and legibly.
217
245
 
218
- ## Migration from `@lightdash-tools/semantic-layer-mcp`
219
-
220
- | Removed / old | Use instead |
221
- | :-------------------------------------------- | :---------------------------------------- |
222
- | `@lightdash-tools/semantic-layer-mcp` | `@lightdash-tools/mcp` |
223
- | Binary `lightdash-semantic-layer-mcp` | `lightdash-mcp` |
224
- | HTTP `/mcp` (old) | `/semantic-layer/v1/mcp` |
225
- | Unprefixed tool names | `lightdash_*` |
226
- | `lightdash-mcp <profile>` / `stdio <profile>` | `lightdash-mcp stdio --profile <profile>` |
227
-
228
246
  ## Further reading
229
247
 
230
248
  - Architecture / contributing — [CONTRIBUTING.md](./CONTRIBUTING.md)
231
249
  - OAuth operator guide — [docs/operators/mcp-oauth.md](../../docs/operators/mcp-oauth.md)
250
+ - Cloud Run — [docs/operators/cloud-run.md](../../docs/operators/cloud-run.md)
232
251
  - Cursor hosted OAuth — [docs/operators/cursor-claude.md](../../docs/operators/cursor-claude.md)
233
252
  - Architecture decisions — [docs/adr/](../../docs/adr/)
234
253
  - MCP transports — [2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports)
@@ -9,12 +9,13 @@ export interface LightdashTokenResponse {
9
9
  /** Exchanges an authorization code at Lightdash using the server-held confidential client. */
10
10
  export declare function exchangeLightdashAuthorizationCode(config: McpHttpConfig, code: string): Promise<LightdashTokenResponse>;
11
11
  /**
12
- * Builds the Lightdash authorize URL for the server-held confidential client.
13
- * Client PKCE is enforced between MCP client and broker only — do not forward
14
- * the client's code_challenge upstream (token exchange uses client_secret).
12
+ * Builds the downstream Lightdash authorize URL for the server-held confidential client.
13
+ *
14
+ * Client PKCE, MCP scopes, and RFC 8707 `resource` are properties of the MCP client→broker
15
+ * authorization leg. They must not be forwarded blindly to Lightdash: the downstream
16
+ * authorization leg has a different client and protected resource. The broker state is the
17
+ * only client-flow correlation value propagated upstream.
15
18
  */
16
19
  export declare function buildLightdashAuthorizeUrl(config: McpHttpConfig, params: {
17
20
  state: string;
18
- scope?: string;
19
- resource?: string;
20
21
  }): string;
@@ -52,9 +52,12 @@ async function exchangeLightdashAuthorizationCode(config, code) {
52
52
  return parseLightdashTokenResponse(await response.json());
53
53
  }
54
54
  /**
55
- * Builds the Lightdash authorize URL for the server-held confidential client.
56
- * Client PKCE is enforced between MCP client and broker only — do not forward
57
- * the client's code_challenge upstream (token exchange uses client_secret).
55
+ * Builds the downstream Lightdash authorize URL for the server-held confidential client.
56
+ *
57
+ * Client PKCE, MCP scopes, and RFC 8707 `resource` are properties of the MCP client→broker
58
+ * authorization leg. They must not be forwarded blindly to Lightdash: the downstream
59
+ * authorization leg has a different client and protected resource. The broker state is the
60
+ * only client-flow correlation value propagated upstream.
58
61
  */
59
62
  function buildLightdashAuthorizeUrl(config, params) {
60
63
  if (!config.oauthClientId) {
@@ -65,12 +68,5 @@ function buildLightdashAuthorizeUrl(config, params) {
65
68
  url.searchParams.set('client_id', config.oauthClientId);
66
69
  url.searchParams.set('redirect_uri', (0, load_mcp_config_js_1.getOAuthCallbackUrl)(config));
67
70
  url.searchParams.set('state', params.state);
68
- if (params.scope) {
69
- url.searchParams.set('scope', params.scope);
70
- }
71
- // Forward resource when Lightdash supports RFC 8707; harmless if ignored.
72
- if (params.resource) {
73
- url.searchParams.set('resource', params.resource);
74
- }
75
71
  return url.toString();
76
72
  }
@@ -0,0 +1,31 @@
1
+ import type { McpHttpConfig } from '../../config/load-mcp-config.js';
2
+ export interface McpAccessTokenPayload {
3
+ v: 1;
4
+ /** Server-held downstream Lightdash credential. Never return this field to MCP clients. */
5
+ lightdashAccessToken: string;
6
+ /** MCP OAuth client_id that completed the broker flow. */
7
+ clientId: string;
8
+ /** Exact RFC 8707 MCP protected-resource URI this token is valid for. */
9
+ resource: string;
10
+ /** MCP authorization scope, not the downstream Lightdash token scope. */
11
+ scope?: string;
12
+ /** Unix timestamp in seconds. */
13
+ iat: number;
14
+ /** Unix timestamp in seconds. */
15
+ exp: number;
16
+ }
17
+ export declare function mintMcpAccessToken(config: McpHttpConfig, input: {
18
+ lightdashAccessToken: string;
19
+ clientId: string;
20
+ resource: string;
21
+ scope?: string;
22
+ expiresAtMs: number;
23
+ }, nowMs?: number): {
24
+ accessToken: string;
25
+ expiresIn: number;
26
+ };
27
+ /**
28
+ * Authenticates/decrypts an MCP-issued bearer token and enforces its exact resource audience.
29
+ * Returns undefined for malformed, tampered, expired, or cross-resource tokens.
30
+ */
31
+ export declare function verifyMcpAccessToken(config: McpHttpConfig, token: string, expectedResource: string, nowMs?: number): McpAccessTokenPayload | undefined;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mintMcpAccessToken = mintMcpAccessToken;
4
+ exports.verifyMcpAccessToken = verifyMcpAccessToken;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const TOKEN_PREFIX = 'ldmcp1';
7
+ const KEY_CONTEXT = 'lightdash-tools:mcp-oauth-access-token:v1';
8
+ const AAD = Buffer.from(KEY_CONTEXT, 'utf8');
9
+ const IV_BYTES = 12;
10
+ const AUTH_TAG_BYTES = 16;
11
+ const MAX_TOKEN_LENGTH = 16 * 1024;
12
+ function deriveEncryptionKey(config) {
13
+ if (!config.oauthClientSecret) {
14
+ throw new Error('OAuth client secret is required to protect MCP access tokens');
15
+ }
16
+ // The confidential Lightdash client secret is already shared by every broker replica.
17
+ // Derive a purpose-specific 256-bit key so the raw secret is never used directly as an AES key.
18
+ return (0, node_crypto_1.createHmac)('sha256', config.oauthClientSecret.expose()).update(KEY_CONTEXT).digest();
19
+ }
20
+ function isNonEmptyString(value) {
21
+ return typeof value === 'string' && value.length > 0;
22
+ }
23
+ function isOptionalString(value) {
24
+ return value === undefined || typeof value === 'string';
25
+ }
26
+ function isSafeInteger(value) {
27
+ return typeof value === 'number' && Number.isSafeInteger(value);
28
+ }
29
+ function isPayload(value) {
30
+ if (typeof value !== 'object' || value === null)
31
+ return false;
32
+ const record = value;
33
+ return (record.v === 1 &&
34
+ isNonEmptyString(record.lightdashAccessToken) &&
35
+ isNonEmptyString(record.clientId) &&
36
+ isNonEmptyString(record.resource) &&
37
+ isOptionalString(record.scope) &&
38
+ isSafeInteger(record.iat) &&
39
+ isSafeInteger(record.exp));
40
+ }
41
+ function mintMcpAccessToken(config, input, nowMs = Date.now()) {
42
+ const nowSeconds = Math.floor(nowMs / 1000);
43
+ const exp = Math.floor(input.expiresAtMs / 1000);
44
+ const expiresIn = exp - nowSeconds;
45
+ if (expiresIn <= 0) {
46
+ throw new Error('Upstream Lightdash access token is already expired');
47
+ }
48
+ const payload = {
49
+ v: 1,
50
+ lightdashAccessToken: input.lightdashAccessToken,
51
+ clientId: input.clientId,
52
+ resource: input.resource,
53
+ scope: input.scope,
54
+ iat: nowSeconds,
55
+ exp,
56
+ };
57
+ const iv = (0, node_crypto_1.randomBytes)(IV_BYTES);
58
+ const cipher = (0, node_crypto_1.createCipheriv)('aes-256-gcm', deriveEncryptionKey(config), iv);
59
+ cipher.setAAD(AAD);
60
+ const ciphertext = Buffer.concat([
61
+ cipher.update(JSON.stringify(payload), 'utf8'),
62
+ cipher.final(),
63
+ ]);
64
+ const tag = cipher.getAuthTag();
65
+ return {
66
+ accessToken: [
67
+ TOKEN_PREFIX,
68
+ iv.toString('base64url'),
69
+ ciphertext.toString('base64url'),
70
+ tag.toString('base64url'),
71
+ ].join('.'),
72
+ expiresIn,
73
+ };
74
+ }
75
+ /**
76
+ * Authenticates/decrypts an MCP-issued bearer token and enforces its exact resource audience.
77
+ * Returns undefined for malformed, tampered, expired, or cross-resource tokens.
78
+ */
79
+ function verifyMcpAccessToken(config, token, expectedResource, nowMs = Date.now()) {
80
+ if (token.length === 0 || token.length > MAX_TOKEN_LENGTH)
81
+ return undefined;
82
+ const parts = token.split('.');
83
+ if (parts.length !== 4 || parts[0] !== TOKEN_PREFIX)
84
+ return undefined;
85
+ try {
86
+ const iv = Buffer.from(parts[1], 'base64url');
87
+ const ciphertext = Buffer.from(parts[2], 'base64url');
88
+ const tag = Buffer.from(parts[3], 'base64url');
89
+ if (iv.length !== IV_BYTES || tag.length !== AUTH_TAG_BYTES || ciphertext.length === 0) {
90
+ return undefined;
91
+ }
92
+ const decipher = (0, node_crypto_1.createDecipheriv)('aes-256-gcm', deriveEncryptionKey(config), iv);
93
+ decipher.setAAD(AAD);
94
+ decipher.setAuthTag(tag);
95
+ const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
96
+ const parsed = JSON.parse(plaintext);
97
+ if (!isPayload(parsed))
98
+ return undefined;
99
+ const nowSeconds = Math.floor(nowMs / 1000);
100
+ if (parsed.exp <= nowSeconds || parsed.iat > nowSeconds + 60)
101
+ return undefined;
102
+ if (parsed.resource !== expectedResource)
103
+ return undefined;
104
+ return parsed;
105
+ }
106
+ catch (_a) {
107
+ return undefined;
108
+ }
109
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const client_1 = require("@lightdash-tools/client");
4
+ const vitest_1 = require("vitest");
5
+ const test_mcp_http_config_js_1 = require("../../config/test-mcp-http-config.js");
6
+ const mcp_access_token_js_1 = require("./mcp-access-token.js");
7
+ const config = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
8
+ oauthClientId: 'ld-client',
9
+ oauthClientSecret: new client_1.SecretString('test-lightdash-confidential-client-secret'),
10
+ });
11
+ const RESOURCE = 'https://mcp.example.com/semantic-layer/v1/mcp';
12
+ const OTHER_RESOURCE = 'https://mcp.example.com/content-governance/v1/mcp';
13
+ const NOW = 1800000000000;
14
+ (0, vitest_1.describe)('MCP broker access token', () => {
15
+ (0, vitest_1.it)('round-trips a downstream credential without exposing it as the bearer token', () => {
16
+ const minted = (0, mcp_access_token_js_1.mintMcpAccessToken)(config, {
17
+ lightdashAccessToken: 'ld-upstream-secret',
18
+ clientId: 'mcp-client-1',
19
+ resource: RESOURCE,
20
+ scope: 'mcp:read',
21
+ expiresAtMs: NOW + 60000,
22
+ }, NOW);
23
+ (0, vitest_1.expect)(minted.accessToken).toMatch(/^ldmcp1\./);
24
+ (0, vitest_1.expect)(minted.accessToken).not.toContain('ld-upstream-secret');
25
+ (0, vitest_1.expect)(minted.expiresIn).toBe(60);
26
+ (0, vitest_1.expect)((0, mcp_access_token_js_1.verifyMcpAccessToken)(config, minted.accessToken, RESOURCE, NOW)).toMatchObject({
27
+ lightdashAccessToken: 'ld-upstream-secret',
28
+ clientId: 'mcp-client-1',
29
+ resource: RESOURCE,
30
+ scope: 'mcp:read',
31
+ });
32
+ });
33
+ (0, vitest_1.it)('rejects a token at a different MCP protected resource', () => {
34
+ const { accessToken } = (0, mcp_access_token_js_1.mintMcpAccessToken)(config, {
35
+ lightdashAccessToken: 'ld-upstream-secret',
36
+ clientId: 'mcp-client-1',
37
+ resource: RESOURCE,
38
+ expiresAtMs: NOW + 60000,
39
+ }, NOW);
40
+ (0, vitest_1.expect)((0, mcp_access_token_js_1.verifyMcpAccessToken)(config, accessToken, OTHER_RESOURCE, NOW)).toBeUndefined();
41
+ });
42
+ (0, vitest_1.it)('rejects tampered and expired tokens', () => {
43
+ const { accessToken } = (0, mcp_access_token_js_1.mintMcpAccessToken)(config, {
44
+ lightdashAccessToken: 'ld-upstream-secret',
45
+ clientId: 'mcp-client-1',
46
+ resource: RESOURCE,
47
+ expiresAtMs: NOW + 1000,
48
+ }, NOW);
49
+ // Mutate the first Base64URL character of the authentication-tag segment. Changing
50
+ // the final character can alter only unused padding bits and still decode to identical bytes.
51
+ const parts = accessToken.split('.');
52
+ const tag = parts[3];
53
+ parts[3] = `${tag[0] === 'A' ? 'B' : 'A'}${tag.slice(1)}`;
54
+ const tampered = parts.join('.');
55
+ (0, vitest_1.expect)((0, mcp_access_token_js_1.verifyMcpAccessToken)(config, tampered, RESOURCE, NOW)).toBeUndefined();
56
+ (0, vitest_1.expect)((0, mcp_access_token_js_1.verifyMcpAccessToken)(config, accessToken, RESOURCE, NOW + 2000)).toBeUndefined();
57
+ });
58
+ (0, vitest_1.it)('rejects raw downstream Lightdash access tokens', () => {
59
+ (0, vitest_1.expect)((0, mcp_access_token_js_1.verifyMcpAccessToken)(config, 'ld-upstream-secret', RESOURCE, NOW)).toBeUndefined();
60
+ });
61
+ });
@@ -2,7 +2,8 @@
2
2
  * OAuth broker pending / codes / DCR clients (ADR-0007 / ADR-0019).
3
3
  *
4
4
  * All values are JSON-serializable. Backend: in-memory only — process-local.
5
- * Multi-instance OAuth needs sticky `/oauth/*` or a single replica until signed-state/CIMD.
5
+ * Multi-instance OAuth authorization/code exchange needs sticky `/oauth/*` or a single replica.
6
+ * Issued MCP access tokens are self-contained and do not depend on this store after exchange.
6
7
  */
7
8
  export interface PendingAuthorization {
8
9
  /** Broker state sent to Lightdash (opaque). */
@@ -15,6 +16,9 @@ export interface PendingAuthorization {
15
16
  clientState?: string;
16
17
  codeChallenge: string;
17
18
  codeChallengeMethod: string;
19
+ /** Exact RFC 8707 MCP protected-resource URI requested by the client. */
20
+ resource: string;
21
+ /** MCP authorization scope. This is not a downstream Lightdash scope. */
18
22
  scope?: string;
19
23
  createdAt: number;
20
24
  }
@@ -24,9 +28,13 @@ export interface IssuedAuthorizationCode {
24
28
  redirectUri: string;
25
29
  codeChallenge: string;
26
30
  codeChallengeMethod: string;
31
+ /** Server-held downstream Lightdash access token; never return it directly to MCP clients. */
27
32
  accessToken: string;
28
33
  expiresIn?: number;
29
34
  tokenType: string;
35
+ /** Exact RFC 8707 MCP protected-resource URI bound during authorization. */
36
+ resource: string;
37
+ /** MCP authorization scope. */
30
38
  scope?: string;
31
39
  createdAt: number;
32
40
  }
@@ -66,7 +74,6 @@ export interface OAuthBrokerStore {
66
74
  accessToken: string;
67
75
  expiresIn?: number;
68
76
  tokenType?: string;
69
- scope?: string;
70
77
  }): Promise<IssuedAuthorizationCode | undefined>;
71
78
  /** Atomic get+delete for one-time code consume. */
72
79
  takeCode(code: string): Promise<IssuedAuthorizationCode | undefined>;
@@ -109,7 +116,6 @@ export declare class InMemoryOAuthBrokerStore implements OAuthBrokerStore {
109
116
  accessToken: string;
110
117
  expiresIn?: number;
111
118
  tokenType?: string;
112
- scope?: string;
113
119
  }): Promise<IssuedAuthorizationCode | undefined>;
114
120
  /** Atomic get+delete of an issued authorization code. */
115
121
  takeCode(code: string): Promise<IssuedAuthorizationCode | undefined>;
@@ -3,7 +3,8 @@
3
3
  * OAuth broker pending / codes / DCR clients (ADR-0007 / ADR-0019).
4
4
  *
5
5
  * All values are JSON-serializable. Backend: in-memory only — process-local.
6
- * Multi-instance OAuth needs sticky `/oauth/*` or a single replica until signed-state/CIMD.
6
+ * Multi-instance OAuth authorization/code exchange needs sticky `/oauth/*` or a single replica.
7
+ * Issued MCP access tokens are self-contained and do not depend on this store after exchange.
7
8
  */
8
9
  Object.defineProperty(exports, "__esModule", { value: true });
9
10
  exports.InMemoryOAuthBrokerStore = exports.DEFAULT_MAX_CLIENTS = exports.DEFAULT_MAX_CODES = exports.DEFAULT_MAX_PENDING = exports.DEFAULT_CLIENT_TTL_MS = exports.DEFAULT_CODE_TTL_MS = exports.DEFAULT_PENDING_TTL_MS = void 0;
@@ -79,7 +80,7 @@ class InMemoryOAuthBrokerStore {
79
80
  return pending;
80
81
  }
81
82
  async issueCode(pending, tokens) {
82
- var _a, _b;
83
+ var _a;
83
84
  this.cleanup();
84
85
  if (this.codes.size >= this.maxCodes) {
85
86
  return undefined;
@@ -93,7 +94,8 @@ class InMemoryOAuthBrokerStore {
93
94
  accessToken: tokens.accessToken,
94
95
  expiresIn: tokens.expiresIn,
95
96
  tokenType: (_a = tokens.tokenType) !== null && _a !== void 0 ? _a : 'Bearer',
96
- scope: (_b = tokens.scope) !== null && _b !== void 0 ? _b : pending.scope,
97
+ resource: pending.resource,
98
+ scope: pending.scope,
97
99
  createdAt: Date.now(),
98
100
  };
99
101
  this.codes.set(issued.code, issued);
@@ -6,43 +6,47 @@
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  const vitest_1 = require("vitest");
8
8
  const pending_store_js_1 = require("./pending-store.js");
9
+ const RESOURCE = 'https://mcp.example.com/semantic-layer/v1/mcp';
10
+ function pendingInput(clientId = 'c1') {
11
+ return {
12
+ clientId,
13
+ redirectUri: 'http://127.0.0.1:1/cb',
14
+ codeChallenge: 'ch',
15
+ codeChallengeMethod: 'S256',
16
+ resource: RESOURCE,
17
+ };
18
+ }
9
19
  (0, vitest_1.describe)('InMemoryOAuthBrokerStore', () => {
10
- (0, vitest_1.it)('createPending / takePending is single-use', async () => {
20
+ (0, vitest_1.it)('createPending / takePending is single-use and keeps the MCP resource', async () => {
11
21
  var _a;
12
22
  const store = new pending_store_js_1.InMemoryOAuthBrokerStore();
13
- const pending = await store.createPending({
14
- clientId: 'c1',
15
- redirectUri: 'http://127.0.0.1:1/cb',
16
- codeChallenge: 'ch',
17
- codeChallengeMethod: 'S256',
18
- });
23
+ const pending = await store.createPending(pendingInput());
19
24
  (0, vitest_1.expect)(pending === null || pending === void 0 ? void 0 : pending.brokerState).toBeTruthy();
25
+ (0, vitest_1.expect)(pending === null || pending === void 0 ? void 0 : pending.resource).toBe(RESOURCE);
20
26
  (0, vitest_1.expect)((_a = (await store.takePending(pending.brokerState))) === null || _a === void 0 ? void 0 : _a.clientId).toBe('c1');
21
27
  (0, vitest_1.expect)(await store.takePending(pending.brokerState)).toBeUndefined();
22
28
  });
23
- (0, vitest_1.it)('issueCode / takeCode is single-use', async () => {
29
+ (0, vitest_1.it)('issueCode / takeCode is single-use and carries MCP resource/scope', async () => {
24
30
  var _a;
25
31
  const store = new pending_store_js_1.InMemoryOAuthBrokerStore();
26
- const pending = await store.createPending({
27
- clientId: 'c1',
28
- redirectUri: 'http://127.0.0.1:1/cb',
29
- codeChallenge: 'ch',
30
- codeChallengeMethod: 'S256',
31
- });
32
+ const pending = await store.createPending(Object.assign(Object.assign({}, pendingInput()), { scope: 'mcp:read' }));
32
33
  const issued = await store.issueCode(pending, { accessToken: 'tok' });
33
34
  (0, vitest_1.expect)(issued === null || issued === void 0 ? void 0 : issued.accessToken).toBe('tok');
35
+ (0, vitest_1.expect)(issued === null || issued === void 0 ? void 0 : issued.resource).toBe(RESOURCE);
36
+ (0, vitest_1.expect)(issued === null || issued === void 0 ? void 0 : issued.scope).toBe('mcp:read');
34
37
  (0, vitest_1.expect)((_a = (await store.takeCode(issued.code))) === null || _a === void 0 ? void 0 : _a.clientId).toBe('c1');
35
38
  (0, vitest_1.expect)(await store.takeCode(issued.code)).toBeUndefined();
36
39
  });
40
+ (0, vitest_1.it)('does not substitute a downstream token scope for the MCP scope', async () => {
41
+ const store = new pending_store_js_1.InMemoryOAuthBrokerStore();
42
+ const pending = await store.createPending(Object.assign(Object.assign({}, pendingInput()), { scope: 'mcp:write' }));
43
+ const issued = await store.issueCode(pending, { accessToken: 'tok' });
44
+ (0, vitest_1.expect)(issued === null || issued === void 0 ? void 0 : issued.scope).toBe('mcp:write');
45
+ });
37
46
  (0, vitest_1.it)('restoreCode re-inserts a taken code for retry', async () => {
38
47
  var _a;
39
48
  const store = new pending_store_js_1.InMemoryOAuthBrokerStore({ codeTtlMs: 60000 });
40
- const pending = await store.createPending({
41
- clientId: 'c1',
42
- redirectUri: 'http://127.0.0.1:1/cb',
43
- codeChallenge: 'ch',
44
- codeChallengeMethod: 'S256',
45
- });
49
+ const pending = await store.createPending(pendingInput());
46
50
  const issued = await store.issueCode(pending, { accessToken: 'tok' });
47
51
  const taken = await store.takeCode(issued.code);
48
52
  (0, vitest_1.expect)(taken === null || taken === void 0 ? void 0 : taken.accessToken).toBe('tok');
@@ -52,12 +56,7 @@ const pending_store_js_1 = require("./pending-store.js");
52
56
  });
53
57
  (0, vitest_1.it)('restoreCode skips codes whose TTL has already elapsed', async () => {
54
58
  const store = new pending_store_js_1.InMemoryOAuthBrokerStore({ codeTtlMs: 1000 });
55
- const pending = await store.createPending({
56
- clientId: 'c1',
57
- redirectUri: 'http://127.0.0.1:1/cb',
58
- codeChallenge: 'ch',
59
- codeChallengeMethod: 'S256',
60
- });
59
+ const pending = await store.createPending(pendingInput());
61
60
  const issued = await store.issueCode(pending, { accessToken: 'tok' });
62
61
  const taken = await store.takeCode(issued.code);
63
62
  (0, vitest_1.expect)(taken).toBeDefined();
@@ -67,12 +66,7 @@ const pending_store_js_1 = require("./pending-store.js");
67
66
  (0, vitest_1.it)('getCode / deleteCode still work for peek diagnostics', async () => {
68
67
  var _a;
69
68
  const store = new pending_store_js_1.InMemoryOAuthBrokerStore();
70
- const pending = await store.createPending({
71
- clientId: 'c1',
72
- redirectUri: 'http://127.0.0.1:1/cb',
73
- codeChallenge: 'ch',
74
- codeChallengeMethod: 'S256',
75
- });
69
+ const pending = await store.createPending(pendingInput());
76
70
  const issued = await store.issueCode(pending, { accessToken: 'tok' });
77
71
  (0, vitest_1.expect)((_a = (await store.getCode(issued.code))) === null || _a === void 0 ? void 0 : _a.clientId).toBe('c1');
78
72
  await store.deleteCode(issued.code);
@@ -87,19 +81,9 @@ const pending_store_js_1 = require("./pending-store.js");
87
81
  });
88
82
  (0, vitest_1.it)('enforces maxPending after cleanup', async () => {
89
83
  const store = new pending_store_js_1.InMemoryOAuthBrokerStore({ maxPending: 1 });
90
- const first = await store.createPending({
91
- clientId: 'c1',
92
- redirectUri: 'http://127.0.0.1:1/cb',
93
- codeChallenge: 'ch',
94
- codeChallengeMethod: 'S256',
95
- });
84
+ const first = await store.createPending(pendingInput());
96
85
  (0, vitest_1.expect)(first).toBeDefined();
97
- (0, vitest_1.expect)(await store.createPending({
98
- clientId: 'c2',
99
- redirectUri: 'http://127.0.0.1:1/cb',
100
- codeChallenge: 'ch',
101
- codeChallengeMethod: 'S256',
102
- })).toBeUndefined();
86
+ (0, vitest_1.expect)(await store.createPending(pendingInput('c2'))).toBeUndefined();
103
87
  });
104
88
  (0, vitest_1.it)('enforces maxClients', async () => {
105
89
  const store = new pending_store_js_1.InMemoryOAuthBrokerStore({ maxClients: 1 });
@@ -8,6 +8,7 @@ export interface OAuthBroker {
8
8
  export declare function isOAuthBrokerPath(path: string): boolean;
9
9
  /**
10
10
  * Creates the OAuth broker request handler for co-located AS façade routes.
11
- * Pending state is process-local (InMemoryOAuthBrokerStore); sticky `/oauth/*` for multi-instance.
11
+ * Pending authorization/code state is process-local, so `/oauth/*` still needs
12
+ * sticky routing or one replica. Issued MCP access tokens are self-contained.
12
13
  */
13
14
  export declare function createOAuthBroker(config: McpHttpConfig, store?: OAuthBrokerStore): OAuthBroker;