@lightdash-tools/mcp 0.6.0 → 0.7.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 (271) hide show
  1. package/README.md +133 -58
  2. package/dist/audit/audit.d.ts +5 -0
  3. package/dist/{audit.js → audit/audit.js} +1 -2
  4. package/dist/audit/tool-audit-context.d.ts +6 -0
  5. package/dist/audit/tool-audit-context.js +12 -0
  6. package/dist/audit/tool-audit-context.test.d.ts +1 -0
  7. package/dist/audit/tool-audit-context.test.js +19 -0
  8. package/dist/auth/auth-mode.d.ts +4 -0
  9. package/dist/auth/auth-mode.js +6 -0
  10. package/dist/auth/bearer.d.ts +3 -0
  11. package/dist/auth/bearer.js +13 -0
  12. package/dist/auth/lightdash-oauth-upstream-contract.d.ts +22 -0
  13. package/dist/auth/lightdash-oauth-upstream-contract.js +36 -0
  14. package/dist/auth/lightdash-oauth-upstream-contract.test.d.ts +1 -0
  15. package/dist/auth/lightdash-oauth-upstream-contract.test.js +56 -0
  16. package/dist/auth/oauth-broker/as-metadata.d.ts +14 -0
  17. package/dist/auth/oauth-broker/as-metadata.js +20 -0
  18. package/dist/auth/oauth-broker/lightdash-token.d.ts +20 -0
  19. package/dist/auth/oauth-broker/lightdash-token.js +76 -0
  20. package/dist/auth/oauth-broker/pending-store.d.ts +76 -0
  21. package/dist/auth/oauth-broker/pending-store.js +124 -0
  22. package/dist/auth/oauth-broker/pkce.d.ts +2 -0
  23. package/dist/auth/oauth-broker/pkce.js +17 -0
  24. package/dist/auth/oauth-broker/routes.d.ts +9 -0
  25. package/dist/auth/oauth-broker/routes.js +447 -0
  26. package/dist/auth/oauth-broker/routes.test.d.ts +1 -0
  27. package/dist/auth/oauth-broker/routes.test.js +237 -0
  28. package/dist/auth/providers/bearer-context-provider.d.ts +24 -0
  29. package/dist/auth/providers/bearer-context-provider.js +52 -0
  30. package/dist/auth/providers/env-context-provider.d.ts +13 -0
  31. package/dist/auth/providers/env-context-provider.js +19 -0
  32. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +23 -0
  33. package/dist/auth/resource-server/lightdash-oauth-middleware.js +115 -0
  34. package/dist/auth/resource-server/lightdash-oauth-middleware.test.d.ts +1 -0
  35. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +202 -0
  36. package/dist/auth/resource-server/lightdash-token-validation.d.ts +14 -0
  37. package/dist/auth/resource-server/lightdash-token-validation.js +82 -0
  38. package/dist/auth/resource-server/lightdash-token-validation.test.d.ts +1 -0
  39. package/dist/auth/resource-server/lightdash-token-validation.test.js +177 -0
  40. package/dist/auth/resource-server/oauth-protected-resource.d.ts +25 -0
  41. package/dist/auth/resource-server/oauth-protected-resource.js +67 -0
  42. package/dist/auth/resource-server/shared-key-middleware.d.ts +13 -0
  43. package/dist/auth/resource-server/shared-key-middleware.js +24 -0
  44. package/dist/auth/resource-server/token-scopes.d.ts +15 -0
  45. package/dist/auth/resource-server/token-scopes.js +76 -0
  46. package/dist/auth/resource-server/token-scopes.test.d.ts +1 -0
  47. package/dist/auth/resource-server/token-scopes.test.js +51 -0
  48. package/dist/auth/resource-server/token-validation-cache.d.ts +15 -0
  49. package/dist/auth/resource-server/token-validation-cache.js +44 -0
  50. package/dist/auth/resource-server/token-validation-cache.test.d.ts +1 -0
  51. package/dist/auth/resource-server/token-validation-cache.test.js +41 -0
  52. package/dist/auth/resource-server/token-validation-error.d.ts +6 -0
  53. package/dist/auth/resource-server/token-validation-error.js +13 -0
  54. package/dist/auth/resource-server/www-authenticate.d.ts +8 -0
  55. package/dist/auth/resource-server/www-authenticate.js +24 -0
  56. package/dist/auth/resource-server/www-authenticate.test.d.ts +1 -0
  57. package/dist/auth/resource-server/www-authenticate.test.js +64 -0
  58. package/dist/auth/token-hash.d.ts +2 -0
  59. package/dist/auth/token-hash.js +8 -0
  60. package/dist/bin.d.ts +0 -4
  61. package/dist/bin.js +41 -33
  62. package/dist/config/env.d.ts +50 -0
  63. package/dist/config/env.js +53 -0
  64. package/dist/config/load-mcp-config.d.ts +30 -0
  65. package/dist/config/load-mcp-config.js +282 -0
  66. package/dist/config/load-mcp-config.test.d.ts +1 -0
  67. package/dist/config/load-mcp-config.test.js +195 -0
  68. package/dist/config/normalize-url.d.ts +13 -0
  69. package/dist/config/normalize-url.js +52 -0
  70. package/dist/config/normalize-url.test.d.ts +1 -0
  71. package/dist/config/normalize-url.test.js +41 -0
  72. package/dist/config/public-url.d.ts +3 -0
  73. package/dist/config/public-url.js +10 -0
  74. package/dist/config/runtime.d.ts +15 -0
  75. package/dist/config/runtime.js +48 -0
  76. package/dist/config/runtime.test.d.ts +1 -0
  77. package/dist/config/runtime.test.js +69 -0
  78. package/dist/config/test-mcp-http-config.d.ts +3 -0
  79. package/dist/config/test-mcp-http-config.js +7 -0
  80. package/dist/governance/project-pin.d.ts +14 -0
  81. package/dist/governance/project-pin.js +44 -0
  82. package/dist/governance/project-pin.test.d.ts +1 -0
  83. package/dist/governance/project-pin.test.js +35 -0
  84. package/dist/http.d.ts +1 -2
  85. package/dist/http.integration.test.d.ts +1 -0
  86. package/dist/http.integration.test.js +688 -0
  87. package/dist/http.js +3 -170
  88. package/dist/http.test.d.ts +4 -0
  89. package/dist/http.test.js +131 -0
  90. package/dist/index.d.ts +2 -0
  91. package/dist/index.integration.test.js +73 -30
  92. package/dist/index.js +28 -27
  93. package/dist/index.test.js +3 -3
  94. package/dist/logging/structured.d.ts +27 -0
  95. package/dist/logging/structured.js +32 -0
  96. package/dist/logging/structured.test.d.ts +1 -0
  97. package/dist/logging/structured.test.js +33 -0
  98. package/dist/personas/index.d.ts +19 -0
  99. package/dist/personas/index.js +57 -0
  100. package/dist/personas/index.test.d.ts +1 -0
  101. package/dist/personas/index.test.js +58 -0
  102. package/dist/personas/organization-audit/v1/index.d.ts +8 -0
  103. package/dist/personas/organization-audit/v1/index.js +42 -0
  104. package/dist/personas/organization-audit/v1/prompts.d.ts +5 -0
  105. package/dist/personas/organization-audit/v1/prompts.js +111 -0
  106. package/dist/personas/organization-audit/v1/prompts.test.d.ts +4 -0
  107. package/dist/personas/organization-audit/v1/prompts.test.js +25 -0
  108. package/dist/personas/organization-audit/v1/resources/playbook.d.ts +11 -0
  109. package/dist/personas/organization-audit/v1/resources/playbook.js +40 -0
  110. package/dist/personas/organization-audit/v1/resources/playbook.md +52 -0
  111. package/dist/personas/semantic-layer/v1/index.d.ts +8 -0
  112. package/dist/personas/semantic-layer/v1/index.js +32 -0
  113. package/dist/personas/semantic-layer/v1/prompts.d.ts +5 -0
  114. package/dist/personas/semantic-layer/v1/prompts.js +107 -0
  115. package/dist/personas/semantic-layer/v1/resources/playbook.d.ts +12 -0
  116. package/dist/personas/semantic-layer/v1/resources/playbook.js +42 -0
  117. package/dist/personas/semantic-layer/v1/resources/playbook.md +153 -0
  118. package/dist/personas/types.d.ts +19 -0
  119. package/dist/personas/types.js +5 -0
  120. package/dist/protocol-contract.test.d.ts +1 -0
  121. package/dist/protocol-contract.test.js +42 -0
  122. package/dist/server/capabilities.d.ts +15 -0
  123. package/dist/server/capabilities.js +19 -0
  124. package/dist/server/capabilities.test.d.ts +1 -0
  125. package/dist/server/capabilities.test.js +39 -0
  126. package/dist/server/errors.test.d.ts +1 -0
  127. package/dist/server/errors.test.js +53 -0
  128. package/dist/server/request-context.d.ts +13 -0
  129. package/dist/server/request-context.js +2 -0
  130. package/dist/server/server.d.ts +4 -0
  131. package/dist/server/server.js +17 -0
  132. package/dist/server/server.test.d.ts +1 -0
  133. package/dist/server/server.test.js +15 -0
  134. package/dist/server/version.d.ts +1 -0
  135. package/dist/server/version.js +7 -0
  136. package/dist/server/version.test.d.ts +1 -0
  137. package/dist/server/version.test.js +9 -0
  138. package/dist/stdio.process.test.d.ts +1 -0
  139. package/dist/stdio.process.test.js +126 -0
  140. package/dist/tools/index.d.ts +2 -4
  141. package/dist/tools/index.js +4 -30
  142. package/dist/tools/index.test.d.ts +1 -0
  143. package/dist/tools/index.test.js +72 -0
  144. package/dist/tools/lib/api-errors.d.ts +9 -0
  145. package/dist/tools/lib/api-errors.js +22 -0
  146. package/dist/tools/lib/api-shape.d.ts +16 -0
  147. package/dist/tools/lib/api-shape.js +47 -0
  148. package/dist/tools/lib/assert-safe.d.ts +13 -0
  149. package/dist/tools/lib/assert-safe.js +21 -0
  150. package/dist/tools/lib/assert-safe.test.d.ts +4 -0
  151. package/dist/tools/lib/assert-safe.test.js +32 -0
  152. package/dist/tools/lib/concurrency.d.ts +4 -0
  153. package/dist/tools/lib/concurrency.js +24 -0
  154. package/dist/tools/lib/contracts.d.ts +34 -0
  155. package/dist/tools/lib/contracts.js +30 -0
  156. package/dist/tools/lib/redaction.d.ts +107 -0
  157. package/dist/tools/lib/redaction.js +299 -0
  158. package/dist/tools/lib/redaction.test.d.ts +4 -0
  159. package/dist/tools/lib/redaction.test.js +216 -0
  160. package/dist/tools/lib/register-org-audit.d.ts +9 -0
  161. package/dist/tools/lib/register-org-audit.js +20 -0
  162. package/dist/tools/lib/schema-fields.d.ts +9 -0
  163. package/dist/tools/lib/schema-fields.js +19 -0
  164. package/dist/tools/organization/binding.d.ts +14 -0
  165. package/dist/tools/organization/binding.js +31 -0
  166. package/dist/tools/organization/invariants.test.d.ts +4 -0
  167. package/dist/tools/organization/invariants.test.js +28 -0
  168. package/dist/tools/organization/inventory.d.ts +10 -0
  169. package/dist/tools/organization/inventory.js +189 -0
  170. package/dist/tools/organization/roles.d.ts +10 -0
  171. package/dist/tools/organization/roles.js +213 -0
  172. package/dist/tools/project/content.d.ts +9 -0
  173. package/dist/tools/project/content.js +192 -0
  174. package/dist/tools/project/projects.d.ts +7 -0
  175. package/dist/tools/project/projects.js +42 -0
  176. package/dist/tools/project/projects.test.d.ts +1 -0
  177. package/dist/tools/project/projects.test.js +117 -0
  178. package/dist/tools/project/schedulers.d.ts +7 -0
  179. package/dist/tools/project/schedulers.js +115 -0
  180. package/dist/tools/registry.d.ts +104 -0
  181. package/dist/tools/registry.js +59 -0
  182. package/dist/tools/semantic/explore-helpers.d.ts +56 -0
  183. package/dist/tools/semantic/explore-helpers.js +115 -0
  184. package/dist/tools/semantic/explore-helpers.test.d.ts +1 -0
  185. package/dist/tools/semantic/explore-helpers.test.js +170 -0
  186. package/dist/tools/semantic/explores.d.ts +9 -0
  187. package/dist/tools/semantic/explores.js +80 -0
  188. package/dist/tools/semantic/metrics.d.ts +7 -0
  189. package/dist/tools/semantic/metrics.js +53 -0
  190. package/dist/tools/semantic/query.d.ts +6 -0
  191. package/dist/tools/semantic/query.js +42 -0
  192. package/dist/tools/semantic/schema-fields.d.ts +3 -0
  193. package/dist/tools/semantic/schema-fields.js +7 -0
  194. package/dist/tools/shared.d.ts +26 -13
  195. package/dist/tools/shared.js +112 -157
  196. package/dist/tools/shared.test.js +132 -183
  197. package/dist/tools/space/access.d.ts +66 -0
  198. package/dist/tools/space/access.js +322 -0
  199. package/dist/tools/space/access.test.d.ts +4 -0
  200. package/dist/tools/space/access.test.js +90 -0
  201. package/dist/transports/http-body.d.ts +5 -0
  202. package/dist/transports/http-body.js +50 -0
  203. package/dist/transports/http-request-utils.d.ts +2 -0
  204. package/dist/transports/http-request-utils.js +13 -0
  205. package/dist/transports/http-response.d.ts +6 -0
  206. package/dist/transports/http-response.js +56 -0
  207. package/dist/transports/session-store.d.ts +40 -0
  208. package/dist/transports/session-store.js +88 -0
  209. package/dist/transports/session-store.test.d.ts +1 -0
  210. package/dist/transports/session-store.test.js +111 -0
  211. package/dist/transports/streamable-http.d.ts +9 -0
  212. package/dist/transports/streamable-http.js +454 -0
  213. package/dist/transports/streamable-http.test.d.ts +1 -0
  214. package/dist/transports/streamable-http.test.js +95 -0
  215. package/package.json +25 -10
  216. package/dist/audit.d.ts +0 -6
  217. package/dist/config.d.ts +0 -47
  218. package/dist/config.js +0 -82
  219. package/dist/tools/ai-agents.d.ts +0 -6
  220. package/dist/tools/ai-agents.js +0 -388
  221. package/dist/tools/charts.d.ts +0 -6
  222. package/dist/tools/charts.js +0 -55
  223. package/dist/tools/content.d.ts +0 -6
  224. package/dist/tools/content.js +0 -37
  225. package/dist/tools/dashboards.d.ts +0 -6
  226. package/dist/tools/dashboards.js +0 -28
  227. package/dist/tools/explores.d.ts +0 -6
  228. package/dist/tools/explores.js +0 -65
  229. package/dist/tools/groups.d.ts +0 -6
  230. package/dist/tools/groups.js +0 -121
  231. package/dist/tools/metrics.d.ts +0 -6
  232. package/dist/tools/metrics.js +0 -45
  233. package/dist/tools/projects.d.ts +0 -6
  234. package/dist/tools/projects.js +0 -58
  235. package/dist/tools/query.d.ts +0 -6
  236. package/dist/tools/query.js +0 -34
  237. package/dist/tools/schedulers.d.ts +0 -6
  238. package/dist/tools/schedulers.js +0 -45
  239. package/dist/tools/spaces.d.ts +0 -6
  240. package/dist/tools/spaces.js +0 -128
  241. package/dist/tools/tags.d.ts +0 -6
  242. package/dist/tools/tags.js +0 -28
  243. package/dist/tools/users.d.ts +0 -6
  244. package/dist/tools/users.js +0 -50
  245. package/src/audit.ts +0 -6
  246. package/src/bin.ts +0 -58
  247. package/src/config.ts +0 -83
  248. package/src/errors.ts +0 -27
  249. package/src/http.ts +0 -187
  250. package/src/index.integration.test.ts +0 -57
  251. package/src/index.test.ts +0 -8
  252. package/src/index.ts +0 -31
  253. package/src/tools/ai-agents.ts +0 -759
  254. package/src/tools/charts.ts +0 -85
  255. package/src/tools/content.ts +0 -44
  256. package/src/tools/dashboards.ts +0 -25
  257. package/src/tools/explores.ts +0 -98
  258. package/src/tools/groups.ts +0 -180
  259. package/src/tools/index.ts +0 -35
  260. package/src/tools/metrics.ts +0 -42
  261. package/src/tools/projects.ts +0 -74
  262. package/src/tools/query.ts +0 -47
  263. package/src/tools/schedulers.ts +0 -42
  264. package/src/tools/shared.test.ts +0 -365
  265. package/src/tools/shared.ts +0 -274
  266. package/src/tools/spaces.ts +0 -217
  267. package/src/tools/tags.ts +0 -25
  268. package/src/tools/users.ts +0 -64
  269. package/tsconfig.json +0 -13
  270. /package/dist/{errors.d.ts → server/errors.d.ts} +0 -0
  271. /package/dist/{errors.js → server/errors.js} +0 -0
