@lightdash-tools/mcp 0.13.2 → 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 (137) hide show
  1. package/README.md +54 -18
  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/request-state-key.d.ts +1 -1
  15. package/dist/auth/request-state-key.js +1 -1
  16. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +2 -0
  17. package/dist/auth/resource-server/lightdash-oauth-middleware.js +58 -37
  18. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +59 -57
  19. package/dist/auth/resource-server/oauth-protected-resource.d.ts +2 -2
  20. package/dist/auth/resource-server/oauth-protected-resource.js +10 -9
  21. package/dist/bin.js +34 -8
  22. package/dist/config/enabled-profiles.d.ts +23 -0
  23. package/dist/config/enabled-profiles.js +57 -0
  24. package/dist/config/enabled-profiles.test.d.ts +1 -0
  25. package/dist/config/enabled-profiles.test.js +62 -0
  26. package/dist/config/env.d.ts +7 -0
  27. package/dist/config/env.js +8 -1
  28. package/dist/config/load-mcp-config.d.ts +15 -1
  29. package/dist/config/load-mcp-config.js +21 -9
  30. package/dist/config/load-mcp-config.test.js +61 -0
  31. package/dist/config/prompt-context-policy.d.ts +18 -0
  32. package/dist/config/prompt-context-policy.js +40 -0
  33. package/dist/config/prompt-context-policy.test.d.ts +4 -0
  34. package/dist/config/prompt-context-policy.test.js +35 -0
  35. package/dist/config/test-mcp-http-config.js +4 -1
  36. package/dist/governance/mcp-post-factory-context.d.ts +2 -0
  37. package/dist/http.d.ts +7 -1
  38. package/dist/http.integration.test.js +102 -44
  39. package/dist/http.js +10 -1
  40. package/dist/index.d.ts +6 -1
  41. package/dist/index.integration.test.js +3 -12
  42. package/dist/index.js +6 -3
  43. package/dist/policy/content-developer.d.ts +5 -0
  44. package/dist/policy/content-developer.js +25 -1
  45. package/dist/policy/content-developer.test.js +29 -0
  46. package/dist/profiles/ai-agent-ops/v1/invariants.d.ts +27 -0
  47. package/dist/profiles/ai-agent-ops/v1/invariants.js +39 -0
  48. package/dist/profiles/ai-agent-ops/v1/prompts.d.ts +3 -2
  49. package/dist/profiles/ai-agent-ops/v1/prompts.js +67 -41
  50. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.d.ts +2 -1
  51. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.js +10 -3
  52. package/dist/profiles/content-developer/v1/invariants.d.ts +69 -0
  53. package/dist/profiles/content-developer/v1/invariants.js +95 -0
  54. package/dist/profiles/content-developer/v1/prompt-specs.d.ts +32 -0
  55. package/dist/profiles/content-developer/v1/prompt-specs.js +56 -0
  56. package/dist/profiles/content-developer/v1/prompts.d.ts +4 -3
  57. package/dist/profiles/content-developer/v1/prompts.js +65 -71
  58. package/dist/profiles/content-developer/v1/prompts.test.js +61 -7
  59. package/dist/profiles/content-developer/v1/resources/playbooks/chart-types.md +2 -1
  60. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +3 -1
  61. package/dist/profiles/content-developer/v1/resources/playbooks/dashboard-design.md +11 -1
  62. package/dist/profiles/content-developer/v1/resources/playbooks/dashboards.md +1 -1
  63. package/dist/profiles/content-developer/v1/resources/playbooks/index.md +11 -8
  64. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/dashboard-diff.md +15 -0
  65. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-required.md +14 -0
  66. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-stale.md +21 -0
  67. package/dist/profiles/content-developer/v1/resources/playbooks/table-calculations.md +15 -3
  68. package/dist/profiles/content-developer/v1/resources/playbooks.d.ts +3 -2
  69. package/dist/profiles/content-developer/v1/resources/playbooks.js +35 -21
  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/index.js +1 -0
  77. package/dist/profiles/content-reader/v1/invariants.d.ts +33 -0
  78. package/dist/profiles/content-reader/v1/invariants.js +47 -0
  79. package/dist/profiles/content-reader/v1/prompt-specs.d.ts +18 -0
  80. package/dist/profiles/content-reader/v1/prompt-specs.js +33 -0
  81. package/dist/profiles/content-reader/v1/prompts.d.ts +3 -2
  82. package/dist/profiles/content-reader/v1/prompts.js +69 -75
  83. package/dist/profiles/content-reader/v1/resources/playbooks/compare.md +1 -1
  84. package/dist/profiles/content-reader/v1/resources/playbooks/core.md +1 -0
  85. package/dist/profiles/content-reader/v1/resources/playbooks/discover.md +12 -3
  86. package/dist/profiles/content-reader/v1/resources/playbooks/explain-run.md +2 -1
  87. package/dist/profiles/content-reader/v1/resources/playbooks.d.ts +2 -1
  88. package/dist/profiles/content-reader/v1/resources/playbooks.js +10 -11
  89. package/dist/profiles/data-analyst/v1/invariants.d.ts +21 -0
  90. package/dist/profiles/data-analyst/v1/invariants.js +31 -0
  91. package/dist/profiles/data-analyst/v1/prompts.d.ts +3 -2
  92. package/dist/profiles/data-analyst/v1/prompts.js +17 -9
  93. package/dist/profiles/data-analyst/v1/resources/playbooks.d.ts +2 -1
  94. package/dist/profiles/data-analyst/v1/resources/playbooks.js +6 -7
  95. package/dist/profiles/index.d.ts +2 -1
  96. package/dist/profiles/index.js +2 -1
  97. package/dist/profiles/index.test.js +2 -1
  98. package/dist/profiles/lib/playbook-resources.d.ts +16 -34
  99. package/dist/profiles/lib/playbook-resources.js +55 -76
  100. package/dist/profiles/lib/prompt-context.d.ts +71 -0
  101. package/dist/profiles/lib/prompt-context.js +205 -0
  102. package/dist/profiles/lib/prompt-context.test.d.ts +4 -0
  103. package/dist/profiles/lib/prompt-context.test.js +154 -0
  104. package/dist/profiles/lib/prompt-invariants.d.ts +20 -0
  105. package/dist/profiles/lib/prompt-invariants.js +54 -0
  106. package/dist/profiles/organization-audit/v1/invariants.d.ts +24 -0
  107. package/dist/profiles/organization-audit/v1/invariants.js +35 -0
  108. package/dist/profiles/organization-audit/v1/prompts.d.ts +3 -2
  109. package/dist/profiles/organization-audit/v1/prompts.js +44 -28
  110. package/dist/profiles/organization-audit/v1/resources/playbooks.d.ts +2 -1
  111. package/dist/profiles/organization-audit/v1/resources/playbooks.js +10 -3
  112. package/dist/profiles/semantic-layer/v1/invariants.d.ts +27 -0
  113. package/dist/profiles/semantic-layer/v1/invariants.js +39 -0
  114. package/dist/profiles/semantic-layer/v1/prompts.d.ts +3 -2
  115. package/dist/profiles/semantic-layer/v1/prompts.js +37 -26
  116. package/dist/profiles/semantic-layer/v1/resources/playbooks.d.ts +2 -4
  117. package/dist/profiles/semantic-layer/v1/resources/playbooks.js +8 -7
  118. package/dist/profiles/test-support/prompt-context-budget.test.d.ts +5 -0
  119. package/dist/profiles/test-support/prompt-context-budget.test.js +72 -0
  120. package/dist/profiles/types.d.ts +6 -1
  121. package/dist/server/capabilities.d.ts +3 -0
  122. package/dist/server/capabilities.js +4 -2
  123. package/dist/stdio.process.test.js +2 -1
  124. package/dist/tools/lib/schema-fields.d.ts +4 -0
  125. package/dist/tools/lib/schema-fields.js +8 -1
  126. package/dist/tools/project/developer-content-preview.js +1 -1
  127. package/dist/tools/project/developer-content.js +2 -2
  128. package/dist/tools/project/reader-content.d.ts +2 -0
  129. package/dist/tools/project/reader-content.js +28 -1
  130. package/dist/tools/query/reader-tool-helpers.d.ts +2 -2
  131. package/dist/tools/query/reader-tool-helpers.js +2 -2
  132. package/dist/tools/query/reader-tool-helpers.test.js +1 -0
  133. package/dist/tools/shared.d.ts +6 -1
  134. package/dist/tools/shared.js +12 -2
  135. package/dist/transports/streamable-http.js +16 -6
  136. package/dist/transports/streamable-http.test.js +16 -0
  137. package/package.json +3 -3
