@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
@@ -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;
@@ -2,12 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isOAuthBrokerPath = isOAuthBrokerPath;
4
4
  exports.createOAuthBroker = createOAuthBroker;
5
+ const enabled_profiles_js_1 = require("../../config/enabled-profiles.js");
5
6
  const env_js_1 = require("../../config/env.js");
6
7
  const normalize_url_js_1 = require("../../config/normalize-url.js");
8
+ const public_url_js_1 = require("../../config/public-url.js");
7
9
  const http_body_js_1 = require("../../transports/http-body.js");
8
10
  const http_response_js_1 = require("../../transports/http-response.js");
9
11
  const as_metadata_js_1 = require("./as-metadata.js");
12
+ const invoke_origins_js_1 = require("./invoke-origins.js");
10
13
  const lightdash_token_js_1 = require("./lightdash-token.js");
14
+ const mcp_access_token_js_1 = require("./mcp-access-token.js");
11
15
  const pending_store_js_1 = require("./pending-store.js");
12
16
  const pkce_js_1 = require("./pkce.js");
13
17
  /** Schemes that must never be used as OAuth redirect targets. */
@@ -94,6 +98,32 @@ function isAllowedClientRedirectUri(redirectUri) {
94
98
  return false;
95
99
  }
96
100
  }