package/README.md CHANGED
@@ -1,6 +1,36 @@
1
1
  # [@lightdash-tools/mcp](https://www.npmjs.com/package/@lightdash-tools/mcp) <!-- markdown-link-check-disable-line -->
2
2
 
3
- MCP server for Lightdash: exposes projects, charts, dashboards, spaces, users, and groups as tools. Uses `@lightdash-tools/client` for all API access.
3
+ MCP server for Lightdash with **persona-scoped** surfaces: `semantic-layer` (explore/compile) and `organization-audit` (read-only org governance). Tools live in a shared registry; each persona selects an explicit `lightdash_*` allowlist, prompts, and playbook. Uses `@lightdash-tools/client` for API access. See [ADR-0006](../../docs/adr/0006-mcp-personas-shared-registry-fixed-paths.md) and [ADR-0010](../../docs/adr/0010-mcp-organization-audit-persona-read-only-boundary.md).
4
+
5
+ Mutation/admin write surfaces are **not** registered on MCP — use `@lightdash-tools/client` or the CLI.
6
+
7
+ **Response sensitivity** ([ADR-0011](../../docs/adr/0011-mcp-tool-response-sensitivity-classes.md)): `list_projects` / `get_project` return project metadata only (warehouse/dbt connection secrets are never exposed). Organization-audit tools mask emails by default (`includeEmail=true` to reveal) and redact scheduler destinations by default (`revealDestinations=true` to reveal). There is no global `withSensitive` flag.
8
+
9
+ ## Directory map
10
+
11
+ | Edit… | Path |
12
+ | :------------------------------------------------------ | :--------------------------------------------------- |
13
+ | Shared tools / registry | `src/tools/` (`registry.ts`, domain modules) |
14
+ | Persona (tools allowlist, prompts, playbook, HTTP path) | `src/personas/<id>/` |
15
+ | HTTP transport / sessions | `src/transports/` |
16
+ | HTTP auth | `src/auth/` |
17
+ | Runtime client + guardrail env | `src/config/runtime.ts` |
18
+ | HTTP env / loader | `src/config/env.ts`, `src/config/load-mcp-config.ts` |
19
+ | Audit logging helpers | `src/audit/` |
20
+ | Entrypoints | `src/bin.ts`, `src/index.ts` (stdio), `src/http.ts` |
21
+
22
+ Prompts and resources are **persona-owned** (e.g. `src/personas/semantic-layer/v1/`). There is no package-level `src/prompts/` or `src/resources/`.
23
+
24
+ ## Replaces `@lightdash-tools/semantic-layer-mcp`
25
+
26
+ That package was removed (ADR-0006). Migrate as follows:
27
+
28
+ | Removed | Use instead |
29
+ | ------------------------------------- | ------------------------ |
30
+ | `@lightdash-tools/semantic-layer-mcp` | `@lightdash-tools/mcp` |
31
+ | Binary `lightdash-semantic-layer-mcp` | `lightdash-mcp` |
32
+ | HTTP `/mcp` (old) | `/semantic-layer/v1/mcp` |
33
+ | Unprefixed tool names | `lightdash_*` |
4
34
 