package/README.md CHANGED
@@ -55,7 +55,7 @@ Or install globally: `npm install -g @lightdash-tools/mcp`, then `lightdash-mcp
55
55
 
56
56
  ### Streamable HTTP (remote)
57
57
 
58
- `http` mounts **every** fixed path from the profile table (no `--profile`); clients pick the path in the URL.
58
+ `http` mounts every fixed path from the profile table by default (no `--profile`); clients pick the path in the URL. Optionally restrict mounts with `LIGHTDASH_TOOLS_MCP_PROFILES` (comma-separated profile ids; unset or empty → all).
59
59
 
60
60
  ```bash
61
61
  export LIGHTDASH_URL="https://app.lightdash.cloud"
@@ -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
 
@@ -87,9 +96,9 @@ Do **not** set OAuth client secrets for stdio. MCP ignores CLI `SAFETY_MODE` / `
87
96
 
88
97
  ### HTTP OAuth (primary)
89
98
 
90
- | Required | Common optional |
91
- | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ |
92
- | `LIGHTDASH_URL`, `LIGHTDASH_TOOLS_MCP_PUBLIC_URL`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_ID`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET` | port, `ALLOWED_ORIGINS`, [`LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS`](#project-allowlist), token cache TTL |
99
+ | Required | Common optional |
100
+ | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |
101
+ | `LIGHTDASH_URL`, `LIGHTDASH_TOOLS_MCP_PUBLIC_URL`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_ID`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET` | port, `ALLOWED_ORIGINS`, [`LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS`](#project-allowlist), [`LIGHTDASH_TOOLS_MCP_PROFILES`](#profile-allowlist), token cache TTL |
93
102
 
94
103
  On Cloud Run / hosted HTTP, leave `LIGHTDASH_TOOLS_AUDIT_LOG` unset — tool audits are stderr JSON (`channel: "audit"`) → Cloud Logging. See [cloud-run.md](../../docs/operators/cloud-run.md).
95
104
 
@@ -97,9 +106,9 @@ Register Lightdash redirect URI: `{PUBLIC_URL}/oauth/callback`. Clients connect
97
106
 
98
107
  ### Content-developer / content-governance signing
99
108
 
100
- | Required (non-test) | Notes |
101
- | :-------------------------------------- | :---------------------------------------------------------------------------------------------- |
102
- | `LIGHTDASH_TOOLS_MCP_REQUEST_STATE_KEY` | ≥32-byte secret for HMAC `previewToken` / `requestState` (fail closed if unset; not encryption) |
109
+ | Required (non-test) | Notes |
110
+ | :-------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
111
+ | `LIGHTDASH_TOOLS_MCP_REQUEST_STATE_KEY` | ≥32-byte secret for HMAC `previewToken` / `requestState` (fail closed if unset; not encryption). Required only when `content-developer` or `content-governance` is mounted (including unrestricted HTTP). |
103
112
 
104
113
  Governance soft-delete needs client form elicitation; missing capability → `ELICITATION_REQUIRED`.
105
114
 
@@ -110,6 +119,42 @@ Governance soft-delete needs client form elicitation; missing capability → `EL
110
119
  | Shared-key | `LIGHTDASH_API_KEY` + `LIGHTDASH_TOOLS_MCP_SHARED_KEY` |