101
+ function canonicalProfileResource(resource) {
102
+ try {
103
+ const url = new URL(resource);
104
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') ||
105
+ url.username !== '' ||
106
+ url.password !== '' ||
107
+ url.search !== '' ||
108
+ url.hash !== '') {
109
+ return undefined;
110
+ }
111
+ return `${url.origin}${url.pathname}`;
112
+ }
113
+ catch (_a) {
114
+ return undefined;
115
+ }
116
+ }
117
+ function allowedMcpResource(config, resource) {
118
+ const canonical = canonicalProfileResource(resource);
119
+ if (canonical === undefined) {
120
+ return undefined;
121
+ }
122
+ const profilePaths = (0, enabled_profiles_js_1.listEnabledProfilePaths)(config.enabledProfiles);
123
+ const origins = (0, invoke_origins_js_1.allowedResourceOrigins)((0, public_url_js_1.requirePublicUrl)(config, 'OAuth resource validation'), config.invokeOrigins);
124
+ const allowed = origins.some((origin) => profilePaths.some((profilePath) => canonical === `${origin}${profilePath}`));
125
+ return allowed ? canonical : undefined;
126
+ }
97
127
  async function parseRegisteredClientRedirect(query, store) {
98
128
  const clientId = query.get('client_id');
99
129
  if (!clientId) {
@@ -139,8 +169,8 @@ async function parseRegisteredClientRedirect(query, store) {
139
169
  }
140
170
  return { ok: true, clientId, redirectUri };
141
171
  }
142
- async function parseAuthorizeRequest(query, store) {
143
- var _a, _b, _c, _d, _e;
172
+ async function parseAuthorizeRequest(query, config, store) {
173
+ var _a, _b, _c, _d;
144
174
  const responseType = query.get('response_type');
145
175
  if (responseType !== 'code') {
146
176
  return {
@@ -168,6 +198,29 @@ async function parseAuthorizeRequest(query, store) {
168
198
  },
169
199
  };
170
200
  }
201
+ const resources = query.getAll('resource');
202
+ if (resources.length !== 1 || resources[0].length === 0) {
203
+ return {
204
+ ok: false,
205
+ status: 400,
206
+ body: {
207
+ error: 'invalid_request',
208
+ error_description: 'Exactly one MCP resource parameter is required',
209
+ },
210
+ };
211
+ }
212
+ const resource = resources[0];
213
+ const allowedResource = allowedMcpResource(config, resource);
214
+ if (allowedResource === undefined) {
215
+ return {
216
+ ok: false,
217
+ status: 400,
218
+ body: {
219
+ error: 'invalid_target',
220
+ error_description: 'resource must identify an enabled MCP profile endpoint',
221
+ },
222
+ };
223
+ }
171
224
  return {
172
225
  ok: true,
173
226
  value: {
@@ -175,8 +228,8 @@ async function parseAuthorizeRequest(query, store) {
175
228
  redirectUri: registered.redirectUri,
176
229
  clientState: (_c = query.get('state')) !== null && _c !== void 0 ? _c : undefined,
177
230
  codeChallenge,
178
- resource: (_d = query.get('resource')) !== null && _d !== void 0 ? _d : undefined,
179
- scope: (_e = query.get('scope')) !== null && _e !== void 0 ? _e : undefined,
231
+ resource: allowedResource,
232
+ scope: (_d = query.get('scope')) !== null && _d !== void 0 ? _d : undefined,
180
233
  },
181
234
  };
182
235
  }
@@ -185,7 +238,7 @@ async function handleAuthorize(req, res, config, store) {
185
238
  res.writeHead(405, { Allow: 'GET' }).end();
186
239
  return;
187
240
  }
188
- const parsed = await parseAuthorizeRequest(readQuery(req), store);
241
+ const parsed = await parseAuthorizeRequest(readQuery(req), config, store);
189
242
  if (!parsed.ok) {
190
243
  (0, http_response_js_1.sendJson)(res, parsed.status, parsed.body);
191
244
  return;
@@ -197,17 +250,16 @@ async function handleAuthorize(req, res, config, store) {
197
250
  clientState,
198
251
  codeChallenge,
199
252
  codeChallengeMethod: 'S256',
253
+ resource,
200
254
  scope,
201
255
  });
202
256
  if (!pending) {
203
257
  (0, http_response_js_1.sendJson)(res, 503, Object.assign({}, AS_BUSY));
204
258
  return;
205
259
  }
206
- redirect(res, (0, lightdash_token_js_1.buildLightdashAuthorizeUrl)(config, {
207
- state: pending.brokerState,
208
- scope,
209
- resource,
210
- }));
260
+ // The MCP resource/scope belong to the client→broker leg. Do not forward them
261
+ // to Lightdash, whose OAuth client and protected resource are distinct.
262
+ redirect(res, (0, lightdash_token_js_1.buildLightdashAuthorizeUrl)(config, { state: pending.brokerState }));
211
263
  }
212
264
  function redirectToClient(res, redirectUri, params) {
213
265
  const target = new URL(redirectUri);
@@ -251,12 +303,13 @@ async function handleCallback(req, res, config, store) {
251
303
  }
252
304
  try {
253
305
  const tokens = await (0, lightdash_token_js_1.exchangeLightdashAuthorizationCode)(config, code);
254
- // Do not persist/return refresh_token: broker only supports authorization_code.
306
+ // The downstream credential remains server-side. The later MCP token endpoint
307
+ // wraps it in an authenticated-encrypted, resource-bound broker token.
308
+ // Refresh tokens are deliberately neither persisted nor returned.
255
309
  const issued = await store.issueCode(pending, {
256
310
  accessToken: tokens.access_token,
257
311
  expiresIn: tokens.expires_in,
258
312
  tokenType: tokens.token_type,
259
- scope: tokens.scope,
260
313
  });
261
314
  if (!issued) {
262
315
  redirectToClient(res, pending.redirectUri, Object.assign(Object.assign({}, AS_BUSY), { state: pending.clientState }));
@@ -276,10 +329,9 @@ async function handleCallback(req, res, config, store) {
276
329
  });
277
330
  }
278
331
  }
279
- async function validateTokenGrant(params, store) {
332
+ function parseTokenGrantRequest(params) {
280
333
  var _a;
281
- const grantType = params.get('grant_type');
282
- if (grantType !== 'authorization_code') {
334
+ if (params.get('grant_type') !== 'authorization_code') {
283
335
  return {
284
336
  status: 400,
285
337
  body: {
@@ -292,44 +344,50 @@ async function validateTokenGrant(params, store) {
292
344
  const redirectUri = params.get('redirect_uri');
293
345
  const clientId = params.get('client_id');
294
346
  const codeVerifier = (_a = params.get('code_verifier')) !== null && _a !== void 0 ? _a : undefined;
295
- if (!code || !redirectUri || !clientId) {
347
+ const resources = params.getAll('resource');
348
+ const resource = resources.length === 1 ? resources[0] : undefined;
349
+ if (!code || !redirectUri || !clientId || !resource) {
296
350
  return {
297
351
  status: 400,
298
352
  body: {
299
353
  error: 'invalid_request',
300
- error_description: 'code, redirect_uri, and client_id are required',
354
+ error_description: 'code, redirect_uri, client_id, and exactly one resource are required',
301
355
  },
302
356
  };
303
357
  }
304
- // Atomic take first (multi-instance safe). Restore on validation failure so a
305
- // bad verifier / redirect does not permanently burn a one-time code.
306
- const candidate = await store.takeCode(code);
358
+ return { code, redirectUri, clientId, codeVerifier, resource };
359
+ }
360
+ async function restoreInvalidGrant(store, candidate, description) {
361
+ await store.restoreCode(candidate);
362
+ return {
363
+ status: 400,
364
+ body: { error: 'invalid_grant', error_description: description },
365
+ };
366
+ }
367
+ async function validateTokenGrant(params, store) {
368
+ const request = parseTokenGrantRequest(params);
369
+ if ('status' in request)
370
+ return request;
371
+ // Atomic take first. Restore on validation failure so a bad verifier / redirect /
372
+ // resource does not permanently burn a one-time code.
373
+ const candidate = await store.takeCode(request.code);
307
374
  if (!candidate) {
308
375
  return {
309
376
  status: 400,
310
377
  body: { error: 'invalid_grant', error_description: 'Invalid or expired code' },
311
378
  };
312
379
  }
313
- if (candidate.redirectUri !== redirectUri) {
314
- await store.restoreCode(candidate);
315
- return {
316
- status: 400,
317
- body: { error: 'invalid_grant', error_description: 'redirect_uri mismatch' },
318
- };
380
+ if (candidate.redirectUri !== request.redirectUri) {
381
+ return restoreInvalidGrant(store, candidate, 'redirect_uri mismatch');
319
382
  }
320
- if (candidate.clientId !== clientId) {
321
- await store.restoreCode(candidate);
322
- return {
323
- status: 400,
324
- body: { error: 'invalid_grant', error_description: 'client_id mismatch' },
325
- };
383
+ if (candidate.clientId !== request.clientId) {
384
+ return restoreInvalidGrant(store, candidate, 'client_id mismatch');
326
385
  }
327
- if (!(0, pkce_js_1.verifyPkce)(codeVerifier, candidate.codeChallenge, candidate.codeChallengeMethod)) {
328
- await store.restoreCode(candidate);
329
- return {
330
- status: 400,
331
- body: { error: 'invalid_grant', error_description: 'PKCE verification failed' },
332
- };
386
+ if (candidate.resource !== canonicalProfileResource(request.resource)) {
387
+ return restoreInvalidGrant(store, candidate, 'resource mismatch');
388
+ }
389
+ if (!(0, pkce_js_1.verifyPkce)(request.codeVerifier, candidate.codeChallenge, candidate.codeChallengeMethod)) {
390
+ return restoreInvalidGrant(store, candidate, 'PKCE verification failed');
333
391
  }
334
392
  return { issued: candidate };
335
393
  }
@@ -348,12 +406,29 @@ async function handleToken(req, res, config, store) {
348
406
  return;
349
407
  }
350
408
  const { issued } = grant;
351
- (0, http_response_js_1.sendJson)(res, 200, {
352
- access_token: issued.accessToken,
353
- token_type: issued.tokenType,
354
- expires_in: (_a = issued.expiresIn) !== null && _a !== void 0 ? _a : 3600,
355
- scope: issued.scope,
356
- });
409
+ const upstreamLifetimeSeconds = (_a = issued.expiresIn) !== null && _a !== void 0 ? _a : 3600;
410
+ const expiresAtMs = issued.createdAt + upstreamLifetimeSeconds * 1000;
411
+ try {
412
+ const minted = (0, mcp_access_token_js_1.mintMcpAccessToken)(config, {
413
+ lightdashAccessToken: issued.accessToken,
414
+ clientId: issued.clientId,
415
+ resource: issued.resource,
416
+ scope: issued.scope,
417
+ expiresAtMs,
418
+ });
419
+ (0, http_response_js_1.sendJson)(res, 200, {
420
+ access_token: minted.accessToken,
421
+ token_type: 'Bearer',
422
+ expires_in: minted.expiresIn,
423
+ scope: issued.scope,
424
+ });
425
+ }
426
+ catch (_b) {
427
+ (0, http_response_js_1.sendJson)(res, 400, {
428
+ error: 'invalid_grant',
429
+ error_description: 'Upstream Lightdash credential expired before broker token issuance',
430
+ });
431
+ }
357
432
  }
358
433
  async function handleRegister(req, res, config, store) {
359
434
  var _a;
@@ -398,8 +473,8 @@ async function handleRegister(req, res, config, store) {
398
473
  client_name: (_a = params.get('client_name')) !== null && _a !== void 0 ? _a : 'MCP Client',
399
474
  });
400
475
  }
401
- function handleAsMetadata(res, config) {
402
- (0, http_response_js_1.sendJson)(res, 200, (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(config));
476
+ function handleAsMetadata(req, res, config) {
477
+ (0, http_response_js_1.sendJson)(res, 200, (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(config, (0, invoke_origins_js_1.resourceOriginForRequest)(req, config.invokeOrigins, (0, public_url_js_1.requirePublicUrl)(config, 'OAuth resource origin'))));
403
478
  }
404
479
  const BROKER_PATHS = new Set([
405
480
  env_js_1.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH,
@@ -414,7 +489,8 @@ function isOAuthBrokerPath(path) {
414
489
  }
415
490
  /**
416
491
  * Creates the OAuth broker request handler for co-located AS façade routes.
417
- * Pending state is process-local (InMemoryOAuthBrokerStore); sticky `/oauth/*` for multi-instance.
492
+ * Pending authorization/code state is process-local, so `/oauth/*` still needs
493
+ * sticky routing or one replica. Issued MCP access tokens are self-contained.
418
494
  */
419
495
  function createOAuthBroker(config, store = new pending_store_js_1.InMemoryOAuthBrokerStore()) {
420
496
  return {
@@ -427,7 +503,7 @@ function createOAuthBroker(config, store = new pending_store_js_1.InMemoryOAuthB
427
503
  return true;
428
504
  }
429
505
  if (path === env_js_1.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH && req.method === 'GET') {
430
- handleAsMetadata(res, config);
506
+ handleAsMetadata(req, res, config);
431
507
  return true;
432
508
  }
433
509
  if (path === env_js_1.OAUTH_AUTHORIZE_PATH) {