5
35
  ## Installation
6
36
 
@@ -21,26 +51,54 @@ npm install -g @lightdash-tools/mcp
21
51
  - **Stdio** — for local use (e.g. Claude Desktop, IDE). One process per client.
22
52
  - **Streamable HTTP** — for remote use. Session-based; supports optional endpoint auth.
23
53
 
54
+ ### SDK / protocol compatibility
55
+
56
+ - Uses MCP TypeScript SDK v2 (`@modelcontextprotocol/server`, `@modelcontextprotocol/node`).
57
+ - Speaks the established 2025-era protocol by default (not `2026-07-28` unless a future flag).
58
+ - Hosted OAuth client setup: [docs/cursor-lightdash-oauth-mcp.md](../../docs/cursor-lightdash-oauth-mcp.md). Protocol/auth details: [docs/mcp-oauth-http.md](../../docs/mcp-oauth-http.md).
59
+
60
+ ### Hosted OAuth (primary HTTP)
61
+
62
+ Auth is **inferred** from credentials ([ADR-0007](../../docs/adr/0007-mcp-http-transport-auth-modes-sdk-v2.md)). The MCP host holds the Lightdash OAuth app client id/secret and brokers login; Claude Code / Cursor use URL-only config. Protocol reference: [MCP Authorization 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization).
63
+
64
+ | What works | Gap |
65
+ | :-------------------------------------------------------------- | :----------------------------------------------------------------------- |
66
+ | Server-held confidential client + `{PUBLIC_URL}/oauth/callback` | Full RFC 8707 audience binding on opaque Lightdash tokens |
67
+ | PRM + broker AS metadata; per-user Bearer to Lightdash | MCP-local scope enforcement for opaque tokens |
68
+ | Session binding to `userUuid` / `organizationUuid` | Horizontal scale without sticky sessions (in-memory broker/MCP sessions) |
69
+
70
+ Authorization: Lightdash RBAC + persona tool surface ([ADR-0006](../../docs/adr/0006-mcp-personas-shared-registry-fixed-paths.md)) + optional `X-Lightdash-Project` pin. See [mcp-oauth-http.md](../../docs/mcp-oauth-http.md).
71
+
24
72
  ## Environment variables