111
120
  | Local none | `NODE_ENV=development` (not `production`) |
112
121
 
122
+ ### Profile allowlist
123
+
124
+ Optional HTTP-only mount ceiling. Unset or empty → all seven shipped profile paths. Non-empty → only listed profile ids are mounted; other paths (and their path-specific OAuth PRM) 404. Stdio ignores this variable (`stdio --profile` still required).
125
+
126
+ **Format**
127
+
128
+ - Comma-separated profile ids from the table above (`semantic-layer`, `content-reader`, …)
129
+ - Whitespace around commas is ignored
130
+ - No empty segments (double commas are rejected)
131
+ - Unknown ids fail at process startup
132
+
133
+ ```bash
134
+ export LIGHTDASH_TOOLS_MCP_PROFILES="content-reader,content-developer"
135
+ ```
136
+
137
+ Architecture: [ADR-0024](../../docs/adr/0024-mcp-http-profile-mount-allowlist-via-env.md).
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
+
113
158
  ### Project allowlist
114
159
 
115
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.
@@ -198,20 +243,11 @@ When a tool handler throws (for example a Lightdash HTTP/API failure), MCP retur
198
243
 
199
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.
200
245
 
201
- ## Migration from `@lightdash-tools/semantic-layer-mcp`
202
-
203
- | Removed / old | Use instead |
204
- | :-------------------------------------------- | :---------------------------------------- |
205
- | `@lightdash-tools/semantic-layer-mcp` | `@lightdash-tools/mcp` |
206
- | Binary `lightdash-semantic-layer-mcp` | `lightdash-mcp` |
207
- | HTTP `/mcp` (old) | `/semantic-layer/v1/mcp` |
208
- | Unprefixed tool names | `lightdash_*` |
209
- | `lightdash-mcp <profile>` / `stdio <profile>` | `lightdash-mcp stdio --profile <profile>` |
210
-
211
246
  ## Further reading
212
247
 
213
248
  - Architecture / contributing — [CONTRIBUTING.md](./CONTRIBUTING.md)
214
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)
215
251
  - Cursor hosted OAuth — [docs/operators/cursor-claude.md](../../docs/operators/cursor-claude.md)
216
252
  - Architecture decisions — [docs/adr/](../../docs/adr/)
217
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;