@lightdash-tools/mcp 0.14.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +43 -14
  2. package/dist/auth/oauth-broker/as-metadata.d.ts +6 -2
  3. package/dist/auth/oauth-broker/as-metadata.js +8 -4
  4. package/dist/auth/oauth-broker/invoke-origins.d.ts +16 -0
  5. package/dist/auth/oauth-broker/invoke-origins.js +112 -0
  6. package/dist/auth/oauth-broker/invoke-origins.test.d.ts +1 -0
  7. package/dist/auth/oauth-broker/invoke-origins.test.js +82 -0
  8. package/dist/auth/oauth-broker/lightdash-token.d.ts +6 -5
  9. package/dist/auth/oauth-broker/lightdash-token.js +6 -10
  10. package/dist/auth/oauth-broker/mcp-access-token.d.ts +31 -0
  11. package/dist/auth/oauth-broker/mcp-access-token.js +109 -0
  12. package/dist/auth/oauth-broker/mcp-access-token.test.d.ts +1 -0
  13. package/dist/auth/oauth-broker/mcp-access-token.test.js +61 -0
  14. package/dist/auth/oauth-broker/pending-store.d.ts +9 -3
  15. package/dist/auth/oauth-broker/pending-store.js +5 -3
  16. package/dist/auth/oauth-broker/pending-store.test.js +28 -44
  17. package/dist/auth/oauth-broker/routes.d.ts +2 -1
  18. package/dist/auth/oauth-broker/routes.js +124 -48
  19. package/dist/auth/oauth-broker/routes.test.js +191 -16
  20. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +3 -1
  21. package/dist/auth/resource-server/lightdash-oauth-middleware.js +65 -41
  22. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +95 -59
  23. package/dist/auth/resource-server/oauth-protected-resource.d.ts +2 -2
  24. package/dist/auth/resource-server/oauth-protected-resource.js +8 -11
  25. package/dist/auth/resource-server/www-authenticate.test.js +3 -3
  26. package/dist/bin.js +33 -7
  27. package/dist/config/env.d.ts +10 -0
  28. package/dist/config/env.js +11 -1
  29. package/dist/config/load-mcp-config.d.ts +14 -1
  30. package/dist/config/load-mcp-config.js +35 -8
  31. package/dist/config/load-mcp-config.test.js +49 -0
  32. package/dist/config/prompt-context-policy.d.ts +18 -0
  33. package/dist/config/prompt-context-policy.js +40 -0
  34. package/dist/config/prompt-context-policy.test.d.ts +4 -0
  35. package/dist/config/prompt-context-policy.test.js +35 -0
  36. package/dist/config/test-mcp-http-config.js +1 -1
  37. package/dist/governance/mcp-post-factory-context.d.ts +2 -0
  38. package/dist/http.d.ts +7 -1
  39. package/dist/http.integration.helpers.d.ts +50 -0
  40. package/dist/http.integration.helpers.js +190 -0
  41. package/dist/http.integration.test.js +81 -187
  42. package/dist/http.invoke-origin.integration.test.d.ts +1 -0
  43. package/dist/http.invoke-origin.integration.test.js +108 -0
  44. package/dist/http.js +10 -1
  45. package/dist/index.d.ts +6 -1
  46. package/dist/index.js +6 -3
  47. package/dist/policy/content-developer.d.ts +5 -0
  48. package/dist/policy/content-developer.js +25 -1
  49. package/dist/policy/content-developer.test.js +29 -0
  50. package/dist/profiles/ai-agent-ops/v1/invariants.d.ts +27 -0
  51. package/dist/profiles/ai-agent-ops/v1/invariants.js +39 -0
  52. package/dist/profiles/ai-agent-ops/v1/prompts.d.ts +3 -2
  53. package/dist/profiles/ai-agent-ops/v1/prompts.js +67 -41
  54. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.d.ts +2 -1
  55. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.js +10 -3
  56. package/dist/profiles/content-developer/v1/invariants.d.ts +69 -0
  57. package/dist/profiles/content-developer/v1/invariants.js +95 -0
  58. package/dist/profiles/content-developer/v1/prompt-specs.d.ts +32 -0
  59. package/dist/profiles/content-developer/v1/prompt-specs.js +56 -0
  60. package/dist/profiles/content-developer/v1/prompts.d.ts +4 -3
  61. package/dist/profiles/content-developer/v1/prompts.js +65 -71
  62. package/dist/profiles/content-developer/v1/prompts.test.js +61 -7
  63. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +1 -0
  64. package/dist/profiles/content-developer/v1/resources/playbooks/index.md +11 -8
  65. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/dashboard-diff.md +15 -0
  66. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-required.md +14 -0
  67. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-stale.md +21 -0
  68. package/dist/profiles/content-developer/v1/resources/playbooks.d.ts +3 -2
  69. package/dist/profiles/content-developer/v1/resources/playbooks.js +35 -22
  70. package/dist/profiles/content-governance/v1/invariants.d.ts +27 -0
  71. package/dist/profiles/content-governance/v1/invariants.js +39 -0
  72. package/dist/profiles/content-governance/v1/prompts.d.ts +4 -2
  73. package/dist/profiles/content-governance/v1/prompts.js +31 -19
  74. package/dist/profiles/content-governance/v1/resources/playbooks.d.ts +2 -1
  75. package/dist/profiles/content-governance/v1/resources/playbooks.js +8 -9
  76. package/dist/profiles/content-reader/v1/invariants.d.ts +33 -0
  77. package/dist/profiles/content-reader/v1/invariants.js +47 -0
  78. package/dist/profiles/content-reader/v1/prompt-specs.d.ts +18 -0
  79. package/dist/profiles/content-reader/v1/prompt-specs.js +33 -0
  80. package/dist/profiles/content-reader/v1/prompts.d.ts +3 -2
  81. package/dist/profiles/content-reader/v1/prompts.js +69 -76
  82. package/dist/profiles/content-reader/v1/resources/playbooks.d.ts +2 -1
  83. package/dist/profiles/content-reader/v1/resources/playbooks.js +10 -11
  84. package/dist/profiles/data-analyst/v1/invariants.d.ts +21 -0
  85. package/dist/profiles/data-analyst/v1/invariants.js +31 -0
  86. package/dist/profiles/data-analyst/v1/prompts.d.ts +3 -2
  87. package/dist/profiles/data-analyst/v1/prompts.js +17 -9
  88. package/dist/profiles/data-analyst/v1/resources/playbooks.d.ts +2 -1
  89. package/dist/profiles/data-analyst/v1/resources/playbooks.js +6 -7
  90. package/dist/profiles/lib/playbook-resources.d.ts +16 -34
  91. package/dist/profiles/lib/playbook-resources.js +55 -76
  92. package/dist/profiles/lib/prompt-context.d.ts +71 -0
  93. package/dist/profiles/lib/prompt-context.js +205 -0
  94. package/dist/profiles/lib/prompt-context.test.d.ts +4 -0
  95. package/dist/profiles/lib/prompt-context.test.js +154 -0
  96. package/dist/profiles/lib/prompt-invariants.d.ts +20 -0
  97. package/dist/profiles/lib/prompt-invariants.js +54 -0
  98. package/dist/profiles/organization-audit/v1/invariants.d.ts +24 -0
  99. package/dist/profiles/organization-audit/v1/invariants.js +35 -0
  100. package/dist/profiles/organization-audit/v1/prompts.d.ts +3 -2
  101. package/dist/profiles/organization-audit/v1/prompts.js +44 -28
  102. package/dist/profiles/organization-audit/v1/resources/playbooks.d.ts +2 -1
  103. package/dist/profiles/organization-audit/v1/resources/playbooks.js +10 -3
  104. package/dist/profiles/semantic-layer/v1/invariants.d.ts +27 -0
  105. package/dist/profiles/semantic-layer/v1/invariants.js +39 -0
  106. package/dist/profiles/semantic-layer/v1/prompts.d.ts +3 -2
  107. package/dist/profiles/semantic-layer/v1/prompts.js +37 -26
  108. package/dist/profiles/semantic-layer/v1/resources/playbooks.d.ts +2 -4
  109. package/dist/profiles/semantic-layer/v1/resources/playbooks.js +8 -7
  110. package/dist/profiles/test-support/prompt-context-budget.test.d.ts +5 -0
  111. package/dist/profiles/test-support/prompt-context-budget.test.js +72 -0
  112. package/dist/profiles/types.d.ts +6 -1
  113. package/dist/server/capabilities.d.ts +3 -0
  114. package/dist/server/capabilities.js +4 -2
  115. package/dist/tools/lib/schema-fields.d.ts +4 -0
  116. package/dist/tools/lib/schema-fields.js +8 -1
  117. package/dist/tools/project/developer-content-preview.js +1 -1
  118. package/dist/tools/project/developer-content.js +2 -2
  119. package/dist/tools/query/reader-tool-helpers.d.ts +2 -2
  120. package/dist/tools/query/reader-tool-helpers.js +2 -2
  121. package/dist/tools/query/reader-tool-helpers.test.js +1 -0
  122. package/dist/tools/shared.d.ts +6 -1
  123. package/dist/tools/shared.js +12 -2
  124. package/dist/transports/streamable-http.js +13 -4
  125. package/dist/transports/streamable-http.test.js +8 -3
  126. package/package.json +3 -3
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
 