25
73
 
26
- ### Required (both modes)
74
+ Preferred names use the `LIGHTDASH_TOOLS_*` prefixes (see [ADR-0009](../../docs/adr/0009-cross-cutting-conventions.md)). Prefer env vars from the parent process. Avoid plaintext `.env` when AI agents have file access. If using `.env`, use [dotenvx](https://dotenvx.com/). See [docs/secrets-and-credentials.md](../../docs/secrets-and-credentials.md).
75
+
76
+ ### Stdio (secondary)
27
77
 
28
- - `LIGHTDASH_URL` — Lightdash instance base URL (e.g. `https://app.lightdash.cloud`).
29
- - `LIGHTDASH_API_KEY` — Personal access token or API key.
78
+ | Required | Optional |
79
+ | :----------------------------------- | :-------------------------- |
80
+ | `LIGHTDASH_URL`, `LIGHTDASH_API_KEY` | `LIGHTDASH_TOOLS_AUDIT_LOG` |
30
81
 
31
- ### Optional (both modes)
82
+ Do **not** set OAuth client secrets for stdio. MCP does not use CLI `SAFETY_MODE` / `ALLOWED_PROJECTS` / `DRY_RUN`.
32
83
 
33
- - `LIGHTDASH_TOOLS_SAFETY_MODE` — Safety mode for dynamic enforcement (`read-only`, `write-idempotent`, `write-destructive`). See [Safety Modes](#safety-modes) for details.
34
- - `LIGHTDASH_TOOLS_ALLOWED_PROJECTS` — Comma-separated project UUIDs to restrict operations (empty = all allowed). CLI `--projects` overrides.
35
- - `LIGHTDASH_TOOLS_DRY_RUN` — Set to `1`, `true`, or `yes` to simulate write operations without executing.
84
+ ### HTTP OAuth (primary)
36
85
 
37
- Prefer env vars from the parent process. Avoid plaintext `.env` when AI agents have file access. If using `.env`, use [dotenvx](https://dotenvx.com/) for encrypted secrets. See [docs/secrets-and-credentials.md](../../docs/secrets-and-credentials.md).
86
+ | Required | Common optional |
87
+ | :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------- |
88
+ | `LIGHTDASH_URL`, `LIGHTDASH_TOOLS_MCP_PUBLIC_URL`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_ID`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET` | port, `ALLOWED_ORIGINS`, audit log, token cache TTL |
38
89
 
39
- ### Streamable HTTP only
90
+ Register Lightdash redirect URI: `{PUBLIC_URL}/oauth/callback`. Clients: URL only to `/semantic-layer/v1/mcp` or `/organization-audit/v1/mcp`.
40
91
 
41
- - `MCP_HTTP_PORT` — Port for the HTTP server (default: `3100`).
42
- - `MCP_AUTH_ENABLED` — Set to `1`, `true`, or `yes` to require auth on the MCP endpoint.
43
- - `MCP_API_KEY` — When auth is enabled, requests must send this value via `Authorization: Bearer <MCP_API_KEY>` or `X-API-Key: <MCP_API_KEY>`.
92
+ ### HTTP shared-key / local (secondary)
93
+
94
+ | Mode | Env |
95
+ | :--------- | :----------------------------------------------------- |
96
+ | Shared-key | `LIGHTDASH_API_KEY` + `LIGHTDASH_TOOLS_MCP_SHARED_KEY` |
97
+ | Local none | `NODE_ENV=development` (not `production`) |
98
+
99
+ Obsolete `LIGHTDASH_TOOLS_MCP_AUTH_MODE`, `EXPERIMENTAL_*`, `DANGEROUSLY_*`, and `INSECURE_DEV` vars are **rejected**. Endpoint path is persona-owned (`LIGHTDASH_TOOLS_MCP_PATH` rejected).
100
+
101
+ See also: [mcp-oauth-http.md](../../docs/mcp-oauth-http.md), [cursor-lightdash-oauth-mcp.md](../../docs/cursor-lightdash-oauth-mcp.md), [cloud-run-mcp-oauth.md](../../docs/cloud-run-mcp-oauth.md), [threat model](../../docs/security/mcp-oauth-threat-model.md).
44
102
 
45
103
  ## Running
46
104
 
@@ -50,53 +108,72 @@ For use with Claude Desktop or IDEs, use `npx`:
50
108
 
51
109
  ```bash
52
110
  npx @lightdash-tools/mcp
53
- ```
54
-
55
- To hide destructive tools from the agent:
56
-
57
- ```bash
58
- npx @lightdash-tools/mcp --safety-mode write-idempotent
111
+ # or explicit personas:
112
+ npx @lightdash-tools/mcp semantic-layer
113
+ npx @lightdash-tools/mcp organization-audit
59
114
  ```
60
115
 
61
116
  Or if installed globally:
62
117
 
63
118
  ```bash
64
119
  lightdash-mcp
120
+ lightdash-mcp organization-audit
65
121
  ```
66
122
 
67
- Logging goes to stderr only; stdout is JSON-RPC.
123
+ Logging goes to stderr only; stdout is JSON-RPC. Bare `lightdash-mcp` defaults to `semantic-layer`.
68
124
 
69
125
  ### Streamable HTTP (remote)
70
126
 
71
127
  ```bash
128
+ # Backward-compatible
72
129
  npx @lightdash-tools/mcp --http
130
+
131
+ # Explicit subcommand
132
+ npx @lightdash-tools/mcp serve-http
133
+
134
+ # Hosted OAuth (server-held Lightdash confidential client)
135
+ export LIGHTDASH_URL="https://app.lightdash.cloud"
136
+ export LIGHTDASH_TOOLS_MCP_PUBLIC_URL="https://lightdash-mcp.example.com"
137
+ export LIGHTDASH_TOOLS_OAUTH_CLIENT_ID="..."
138
+ export LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET="..."
139
+ npx @lightdash-tools/mcp serve-http
73
140
  ```
74
141
 
75
- The server listens on `http://localhost:3100` (or `MCP_HTTP_PORT`). MCP endpoint: `POST/GET/DELETE /mcp`. Sessions are created on first `initialize`; subsequent requests must include the `Mcp-Session-Id` header returned by the server.
142
+ The server listens on `http://localhost:3100` (or `LIGHTDASH_TOOLS_MCP_HTTP_PORT`). Persona MCP endpoints:
76
143
 
77
- With auth disabled (default), any client can call the endpoint. With `MCP_AUTH_ENABLED` set, send `Authorization: Bearer <token>` or `X-API-Key: <key>` matching `MCP_API_KEY`; otherwise the server returns 401.
144
+ - `POST/GET/DELETE /semantic-layer/v1/mcp`
145
+ - `POST/GET/DELETE /organization-audit/v1/mcp`
146
+
147
+ Register `{PUBLIC_URL}/oauth/callback` in Lightdash. See [mcp-oauth-http.md](../../docs/mcp-oauth-http.md).
148
+
149
+ **Local Compose (dev):**
150
+
151
+ - Unauthenticated / PAT smoke: `docker compose -f docker-compose.dev.yml --profile semantic-layer up --build` then Cursor `url: http://localhost:8080/semantic-layer/v1/mcp` (`NODE_ENV=development` + PAT from `.env`).
152
+ - Hosted OAuth smoke: expose `:3100` with Cloudflare Tunnel (`cloudflared tunnel --url http://127.0.0.1:3100`), set `LIGHTDASH_TOOLS_MCP_PUBLIC_URL` in `.env` to the `*.trycloudflare.com` URL, recreate the container, register `{PUBLIC_URL}/oauth/callback` in Lightdash, and point Cursor at `{PUBLIC_URL}/semantic-layer/v1/mcp`. Do not use free ngrok. Details: [cursor-lightdash-oauth-mcp.md](../../docs/cursor-lightdash-oauth-mcp.md).
78
153
 
79
154
  ## Tools
80
155
 
81
- The server registers the following tools (names prefixed with `ldt__`):
82
-
83
- - **Projects**: `list_projects`, `get_project`, `validate_project`, `get_validation_results`
84
- - **Explores**: `list_explores`, `get_explore`
85
- - **Charts**: `list_charts`, `list_charts_as_code`, `upsert_chart_as_code`
86
- - **Dashboards**: `list_dashboards`
87
- - **Spaces**: `list_spaces`, `get_space`
88
- - **Users**: `list_organization_members`, `get_member`, `delete_member`
89
- - **Groups**: `list_groups`, `get_group`
90
- - **Metrics**: `list_metrics`
91
- - **Schedulers**: `list_schedulers`
92
- - **Tags**: `list_tags`
93
- - **Query**: `compile_query`
94
- - **Content**: `search_content` (v2)
95
- - **AI Agents**:
96
- - **Admin**: `list_admin_agents`, `list_admin_agent_threads`, `get_ai_organization_settings`, `update_ai_organization_settings`
97
- - **Agent Management**: `list_project_agents`, `get_project_agent`, `create_project_agent`, `update_project_agent`, `delete_project_agent`
98
- - **Conversations**: `list_agent_threads`, `get_agent_thread`, `generate_agent_message`, `continue_agent_thread`
99
- - **Evaluations**: `list_agent_evaluations`, `get_agent_evaluation`, `create_agent_evaluation`, `update_agent_evaluation`, `append_agent_evaluation_prompts`, `run_agent_evaluation`, `list_agent_evaluation_runs`, `get_agent_evaluation_run_results`, `delete_agent_evaluation`
156
+ ### `semantic-layer` persona
157
+
158
+ Registers these tools (names prefixed with `lightdash_`):
159
+
160
+ - **Projects**: `list_projects`, `get_project`
161
+ - **Explores**: `list_explores`, `get_explore`, `list_dimensions`, `get_field_lineage`
162
+ - **Metrics**: `list_metrics`, `get_metric`
163
+ - **Query**: `compile_query` (empty SELECT → `isError`; no run-query)
164
+
165
+ Prompts and playbook: `lightdash://playbooks/semantic-layer` (cite `lightdash_*` names only).
166
+
167
+ ### `organization-audit` persona
168
+
169
+ Read-only organization inventory, access, content health, usage signals, and schedulers ([ADR-0010](../../docs/adr/0010-mcp-organization-audit-persona-read-only-boundary.md)). MCP server display name is `lightdash-mcp-org-audit` (60-char client limit). Endpoint inventory: [docs/organization-audit-endpoint-inventory.md](../../docs/organization-audit-endpoint-inventory.md).
170
+
171
+ - **Inventory**: `get_org_profile`, `list_org_members`, `get_org_member`, `list_org_groups`, `list_org_projects`
172
+ - **Access**: `list_org_role_assignments`, `list_custom_roles`, `get_custom_role`, `list_project_roles`, `list_project_direct_access`, `list_space_access`, `resolve_effective_access`
173
+ - **Content / health**: `list_content`, `get_dashboard_meta`, `list_validation_results`, `get_project_user_activity`
174
+ - **Delivery**: `list_project_schedulers`, `get_scheduler`
175
+
176
+ Prompts and playbook: `lightdash://playbooks/organization-audit` (host orchestrates multi-step audits via primitives). No mutation, warehouse queries, or user-activity CSV download.
100
177
 
101
178
  ### CLI Binary
102
179
 
@@ -109,32 +186,28 @@ lightdash-mcp --help
109
186
  ### CLI Options
110
187
 
111
188
  - `--http` — Run as HTTP server instead of Stdio.
112
- - `--safety-mode <mode>` — Filter registered tools by safety mode (`read-only`, `write-idempotent`, `write-destructive`). Tools not allowed in this mode will not be registered, hiding them from AI agents (Static Filtering).
113
- - `--projects <uuids>` — Comma-separated list of allowed project UUIDs (overrides `LIGHTDASH_TOOLS_ALLOWED_PROJECTS`; empty = all allowed).
114
- - `--dry-run` — Simulate write operations without executing them (overrides `LIGHTDASH_TOOLS_DRY_RUN`).
115
-
116
- ## Safety Modes
189
+ - `stdio` / `semantic-layer` / `organization-audit` / `serve-http` — Explicit transport/persona subcommands.
117
190
 
118
- The MCP server implements a hierarchical safety model. You can control which tools are available to AI agents using the `LIGHTDASH_TOOLS_SAFETY_MODE` environment variable or the `--safety-mode` CLI option.
191
+ ## Safety (persona-first)
119
192
 
120
- - `read-only` (default): Only allows non-modifying tools (e.g., `list_*`, `get_*`).
121
- - `write-idempotent`: Allows read tools and non-destructive writes (e.g., `upsert_chart_as_code`).
122
- - `write-destructive`: Allows all tools, including destructive ones (e.g., `delete_member`).
193
+ MCP safety is **persona-first** ([ADR-0006](../../docs/adr/0006-mcp-personas-shared-registry-fixed-paths.md), [ADR-0008](../../docs/adr/0008-mcp-request-scope-and-hardening.md)):
123
194
 
124
- ### Enforcement Layers
195
+ | Concern | Mechanism |
196
+ | :----------- | :------------------------------------------------------------------------------------------------- |
197
+ | Which tools | Persona `toolIds` in code (`semantic-layer` or `organization-audit`) |
198
+ | Who | Auth mode + Lightdash API RBAC |
199
+ | Where (HTTP) | Optional `X-Lightdash-Project` pin |
200
+ | Hardening | Input validation on known ID fields + optional `LIGHTDASH_TOOLS_AUDIT_LOG` + org-audit GET asserts |
125
201
 
126
- 1. **Dynamic Enforcement (Visible but Disabled)**: Using `LIGHTDASH_TOOLS_SAFETY_MODE` environment variable. Tools are registered and visible to the agent, but return an error if called. This allows agents to understand that a capability exists but is restricted.
127
- 2. **Static Filtering (Hidden)**: Using the `--safety-mode` CLI option. Tools not allowed in the selected mode are not registered at all. They are completely hidden from the AI agent.
202
+ Process `LIGHTDASH_TOOLS_SAFETY_MODE` / allowlist / dry-run are **CLI-only**, not used by this package.
128
203
 
129
- When a tool is disabled via dynamic enforcement, the server will return a descriptive error message if an agent attempts to call it.
204
+ ### Agent-safe surface
130
205
 
131
- ### Destructive tools
132
-
133
- Tools with `destructiveHint: true` (e.g. `delete_member`) perform irreversible or high-impact actions. MCP clients should show a warning and/or require user confirmation before executing them. AI agents should ask the user for explicit confirmation before calling such tools.
206
+ See [ADR-0004](../../docs/adr/0004-agent-safe-exposure-mcp-cli-vs-client-only.md) and [ADR-0006](../../docs/adr/0006-mcp-personas-shared-registry-fixed-paths.md). Broad admin ops stay on `@lightdash-tools/client` / CLI. The shipped MCP persona is compile/discovery only.
134
207
 
135
208
  ### Input validation
136
209
 
137
- Resource IDs (project UUIDs, slugs) are validated before execution. Invalid inputs (control characters, `?`, `#`, `%`, path traversal) are rejected. This guards against adversarial or hallucinated inputs when used by AI agents. See [docs/agent-context/CONTEXT.md](../../docs/agent-context/CONTEXT.md) for agent-specific guidance.
210
+ Resource IDs (project UUIDs, slugs) are validated before execution. Invalid inputs (control characters, `?`, `#`, `%`, path traversal) are rejected. See [docs/agent-context/CONTEXT.md](../../docs/agent-context/CONTEXT.md).
138
211
 
139
212
  ## Testing
140
213
 
@@ -156,6 +229,8 @@ LIGHTDASH_URL=https://app.lightdash.cloud LIGHTDASH_API_KEY=your_api_key pnpm te
156
229
 
157
230
  The integration tests will automatically detect these environment variables and run additional scenarios, such as verifying authentication and tool execution against the live API.
158
231
 
232
+ For OAuth HTTP mode, set `LIGHTDASH_TOOLS_TEST_OAUTH_ACCESS_TOKEN` (and `LIGHTDASH_URL`) to run the optional live OAuth integration test.
233
+
159
234
  ## License
160
235
 
161
236
  Apache-2.0
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Re-exports the shared audit logger from @lightdash-tools/common.
3
+ * The canonical implementation lives in common so the CLI can also use it.
4
+ */
5
+ export { getSessionId, initAuditLog } from '@lightdash-tools/common';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.logAuditEntry = exports.initAuditLog = exports.getSessionId = void 0;
3
+ exports.initAuditLog = exports.getSessionId = void 0;
4
4
  /**
5
5
  * Re-exports the shared audit logger from @lightdash-tools/common.
6
6
  * The canonical implementation lives in common so the CLI can also use it.
@@ -8,4 +8,3 @@ exports.logAuditEntry = exports.initAuditLog = exports.getSessionId = void 0;
8
8
  var common_1 = require("@lightdash-tools/common");
9
9
  Object.defineProperty(exports, "getSessionId", { enumerable: true, get: function () { return common_1.getSessionId; } });
10
10
  Object.defineProperty(exports, "initAuditLog", { enumerable: true, get: function () { return common_1.initAuditLog; } });
11
- Object.defineProperty(exports, "logAuditEntry", { enumerable: true, get: function () { return common_1.logAuditEntry; } });
@@ -0,0 +1,6 @@
1
+ export type ToolAuditAuthContext = {
2
+ tokenHash?: string;
3
+ subject?: string;
4
+ };
5
+ export declare function runWithToolAuditAuthAsync<T>(auth: ToolAuditAuthContext, fn: () => Promise<T>): Promise<T>;
6
+ export declare function getToolAuditAuth(): ToolAuditAuthContext | undefined;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runWithToolAuditAuthAsync = runWithToolAuditAuthAsync;
4
+ exports.getToolAuditAuth = getToolAuditAuth;
5
+ const node_async_hooks_1 = require("node:async_hooks");
6
+ const storage = new node_async_hooks_1.AsyncLocalStorage();
7
+ async function runWithToolAuditAuthAsync(auth, fn) {
8
+ return storage.run(auth, fn);
9
+ }
10
+ function getToolAuditAuth() {
11
+ return storage.getStore();
12
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const tool_audit_context_js_1 = require("./tool-audit-context.js");
5
+ (0, vitest_1.describe)('tool-audit-context', () => {
6
+ (0, vitest_1.it)('exposes auth fields within the async scope', async () => {
7
+ const seen = [];
8
+ await (0, tool_audit_context_js_1.runWithToolAuditAuthAsync)({ tokenHash: 'hash-abc', subject: 'user-1' }, async () => {
9
+ seen.push((0, tool_audit_context_js_1.getToolAuditAuth)());
10
+ await Promise.resolve();
11
+ seen.push((0, tool_audit_context_js_1.getToolAuditAuth)());
12
+ });
13
+ (0, vitest_1.expect)(seen).toEqual([
14
+ { tokenHash: 'hash-abc', subject: 'user-1' },
15
+ { tokenHash: 'hash-abc', subject: 'user-1' },
16
+ ]);
17
+ (0, vitest_1.expect)((0, tool_audit_context_js_1.getToolAuditAuth)()).toBeUndefined();
18
+ });
19
+ });
@@ -0,0 +1,4 @@
1
+ export type McpAuthMode = 'env' | 'lightdash-oauth' | 'none' | 'shared-key';
2
+ export declare const MCP_AUTH_MODE_NONE: "none";
3
+ export declare const MCP_AUTH_MODE_SHARED_KEY: "shared-key";
4
+ export declare const MCP_AUTH_MODE_LIGHTDASH_OAUTH: "lightdash-oauth";
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MCP_AUTH_MODE_LIGHTDASH_OAUTH = exports.MCP_AUTH_MODE_SHARED_KEY = exports.MCP_AUTH_MODE_NONE = void 0;
4
+ exports.MCP_AUTH_MODE_NONE = 'none';
5
+ exports.MCP_AUTH_MODE_SHARED_KEY = 'shared-key';
6
+ exports.MCP_AUTH_MODE_LIGHTDASH_OAUTH = 'lightdash-oauth';
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ /** Extracts a bearer token from Authorization header (case-insensitive scheme). */
3
+ export declare function extractBearerToken(req: IncomingMessage): string | undefined;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extractBearerToken = extractBearerToken;
4
+ const BEARER_PREFIX = /^bearer\s+/i;
5
+ /** Extracts a bearer token from Authorization header (case-insensitive scheme). */
6
+ function extractBearerToken(req) {
7
+ const authorization = req.headers.authorization;
8
+ if (typeof authorization !== 'string' || !BEARER_PREFIX.test(authorization)) {
9
+ return undefined;
10
+ }
11
+ const token = authorization.replace(BEARER_PREFIX, '').trim();
12
+ return token.length > 0 ? token : undefined;
13
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Upstream Lightdash OAuth contract used by MCP token validation.
3
+ *
4
+ * MCP validates identity by calling `GET /api/v1/user` with the user's OAuth access
5
+ * token as `Authorization: Bearer <token>`. This is not an MCP invention: upstream
6
+ * Lightdash wires that route through `allowApiKeyAuthentication`, which authenticates
7
+ * OAuth bearer tokens before personal access tokens.
8
+ *
9
+ * @see https://github.com/lightdash/lightdash/blob/master/packages/backend/src/controllers/userController.ts
10
+ * @see https://github.com/lightdash/lightdash/blob/master/packages/backend/src/controllers/authentication/middlewares.ts
11
+ */
12
+ export declare const LIGHTDASH_OAUTH_VALIDATION_ENDPOINT: "/api/v1/user";
13
+ export declare const LIGHTDASH_OAUTH_AUTHORIZE_ENDPOINT: "/api/v1/oauth/authorize";
14
+ export declare const LIGHTDASH_OAUTH_TOKEN_ENDPOINT: "/api/v1/oauth/token";
15
+ /** Middleware chain on upstream `GetAuthenticatedUser` (TSOA `UserController`). */
16
+ export declare const LIGHTDASH_GET_AUTHENTICATED_USER_MIDDLEWARE: readonly ["allowApiKeyAuthentication", "isAuthenticated"];
17
+ /**
18
+ * Order enforced by upstream `allowApiKeyAuthentication`:
19
+ * OAuth bearer → service account bearer → personal access token (`ApiKey` header).
20
+ */
21
+ export declare const LIGHTDASH_ALLOW_API_KEY_AUTH_ORDER: readonly ["oauth-bearer", "service-account-bearer", "personal-access-token"];
22
+ export declare const LIGHTDASH_OAUTH_UPSTREAM_REFERENCES: readonly ["lightdash/lightdash packages/backend/src/controllers/userController.ts — GetAuthenticatedUser uses allowApiKeyAuthentication", "lightdash/lightdash packages/backend/src/controllers/authentication/middlewares.ts — allowApiKeyAuthentication tries oauthService.authenticate() first", "lightdash/lightdash packages/backend/src/routers/oauthRouter.ts — /api/v1/oauth/userinfo also uses allowApiKeyAuthentication (alternate OIDC surface, not used by MCP v1 validation)"];
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LIGHTDASH_OAUTH_UPSTREAM_REFERENCES = exports.LIGHTDASH_ALLOW_API_KEY_AUTH_ORDER = exports.LIGHTDASH_GET_AUTHENTICATED_USER_MIDDLEWARE = exports.LIGHTDASH_OAUTH_TOKEN_ENDPOINT = exports.LIGHTDASH_OAUTH_AUTHORIZE_ENDPOINT = exports.LIGHTDASH_OAUTH_VALIDATION_ENDPOINT = void 0;
4
+ /**
5
+ * Upstream Lightdash OAuth contract used by MCP token validation.
6
+ *
7
+ * MCP validates identity by calling `GET /api/v1/user` with the user's OAuth access
8
+ * token as `Authorization: Bearer <token>`. This is not an MCP invention: upstream
9
+ * Lightdash wires that route through `allowApiKeyAuthentication`, which authenticates
10
+ * OAuth bearer tokens before personal access tokens.
11
+ *
12
+ * @see https://github.com/lightdash/lightdash/blob/master/packages/backend/src/controllers/userController.ts
13
+ * @see https://github.com/lightdash/lightdash/blob/master/packages/backend/src/controllers/authentication/middlewares.ts
14
+ */
15
+ exports.LIGHTDASH_OAUTH_VALIDATION_ENDPOINT = '/api/v1/user';
16
+ exports.LIGHTDASH_OAUTH_AUTHORIZE_ENDPOINT = '/api/v1/oauth/authorize';
17
+ exports.LIGHTDASH_OAUTH_TOKEN_ENDPOINT = '/api/v1/oauth/token';
18
+ /** Middleware chain on upstream `GetAuthenticatedUser` (TSOA `UserController`). */
19
+ exports.LIGHTDASH_GET_AUTHENTICATED_USER_MIDDLEWARE = [
20
+ 'allowApiKeyAuthentication',
21
+ 'isAuthenticated',
22
+ ];
23
+ /**
24
+ * Order enforced by upstream `allowApiKeyAuthentication`:
25
+ * OAuth bearer → service account bearer → personal access token (`ApiKey` header).
26
+ */
27
+ exports.LIGHTDASH_ALLOW_API_KEY_AUTH_ORDER = [
28
+ 'oauth-bearer',
29
+ 'service-account-bearer',
30
+ 'personal-access-token',
31
+ ];
32
+ exports.LIGHTDASH_OAUTH_UPSTREAM_REFERENCES = [
33
+ 'lightdash/lightdash packages/backend/src/controllers/userController.ts — GetAuthenticatedUser uses allowApiKeyAuthentication',
34
+ 'lightdash/lightdash packages/backend/src/controllers/authentication/middlewares.ts — allowApiKeyAuthentication tries oauthService.authenticate() first',
35
+ 'lightdash/lightdash packages/backend/src/routers/oauthRouter.ts — /api/v1/oauth/userinfo also uses allowApiKeyAuthentication (alternate OIDC surface, not used by MCP v1 validation)',
36
+ ];
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const lightdash_oauth_upstream_contract_js_1 = require("./lightdash-oauth-upstream-contract.js");
5
+ (0, vitest_1.describe)('Lightdash OAuth upstream contract', () => {
6
+ (0, vitest_1.it)('documents GET /api/v1/user as the validation endpoint with allowApiKeyAuthentication', () => {
7
+ (0, vitest_1.expect)(lightdash_oauth_upstream_contract_js_1.LIGHTDASH_OAUTH_VALIDATION_ENDPOINT).toBe('/api/v1/user');
8
+ (0, vitest_1.expect)(lightdash_oauth_upstream_contract_js_1.LIGHTDASH_GET_AUTHENTICATED_USER_MIDDLEWARE).toEqual([
9
+ 'allowApiKeyAuthentication',
10
+ 'isAuthenticated',
11
+ ]);
12
+ (0, vitest_1.expect)(lightdash_oauth_upstream_contract_js_1.LIGHTDASH_ALLOW_API_KEY_AUTH_ORDER[0]).toBe('oauth-bearer');
13
+ (0, vitest_1.expect)(lightdash_oauth_upstream_contract_js_1.LIGHTDASH_OAUTH_UPSTREAM_REFERENCES.length).toBeGreaterThanOrEqual(2);
14
+ (0, vitest_1.expect)(lightdash_oauth_upstream_contract_js_1.LIGHTDASH_OAUTH_UPSTREAM_REFERENCES.join(' ')).toContain('userController.ts');
15
+ (0, vitest_1.expect)(lightdash_oauth_upstream_contract_js_1.LIGHTDASH_OAUTH_UPSTREAM_REFERENCES.join(' ')).toContain('middlewares.ts');
16
+ });
17
+ (0, vitest_1.it)('expects AuthenticatedUser to expose optional organizationUuid for session binding', () => {
18
+ const user = {
19
+ userUuid: 'user-uuid',
20
+ firstName: 'Test',
21
+ lastName: 'User',
22
+ userId: 1,
23
+ isTrackingAnonymized: false,
24
+ isMarketingOptedIn: false,
25
+ isSetupComplete: true,
26
+ isActive: true,
27
+ createdAt: '2026-01-01T00:00:00.000Z',
28
+ updatedAt: '2026-01-01T00:00:00.000Z',
29
+ timezone: null,
30
+ organizationUuid: 'org-uuid',
31
+ impersonation: null,
32
+ avatarUrl: null,
33
+ avatarGradient: null,
34
+ };
35
+ (0, vitest_1.expect)(user.organizationUuid).toBe('org-uuid');
36
+ });
37
+ (0, vitest_1.it)('allows AuthenticatedUser without organizationUuid (org binding falls back to subject only)', () => {
38
+ const user = {
39
+ userUuid: 'user-uuid',
40
+ firstName: 'Test',
41
+ lastName: 'User',
42
+ userId: 1,
43
+ isTrackingAnonymized: false,
44
+ isMarketingOptedIn: false,
45
+ isSetupComplete: true,
46
+ isActive: true,
47
+ createdAt: '2026-01-01T00:00:00.000Z',
48
+ updatedAt: '2026-01-01T00:00:00.000Z',
49
+ timezone: null,
50
+ impersonation: null,
51
+ avatarUrl: null,
52
+ avatarGradient: null,
53
+ };
54
+ (0, vitest_1.expect)(user.organizationUuid).toBeUndefined();
55
+ });
56
+ });
@@ -0,0 +1,14 @@
1
+ import { type McpHttpConfig } from '../../config/load-mcp-config.js';
2
+ export interface AuthorizationServerMetadata {
3
+ issuer: string;
4
+ authorization_endpoint: string;
5
+ token_endpoint: string;
6
+ registration_endpoint: string;
7
+ response_types_supported: string[];
8
+ grant_types_supported: string[];
9
+ code_challenge_methods_supported: string[];
10
+ token_endpoint_auth_methods_supported: string[];
11
+ scopes_supported: string[];
12
+ }
13
+ /** RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL). */
14
+ export declare function buildBrokerAuthorizationServerMetadata(config: McpHttpConfig): AuthorizationServerMetadata;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildBrokerAuthorizationServerMetadata = buildBrokerAuthorizationServerMetadata;
4
+ const env_js_1 = require("../../config/env.js");
5
+ const public_url_js_1 = require("../../config/public-url.js");
6
+ /** RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL). */
7
+ function buildBrokerAuthorizationServerMetadata(config) {
8
+ const issuer = (0, public_url_js_1.requirePublicUrl)(config, 'authorization server metadata');
9
+ return {
10
+ issuer,
11
+ authorization_endpoint: `${issuer}${env_js_1.OAUTH_AUTHORIZE_PATH}`,
12
+ token_endpoint: `${issuer}${env_js_1.OAUTH_TOKEN_PATH}`,
13
+ registration_endpoint: `${issuer}${env_js_1.OAUTH_REGISTER_PATH}`,
14
+ response_types_supported: ['code'],
15
+ grant_types_supported: ['authorization_code'],
16
+ code_challenge_methods_supported: ['S256'],
17
+ token_endpoint_auth_methods_supported: ['none'],
18
+ scopes_supported: config.scopesSupported,
19
+ };
20
+ }
@@ -0,0 +1,20 @@
1
+ import { type McpHttpConfig } from '../../config/load-mcp-config.js';
2
+ export interface LightdashTokenResponse {
3
+ access_token: string;
4
+ token_type?: string;
5
+ expires_in?: number;
6
+ refresh_token?: string;
7
+ scope?: string;
8
+ }
9
+ /** Exchanges an authorization code at Lightdash using the server-held confidential client. */
10
+ export declare function exchangeLightdashAuthorizationCode(config: McpHttpConfig, code: string): Promise<LightdashTokenResponse>;
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).
15
+ */
16
+ export declare function buildLightdashAuthorizeUrl(config: McpHttpConfig, params: {
17
+ state: string;
18
+ scope?: string;
19
+ resource?: string;
20
+ }): string;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exchangeLightdashAuthorizationCode = exchangeLightdashAuthorizationCode;
4
+ exports.buildLightdashAuthorizeUrl = buildLightdashAuthorizeUrl;
5
+ const load_mcp_config_js_1 = require("../../config/load-mcp-config.js");
6
+ const lightdash_oauth_upstream_contract_js_1 = require("../lightdash-oauth-upstream-contract.js");
7
+ function parseLightdashTokenResponse(body) {
8
+ if (typeof body !== 'object' ||
9
+ body === null ||
10
+ typeof body.access_token !== 'string' ||
11
+ body.access_token.length === 0) {
12
+ throw new Error('Lightdash token response missing access_token');
13
+ }
14
+ const record = body;
15
+ return {
16
+ access_token: record.access_token,
17
+ token_type: typeof record.token_type === 'string' ? record.token_type : undefined,
18
+ expires_in: typeof record.expires_in === 'number' ? record.expires_in : undefined,
19
+ refresh_token: typeof record.refresh_token === 'string' ? record.refresh_token : undefined,
20
+ scope: typeof record.scope === 'string' ? record.scope : undefined,
21
+ };
22
+ }
23
+ /** Exchanges an authorization code at Lightdash using the server-held confidential client. */
24
+ async function exchangeLightdashAuthorizationCode(config, code) {
25
+ if (!config.oauthClientId || !config.oauthClientSecret) {
26
+ throw new Error('OAuth client credentials are required for token exchange');
27
+ }
28
+ const tokenUrl = `${config.lightdashUrl}${lightdash_oauth_upstream_contract_js_1.LIGHTDASH_OAUTH_TOKEN_ENDPOINT}`;
29
+ const body = new URLSearchParams({
30
+ grant_type: 'authorization_code',
31
+ code,
32
+ redirect_uri: (0, load_mcp_config_js_1.getOAuthCallbackUrl)(config),
33
+ client_id: config.oauthClientId,
34
+ client_secret: config.oauthClientSecret.expose(),
35
+ });
36
+ const headers = {
37
+ 'Content-Type': 'application/x-www-form-urlencoded',
38
+ Accept: 'application/json',
39
+ };
40
+ if (config.proxyAuthorization) {
41
+ headers['Proxy-Authorization'] = config.proxyAuthorization.expose();
42
+ }
43
+ const response = await fetch(tokenUrl, {
44
+ method: 'POST',
45
+ headers,
46
+ body,
47
+ });
48
+ if (!response.ok) {
49
+ const text = await response.text().catch(() => '');
50
+ throw new Error(`Lightdash token exchange failed (${response.status}): ${text.slice(0, 200)}`);
51
+ }
52
+ return parseLightdashTokenResponse(await response.json());
53
+ }
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).
58
+ */
59
+ function buildLightdashAuthorizeUrl(config, params) {
60
+ if (!config.oauthClientId) {
61
+ throw new Error('OAuth client id is required');
62
+ }
63
+ const url = new URL(`${config.lightdashUrl}${lightdash_oauth_upstream_contract_js_1.LIGHTDASH_OAUTH_AUTHORIZE_ENDPOINT}`);
64
+ url.searchParams.set('response_type', 'code');
65
+ url.searchParams.set('client_id', config.oauthClientId);
66
+ url.searchParams.set('redirect_uri', (0, load_mcp_config_js_1.getOAuthCallbackUrl)(config));
67
+ 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
+ return url.toString();
76
+ }