@@ -87,14 +96,24 @@ 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), [`LIGHTDASH_TOOLS_MCP_PROFILES`](#profile-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_MCP_INVOKE_ORIGINS`](#extra-invoke-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
 
96
105
  Register Lightdash redirect URI: `{PUBLIC_URL}/oauth/callback`. Clients connect with URL only to a profile path above. Protocol: [MCP Authorization 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization).
97
106
 
107
+ ### Extra invoke origins
108
+
109
+ Optional private-network hostnames (internal LB, internal DNS) that should advertise their own PRM and token/DCR while Google authorize/callback stay on `PUBLIC_URL`. See [mcp-oauth.md](../../docs/operators/mcp-oauth.md#extra-invoke-origins-private-load-balancer--internal-dns) and [ADR-0027](../../docs/adr/0027-mcp-oauth-extra-invoke-origins.md).
110
+
111
+ ```bash
112
+ export LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS="http://mcp.ilb.internal"
113
+ ```
114
+
115
+ On those Hosts, leave the client Resource URL empty. Do not point `@modelcontextprotocol/client` v2 at an HTTP extra origin — use public HTTPS.
116
+
98
117
  ### Content-developer / content-governance signing
99
118
 
100
119
  | Required (non-test) | Notes |
@@ -127,6 +146,25 @@ export LIGHTDASH_TOOLS_MCP_PROFILES="content-reader,content-developer"
127
146
 
128
147
  Architecture: [ADR-0024](../../docs/adr/0024-mcp-http-profile-mount-allowlist-via-env.md).
129
148
 
149
+ ### Prompt context policy
150
+
151
+ Controls how much playbook markdown is embedded into `prompts/get` (progressive disclosure; [ADR-0025](../../docs/adr/0025-mcp-progressive-disclosure-prompt-context-policies.md)).
152
+
153
+ | Value | Behavior |
154
+ | :------------------ | :-------------------------------------------------- |
155
+ | `compact` (default) | Task + critical invariants + resource manifest only |
156
+ | `compatible` | Also embeds required topic playbooks |
157
+ | `embedded` | Legacy: embeds core + required topics (rollback) |
158
+
159
+ ```bash
160
+ export LIGHTDASH_TOOLS_MCP_PROMPT_CONTEXT=compatible
161
+ # or
162
+ lightdash-mcp stdio --profile content-reader --prompt-context embedded
163
+ lightdash-mcp http --prompt-context compact
164
+ ```
165
+
166
+ Invalid values fail at startup. Do not infer policy from MCP client names.
167
+
130
168
  ### Project allowlist
131
169
 
132
170
  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 +253,11 @@ When a tool handler throws (for example a Lightdash HTTP/API failure), MCP retur
215
253
 
216
254
  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
255
 
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
256
  ## Further reading
229
257
 
230
258
  - Architecture / contributing — [CONTRIBUTING.md](./CONTRIBUTING.md)
231
259
  - OAuth operator guide — [docs/operators/mcp-oauth.md](../../docs/operators/mcp-oauth.md)
260
+ - Cloud Run — [docs/operators/cloud-run.md](../../docs/operators/cloud-run.md)
232
261
  - Cursor hosted OAuth — [docs/operators/cursor-claude.md](../../docs/operators/cursor-claude.md)
233
262
  - Architecture decisions — [docs/adr/](../../docs/adr/)
234
263
  - MCP transports — [2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports)
@@ -10,5 +10,9 @@ export interface AuthorizationServerMetadata {
10
10
  token_endpoint_auth_methods_supported: string[];
11
11
  scopes_supported: string[];
12
12
  }
13
- /** RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL). */
14
- export declare function buildBrokerAuthorizationServerMetadata(config: McpHttpConfig): AuthorizationServerMetadata;
13
+ /**
14
+ * RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL).
15
+ * On an extra invoke origin, token/DCR URLs move to that origin; issuer and
16
+ * authorize stay on PUBLIC_URL (intentional RFC 8414 split).
17
+ */
18
+ export declare function buildBrokerAuthorizationServerMetadata(config: McpHttpConfig, tokenOrigin: string): AuthorizationServerMetadata;
@@ -3,14 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildBrokerAuthorizationServerMetadata = buildBrokerAuthorizationServerMetadata;
4
4
  const env_js_1 = require("../../config/env.js");
5
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) {
6
+ /**
7
+ * RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL).
8
+ * On an extra invoke origin, token/DCR URLs move to that origin; issuer and
9
+ * authorize stay on PUBLIC_URL (intentional RFC 8414 split).
10
+ */
11
+ function buildBrokerAuthorizationServerMetadata(config, tokenOrigin) {
8
12
  const issuer = (0, public_url_js_1.requirePublicUrl)(config, 'authorization server metadata');
9
13
  return {
10
14
  issuer,
11
15
  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}`,
16
+ token_endpoint: `${tokenOrigin}${env_js_1.OAUTH_TOKEN_PATH}`,
17
+ registration_endpoint: `${tokenOrigin}${env_js_1.OAUTH_REGISTER_PATH}`,
14
18
  response_types_supported: ['code'],
15
19
  grant_types_supported: ['authorization_code'],
16
20
  code_challenge_methods_supported: ['S256'],
@@ -0,0 +1,16 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ /**
3
+ * Request scheme for origin matching. `X-Forwarded-Proto` wins (first value),
4
+ * then TLS socket, otherwise http. Non-https is treated as http.
5
+ */
6
+ export declare function requestProtocol(req: IncomingMessage): 'http' | 'https';
7
+ export declare function originFromHostHeader(hostHeader: string | undefined, protocol: string): URL | undefined;
8
+ /**
9
+ * Extra MCP invoke origins (private load balancer, internal DNS, etc.).
10
+ * Duplicates of `publicUrl` are skipped.
11
+ */
12
+ export declare function parseInvokeOrigins(raw: string | undefined, publicUrl?: string): URL[];
13
+ export declare function matchInvokeOrigin(hostHeader: string | undefined, protocol: string, invokeOrigins: readonly URL[]): URL | undefined;
14
+ export declare function allowedResourceOrigins(publicUrl: string, invokeOrigins: readonly URL[]): string[];
15
+ /** Public URL, or a matching extra invoke origin, with no trailing slash. */
16
+ export declare function resourceOriginForRequest(req: IncomingMessage, invokeOrigins: readonly URL[], publicUrl: string): string;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requestProtocol = requestProtocol;
4
+ exports.originFromHostHeader = originFromHostHeader;
5
+ exports.parseInvokeOrigins = parseInvokeOrigins;
6
+ exports.matchInvokeOrigin = matchInvokeOrigin;
7
+ exports.allowedResourceOrigins = allowedResourceOrigins;
8
+ exports.resourceOriginForRequest = resourceOriginForRequest;
9
+ const env_js_1 = require("../../config/env.js");
10
+ const INVOKE_ORIGIN_ABSOLUTE_ERROR = `${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS} entries must be absolute http(s) origins`;
11
+ function parseOneInvokeOrigin(raw) {
12
+ let parsed;
13
+ try {
14
+ parsed = new URL(raw);
15
+ }
16
+ catch (_a) {
17
+ throw new Error(`${INVOKE_ORIGIN_ABSOLUTE_ERROR} (got ${raw})`);
18
+ }
19
+ if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') ||
20
+ parsed.username !== '' ||
21
+ parsed.password !== '') {
22
+ throw new Error(`${INVOKE_ORIGIN_ABSOLUTE_ERROR} (got ${raw})`);
23
+ }
24
+ if (parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '') {
25
+ throw new Error(`${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS} entries must be origins without a path, query, or fragment (got ${raw})`);
26
+ }
27
+ return new URL(parsed.origin);
28
+ }
29
+ function firstForwardedProto(req) {
30
+ var _a;
31
+ const raw = req.headers['x-forwarded-proto'];
32
+ const value = Array.isArray(raw) ? raw[0] : raw;
33
+ if (value === undefined || value.length === 0) {
34
+ return undefined;
35
+ }
36
+ return (_a = value.split(',')[0]) === null || _a === void 0 ? void 0 : _a.trim().toLowerCase();
37
+ }
38
+ /**
39
+ * Request scheme for origin matching. `X-Forwarded-Proto` wins (first value),
40
+ * then TLS socket, otherwise http. Non-https is treated as http.
41
+ */
42
+ function requestProtocol(req) {
43
+ const forwarded = firstForwardedProto(req);
44
+ if (forwarded === 'https') {
45
+ return 'https';
46
+ }
47
+ if (forwarded === 'http') {
48
+ return 'http';
49
+ }
50
+ return 'encrypted' in req.socket && req.socket.encrypted === true ? 'https' : 'http';
51
+ }
52
+ function originFromHostHeader(hostHeader, protocol) {
53
+ if (hostHeader === undefined || hostHeader.length === 0) {
54
+ return undefined;
55
+ }
56
+ try {
57
+ return new URL(`${protocol === 'https' ? 'https' : 'http'}://${hostHeader}`);
58
+ }
59
+ catch (_a) {
60
+ return undefined;
61
+ }
62
+ }
63
+ /**
64
+ * Extra MCP invoke origins (private load balancer, internal DNS, etc.).
65
+ * Duplicates of `publicUrl` are skipped.
66
+ */
67
+ function parseInvokeOrigins(raw, publicUrl) {
68
+ if (raw === undefined || raw.trim() === '') {
69
+ return [];
70
+ }
71
+ const seen = new Set();
72
+ if (publicUrl !== undefined && publicUrl.length > 0) {
73
+ seen.add(new URL(publicUrl).origin);
74
+ }
75
+ const parsed = [];
76
+ for (const part of raw
77
+ .split(',')
78
+ .map((entry) => entry.trim())
79
+ .filter(Boolean)) {
80
+ const origin = parseOneInvokeOrigin(part);
81
+ if (seen.has(origin.origin)) {
82
+ continue;
83
+ }
84
+ seen.add(origin.origin);
85
+ parsed.push(origin);
86
+ }
87
+ return parsed;
88
+ }
89
+ function matchInvokeOrigin(hostHeader, protocol, invokeOrigins) {
90
+ if (invokeOrigins.length === 0) {
91
+ return undefined;
92
+ }
93
+ const fromHost = originFromHostHeader(hostHeader, protocol);
94
+ if (fromHost === undefined) {
95
+ return undefined;
96
+ }
97
+ return invokeOrigins.find((origin) => origin.origin === fromHost.origin);
98
+ }
99
+ function matchInvokeOriginFromRequest(req, invokeOrigins) {
100
+ return matchInvokeOrigin(req.headers.host, requestProtocol(req), invokeOrigins);
101
+ }
102
+ function allowedResourceOrigins(publicUrl, invokeOrigins) {
103
+ return [new URL(publicUrl).origin, ...invokeOrigins.map((origin) => origin.origin)];
104
+ }
105
+ /** Public URL, or a matching extra invoke origin, with no trailing slash. */
106
+ function resourceOriginForRequest(req, invokeOrigins, publicUrl) {
107
+ const invoke = matchInvokeOriginFromRequest(req, invokeOrigins);
108
+ if (invoke !== undefined) {
109
+ return invoke.origin;
110
+ }
111
+ return new URL(publicUrl).origin;
112
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const invoke_origins_js_1 = require("./invoke-origins.js");
5
+ const ILB = 'http://mcp.ilb.internal';
6
+ (0, vitest_1.describe)('parseInvokeOrigins', () => {
7
+ (0, vitest_1.it)('returns empty when unset or blank', () => {
8
+ (0, vitest_1.expect)((0, invoke_origins_js_1.parseInvokeOrigins)(undefined, 'https://mcp.example.com')).toEqual([]);
9
+ (0, vitest_1.expect)((0, invoke_origins_js_1.parseInvokeOrigins)(' ', 'https://mcp.example.com')).toEqual([]);
10
+ });
11
+ (0, vitest_1.it)('parses comma-separated http(s) origins and skips the public URL', () => {
12
+ const parsed = (0, invoke_origins_js_1.parseInvokeOrigins)(` ${ILB}, https://mcp.example.com, http://other.internal:8080 `, 'https://mcp.example.com');
13
+ (0, vitest_1.expect)(parsed.map((origin) => origin.origin)).toEqual([
14
+ 'http://mcp.ilb.internal',
15
+ 'http://other.internal:8080',
16
+ ]);
17
+ });
18
+ (0, vitest_1.it)('strips default ports so http://host:80 matches http://host', () => {
19
+ const parsed = (0, invoke_origins_js_1.parseInvokeOrigins)('http://mcp.ilb.internal:80', 'https://mcp.example.com');
20
+ (0, vitest_1.expect)(parsed).toHaveLength(1);
21
+ (0, vitest_1.expect)(parsed[0].origin).toBe(ILB);
22
+ });
23
+ (0, vitest_1.it)('rejects a path, query, fragment, or non-http scheme', () => {
24
+ (0, vitest_1.expect)(() => (0, invoke_origins_js_1.parseInvokeOrigins)('http://mcp.ilb.internal/v1', 'https://mcp.example.com')).toThrow(/without a path/);
25
+ (0, vitest_1.expect)(() => (0, invoke_origins_js_1.parseInvokeOrigins)('not-a-url', 'https://mcp.example.com')).toThrow(/absolute http\(s\) origins/);
26
+ (0, vitest_1.expect)(() => (0, invoke_origins_js_1.parseInvokeOrigins)('ftp://mcp.ilb.internal', 'https://mcp.example.com')).toThrow(/absolute http\(s\) origins/);
27
+ });
28
+ });
29
+ (0, vitest_1.describe)('originFromHostHeader / matchInvokeOrigin', () => {
30
+ const invokeOrigins = (0, invoke_origins_js_1.parseInvokeOrigins)(ILB, 'https://mcp.example.com');
31
+ (0, vitest_1.it)('matches Host + http scheme to the listed origin', () => {
32
+ var _a;
33
+ (0, vitest_1.expect)((_a = (0, invoke_origins_js_1.matchInvokeOrigin)('mcp.ilb.internal', 'http', invokeOrigins)) === null || _a === void 0 ? void 0 : _a.origin).toBe(ILB);
34
+ });
35
+ (0, vitest_1.it)('does not match the same hostname on a different port', () => {
36
+ (0, vitest_1.expect)((0, invoke_origins_js_1.matchInvokeOrigin)('mcp.ilb.internal:9999', 'http', invokeOrigins)).toBeUndefined();
37
+ });
38
+ (0, vitest_1.it)('does not match https when the listed origin is http', () => {
39
+ (0, vitest_1.expect)((0, invoke_origins_js_1.matchInvokeOrigin)('mcp.ilb.internal', 'https', invokeOrigins)).toBeUndefined();
40
+ });
41
+ (0, vitest_1.it)('does not match the public hostname', () => {
42
+ (0, vitest_1.expect)((0, invoke_origins_js_1.matchInvokeOrigin)('mcp.example.com', 'https', invokeOrigins)).toBeUndefined();
43
+ });
44
+ (0, vitest_1.it)('does not parse Host when the extra-origin list is empty', () => {
45
+ (0, vitest_1.expect)((0, invoke_origins_js_1.matchInvokeOrigin)('mcp.ilb.internal', 'http', [])).toBeUndefined();
46
+ });
47
+ (0, vitest_1.it)('treats non-https protocol as http', () => {
48
+ var _a, _b;
49
+ (0, vitest_1.expect)((_a = (0, invoke_origins_js_1.originFromHostHeader)('mcp.ilb.internal', 'http')) === null || _a === void 0 ? void 0 : _a.origin).toBe(ILB);
50
+ (0, vitest_1.expect)((_b = (0, invoke_origins_js_1.originFromHostHeader)('mcp.ilb.internal', 'bogus')) === null || _b === void 0 ? void 0 : _b.origin).toBe(ILB);
51
+ });
52
+ });
53
+ (0, vitest_1.describe)('requestProtocol', () => {
54
+ (0, vitest_1.it)('prefers the first X-Forwarded-Proto value', () => {
55
+ (0, vitest_1.expect)((0, invoke_origins_js_1.requestProtocol)({
56
+ headers: { 'x-forwarded-proto': 'https, http' },
57
+ socket: {},
58
+ })).toBe('https');
59
+ (0, vitest_1.expect)((0, invoke_origins_js_1.requestProtocol)({
60
+ headers: { 'x-forwarded-proto': 'http' },
61
+ socket: { encrypted: true },
62
+ })).toBe('http');
63
+ });
64
+ (0, vitest_1.it)('falls back to TLS then http', () => {
65
+ (0, vitest_1.expect)((0, invoke_origins_js_1.requestProtocol)({
66
+ headers: {},
67
+ socket: { encrypted: true },
68
+ })).toBe('https');
69
+ (0, vitest_1.expect)((0, invoke_origins_js_1.requestProtocol)({
70
+ headers: {},
71
+ socket: {},
72
+ })).toBe('http');
73
+ });
74
+ });
75
+ (0, vitest_1.describe)('allowedResourceOrigins / resourceOriginForRequest', () => {
76
+ (0, vitest_1.it)('strips a default port from the configured public URL', () => {
77
+ (0, vitest_1.expect)((0, invoke_origins_js_1.allowedResourceOrigins)('https://mcp.example.com:443', [])).toEqual([
78
+ 'https://mcp.example.com',
79
+ ]);
80
+ (0, vitest_1.expect)((0, invoke_origins_js_1.resourceOriginForRequest)({ headers: { host: 'mcp.example.com' }, socket: {} }, [], 'https://mcp.example.com:443')).toBe('https://mcp.example.com');
81
+ });
82
+ });
@@ -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
+ });