@lightdash-tools/mcp 0.5.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
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionStore = void 0;
4
+ class SessionStore {
5
+ constructor(sessionTtlMs, maxSessions,
6
+ /** `0` disables the per-subject cap (unlimited per subject; global maxSessions still applies). */
7
+ maxSessionsPerSubject) {
8
+ this.sessionTtlMs = sessionTtlMs;
9
+ this.maxSessions = maxSessions;
10
+ this.maxSessionsPerSubject = maxSessionsPerSubject;
11
+ this.sessions = new Map();
12
+ this.subjectSessionCounts = new Map();
13
+ }
14
+ get(sessionId) {
15
+ return this.sessions.get(sessionId);
16
+ }
17
+ set(sessionId, entry) {
18
+ var _a;
19
+ const existing = this.sessions.get(sessionId);
20
+ if (existing) {
21
+ this.decrementSubjectCount(existing);
22
+ }
23
+ this.sessions.set(sessionId, entry);
24
+ const subject = entry.auth.subject;
25
+ if (subject) {
26
+ this.subjectSessionCounts.set(subject, ((_a = this.subjectSessionCounts.get(subject)) !== null && _a !== void 0 ? _a : 0) + 1);
27
+ }
28
+ }
29
+ delete(sessionId) {
30
+ const entry = this.sessions.get(sessionId);
31
+ if (entry) {
32
+ this.decrementSubjectCount(entry);
33
+ }
34
+ this.sessions.delete(sessionId);
35
+ }
36
+ decrementSubjectCount(entry) {
37
+ var _a;
38
+ const subject = entry.auth.subject;
39
+ if (!subject)
40
+ return;
41
+ const count = (_a = this.subjectSessionCounts.get(subject)) !== null && _a !== void 0 ? _a : 0;
42
+ if (count <= 1) {
43
+ this.subjectSessionCounts.delete(subject);
44
+ }
45
+ else {
46
+ this.subjectSessionCounts.set(subject, count - 1);
47
+ }
48
+ }
49
+ touch(sessionId) {
50
+ const entry = this.sessions.get(sessionId);
51
+ if (entry) {
52
+ entry.lastAccessAt = Date.now();
53
+ }
54
+ }
55
+ cleanupExpired(onClose) {
56
+ const now = Date.now();
57
+ for (const [sessionId, entry] of this.sessions) {
58
+ if (now - entry.lastAccessAt > this.sessionTtlMs) {
59
+ this.delete(sessionId);
60
+ onClose(entry, sessionId);
61
+ }
62
+ }
63
+ }
64
+ get size() {
65
+ return this.sessions.size;
66
+ }
67
+ canAcceptNewSession(subject, onClose) {
68
+ var _a;
69
+ this.cleanupExpired(onClose);
70
+ if (this.sessions.size >= this.maxSessions) {
71
+ return false;
72
+ }
73
+ if (subject &&
74
+ this.maxSessionsPerSubject > 0 &&
75
+ ((_a = this.subjectSessionCounts.get(subject)) !== null && _a !== void 0 ? _a : 0) >= this.maxSessionsPerSubject) {
76
+ return false;
77
+ }
78
+ return true;
79
+ }
80
+ drainAll(onClose) {
81
+ for (const [sessionId, entry] of this.sessions) {
82
+ onClose(entry, sessionId);
83
+ }
84
+ this.sessions.clear();
85
+ this.subjectSessionCounts.clear();
86
+ }
87
+ }
88
+ exports.SessionStore = SessionStore;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const session_store_js_1 = require("./session-store.js");
5
+ function createMockEntry(lastAccessAt) {
6
+ return {
7
+ transport: {},
8
+ server: {},
9
+ lastAccessAt,
10
+ auth: { mode: 'lightdash-oauth', tokenHash: 'hash-a' },
11
+ personaId: 'semantic-layer',
12
+ };
13
+ }
14
+ (0, vitest_1.describe)('SessionStore', () => {
15
+ (0, vitest_1.beforeEach)(() => {
16
+ vitest_1.vi.useFakeTimers();
17
+ vitest_1.vi.setSystemTime(new Date('2026-06-15T12:00:00Z'));
18
+ });
19
+ (0, vitest_1.afterEach)(() => {
20
+ vitest_1.vi.useRealTimers();
21
+ });
22
+ (0, vitest_1.it)('stores, retrieves, and deletes sessions', () => {
23
+ const store = new session_store_js_1.SessionStore(60000, 10, 5);
24
+ const entry = createMockEntry(Date.now());
25
+ store.set('session-1', entry);
26
+ (0, vitest_1.expect)(store.get('session-1')).toBe(entry);
27
+ (0, vitest_1.expect)(store.size).toBe(1);
28
+ store.delete('session-1');
29
+ (0, vitest_1.expect)(store.get('session-1')).toBeUndefined();
30
+ (0, vitest_1.expect)(store.size).toBe(0);
31
+ });
32
+ (0, vitest_1.it)('touch updates lastAccessAt for an existing session', () => {
33
+ var _a;
34
+ const store = new session_store_js_1.SessionStore(60000, 10, 5);
35
+ const entry = createMockEntry(1000);
36
+ store.set('session-1', entry);
37
+ vitest_1.vi.setSystemTime(new Date('2026-06-15T12:00:05Z'));
38
+ store.touch('session-1');
39
+ (0, vitest_1.expect)((_a = store.get('session-1')) === null || _a === void 0 ? void 0 : _a.lastAccessAt).toBe(Date.now());
40
+ });
41
+ (0, vitest_1.it)('cleanupExpired removes stale sessions and invokes onClose', () => {
42
+ const store = new session_store_js_1.SessionStore(1000, 10, 5);
43
+ const stale = createMockEntry(Date.now() - 2000);
44
+ const fresh = createMockEntry(Date.now());
45
+ store.set('stale', stale);
46
+ store.set('fresh', fresh);
47
+ const onClose = vitest_1.vi.fn();
48
+ store.cleanupExpired(onClose);
49
+ (0, vitest_1.expect)(store.get('stale')).toBeUndefined();
50
+ (0, vitest_1.expect)(store.get('fresh')).toBe(fresh);
51
+ (0, vitest_1.expect)(onClose).toHaveBeenCalledTimes(1);
52
+ (0, vitest_1.expect)(onClose).toHaveBeenCalledWith(stale, 'stale');
53
+ });
54
+ (0, vitest_1.it)('canAcceptNewSession enforces maxSessions after cleanup', () => {
55
+ const store = new session_store_js_1.SessionStore(60000, 2, 5);
56
+ store.set('a', createMockEntry(Date.now()));
57
+ store.set('b', createMockEntry(Date.now()));
58
+ const onClose = vitest_1.vi.fn();
59
+ (0, vitest_1.expect)(store.canAcceptNewSession(undefined, onClose)).toBe(false);
60
+ store.delete('a');
61
+ (0, vitest_1.expect)(store.canAcceptNewSession(undefined, onClose)).toBe(true);
62
+ });
63
+ (0, vitest_1.it)('canAcceptNewSession closes expired sessions via onClose', () => {
64
+ const store = new session_store_js_1.SessionStore(1000, 2, 5);
65
+ const stale = createMockEntry(Date.now() - 2000);
66
+ store.set('stale', stale);
67
+ store.set('fresh', createMockEntry(Date.now()));
68
+ const onClose = vitest_1.vi.fn();
69
+ (0, vitest_1.expect)(store.canAcceptNewSession(undefined, onClose)).toBe(true);
70
+ (0, vitest_1.expect)(store.get('stale')).toBeUndefined();
71
+ (0, vitest_1.expect)(store.get('fresh')).toBeDefined();
72
+ (0, vitest_1.expect)(onClose).toHaveBeenCalledTimes(1);
73
+ (0, vitest_1.expect)(onClose).toHaveBeenCalledWith(stale, 'stale');
74
+ });
75
+ (0, vitest_1.it)('canAcceptNewSession enforces maxSessionsPerSubject', () => {
76
+ const store = new session_store_js_1.SessionStore(60000, 10, 2);
77
+ const subjectEntry = (subject) => (Object.assign(Object.assign({}, createMockEntry(Date.now())), { auth: { mode: 'lightdash-oauth', tokenHash: 'hash-a', subject } }));
78
+ store.set('a', subjectEntry('user-a'));
79
+ store.set('b', subjectEntry('user-a'));
80
+ const onClose = vitest_1.vi.fn();
81
+ (0, vitest_1.expect)(store.canAcceptNewSession('user-a', onClose)).toBe(false);
82
+ (0, vitest_1.expect)(store.canAcceptNewSession('user-b', onClose)).toBe(true);
83
+ });
84
+ (0, vitest_1.it)('treats maxSessionsPerSubject=0 as unlimited per subject', () => {
85
+ const store = new session_store_js_1.SessionStore(60000, 10, 0);
86
+ const subjectEntry = (subject) => (Object.assign(Object.assign({}, createMockEntry(Date.now())), { auth: { mode: 'lightdash-oauth', tokenHash: 'hash-a', subject } }));
87
+ store.set('a', subjectEntry('user-a'));
88
+ store.set('b', subjectEntry('user-a'));
89
+ store.set('c', subjectEntry('user-a'));
90
+ const onClose = vitest_1.vi.fn();
91
+ (0, vitest_1.expect)(store.canAcceptNewSession('user-a', onClose)).toBe(true);
92
+ });
93
+ (0, vitest_1.it)('enforces maxSessionsPerSubject=1 for a single concurrent session per subject', () => {
94
+ const store = new session_store_js_1.SessionStore(60000, 10, 1);
95
+ const subjectEntry = (subject) => (Object.assign(Object.assign({}, createMockEntry(Date.now())), { auth: { mode: 'lightdash-oauth', tokenHash: 'hash-a', subject } }));
96
+ store.set('a', subjectEntry('user-a'));
97
+ const onClose = vitest_1.vi.fn();
98
+ (0, vitest_1.expect)(store.canAcceptNewSession('user-a', onClose)).toBe(false);
99
+ (0, vitest_1.expect)(store.canAcceptNewSession('user-b', onClose)).toBe(true);
100
+ });
101
+ (0, vitest_1.it)('does not double-count per-subject sessions when overwriting the same session ID', () => {
102
+ const store = new session_store_js_1.SessionStore(60000, 10, 2);
103
+ const first = Object.assign(Object.assign({}, createMockEntry(Date.now())), { auth: { mode: 'lightdash-oauth', tokenHash: 'hash-a', subject: 'user-a' } });
104
+ const replacement = Object.assign(Object.assign({}, createMockEntry(Date.now())), { auth: { mode: 'lightdash-oauth', tokenHash: 'hash-b', subject: 'user-a' } });
105
+ store.set('session-1', first);
106
+ store.set('session-1', replacement);
107
+ const onClose = vitest_1.vi.fn();
108
+ (0, vitest_1.expect)(store.canAcceptNewSession('user-a', onClose)).toBe(true);
109
+ (0, vitest_1.expect)(store.size).toBe(1);
110
+ });
111
+ });
@@ -0,0 +1,9 @@
1
+ import { type McpHttpConfig } from '../config/load-mcp-config.js';
2
+ export interface StreamableHttpServerHandle {
3
+ port: number;
4
+ baseUrl: string;
5
+ config: McpHttpConfig;
6
+ close: () => Promise<void>;
7
+ }
8
+ export declare function createStreamableHttpServer(config?: McpHttpConfig): Promise<StreamableHttpServerHandle>;
9
+ export declare function startStreamableHttpServer(config?: McpHttpConfig): void;
@@ -0,0 +1,454 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createStreamableHttpServer = createStreamableHttpServer;
4
+ exports.startStreamableHttpServer = startStreamableHttpServer;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const node_http_1 = require("node:http");
7
+ const node_1 = require("@modelcontextprotocol/node");
8
+ const audit_js_1 = require("../audit/audit.js");
9
+ const tool_audit_context_js_1 = require("../audit/tool-audit-context.js");
10
+ const auth_mode_js_1 = require("../auth/auth-mode.js");
11
+ const routes_js_1 = require("../auth/oauth-broker/routes.js");
12
+ const bearer_context_provider_js_1 = require("../auth/providers/bearer-context-provider.js");
13
+ const env_context_provider_js_1 = require("../auth/providers/env-context-provider.js");
14
+ const lightdash_oauth_middleware_js_1 = require("../auth/resource-server/lightdash-oauth-middleware.js");
15
+ const oauth_protected_resource_js_1 = require("../auth/resource-server/oauth-protected-resource.js");
16
+ const shared_key_middleware_js_1 = require("../auth/resource-server/shared-key-middleware.js");
17
+ const token_hash_js_1 = require("../auth/token-hash.js");
18
+ const load_mcp_config_js_1 = require("../config/load-mcp-config.js");
19
+ const runtime_js_1 = require("../config/runtime.js");
20
+ const project_pin_js_1 = require("../governance/project-pin.js");
21
+ const index_js_1 = require("../personas/index.js");
22
+ const server_js_1 = require("../server/server.js");
23
+ const http_body_js_1 = require("./http-body.js");
24
+ const http_request_utils_js_1 = require("./http-request-utils.js");
25
+ const http_response_js_1 = require("./http-response.js");
26
+ const session_store_js_1 = require("./session-store.js");
27
+ const ERROR_SESSION_NOT_FOUND = 'Session not found';
28
+ function listen(server, port, host) {
29
+ return new Promise((resolve, reject) => {
30
+ server.once('error', reject);
31
+ server.listen(port, host, () => {
32
+ server.removeListener('error', reject);
33
+ resolve();
34
+ });
35
+ });
36
+ }
37
+ function resolveListenHost(host) {
38
+ return host === '0.0.0.0' ? '127.0.0.1' : host;
39
+ }
40
+ function resolvePublicUrl(publicUrl, listenHost, listenPort) {
41
+ if (!publicUrl) {
42
+ return `http://${listenHost}:${listenPort}`;
43
+ }
44
+ try {
45
+ const url = new URL(publicUrl);
46
+ if (url.port === '0') {
47
+ url.port = String(listenPort);
48
+ return url.origin;
49
+ }
50
+ }
51
+ catch (_a) {
52
+ // Fall through to the configured value when URL parsing fails.
53
+ }
54
+ return publicUrl;
55
+ }
56
+ function resolveHttpConfig(config, listenPort) {
57
+ const listenHost = resolveListenHost(config.host);
58
+ return Object.assign(Object.assign({}, config), { publicUrl: resolvePublicUrl(config.publicUrl, listenHost, listenPort) });
59
+ }
60
+ function getSessionId(req) {
61
+ const sessionId = req.headers['mcp-session-id'];
62
+ return typeof sessionId === 'string' ? sessionId : sessionId === null || sessionId === void 0 ? void 0 : sessionId[0];
63
+ }
64
+ function createEnvContextProvider(config) {
65
+ return new env_context_provider_js_1.EnvContextProvider({
66
+ mode: config.authMode === auth_mode_js_1.MCP_AUTH_MODE_SHARED_KEY ? auth_mode_js_1.MCP_AUTH_MODE_SHARED_KEY : auth_mode_js_1.MCP_AUTH_MODE_NONE,
67
+ client: (0, runtime_js_1.getClient)(),
68
+ });
69
+ }
70
+ function closeSessionEntry(entry, sessionId, reason) {
71
+ void Promise.all([entry.transport.close(), entry.server.close()]).catch((err) => {
72
+ console.error(`Failed to close MCP session ${sessionId} (${reason}):`, err);
73
+ });
74
+ }
75
+ function createSessionTransport(contextProvider, sessionStore, auth, persona) {
76
+ const holder = {
77
+ server: (0, server_js_1.createLightdashMcpServer)(contextProvider, { persona }),
78
+ };
79
+ const transport = new node_1.NodeStreamableHTTPServerTransport({
80
+ sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(),
81
+ onsessioninitialized: (sessionId) => {
82
+ sessionStore.set(sessionId, {
83
+ transport,
84
+ server: holder.server,
85
+ lastAccessAt: Date.now(),
86
+ auth: {
87
+ mode: auth.mode,
88
+ tokenHash: auth.tokenHash,
89
+ subject: auth.subject,
90
+ organizationUuid: auth.organizationUuid,
91
+ },
92
+ contextProvider,
93
+ personaId: persona.id,
94
+ });
95
+ },
96
+ onsessionclosed: (sessionId) => {
97
+ const entry = sessionStore.get(sessionId);
98
+ sessionStore.delete(sessionId);
99
+ if (entry) {
100
+ closeSessionEntry(entry, sessionId, 'closed');
101
+ }
102
+ },
103
+ });
104
+ holder.server.connect(transport).catch((err) => {
105
+ console.error('MCP server connect error:', err);
106
+ });
107
+ return transport;
108
+ }
109
+ function handleHealth(path, res, config) {
110
+ if (path === '/health/live') {
111
+ (0, http_response_js_1.sendJson)(res, 200, { status: 'ok' });
112
+ return;
113
+ }
114
+ try {
115
+ if ((0, load_mcp_config_js_1.requiresLightdashApiKey)(config.authMode)) {
116
+ (0, runtime_js_1.getClient)();
117
+ }
118
+ (0, http_response_js_1.sendJson)(res, 200, { status: 'ready' });
119
+ }
120
+ catch (_a) {
121
+ (0, http_response_js_1.sendJson)(res, 503, { status: 'not ready' });
122
+ }
123
+ }
124
+ /**
125
+ * Auth helpers for persona MCP routes. PRM path resolution lives in
126
+ * `oauth-protected-resource.ts` (single owner for well-known PRM grammar).
127
+ */
128
+ async function ensureEndpointAuth(req, res, config, mcpPath) {
129
+ if (config.authMode === auth_mode_js_1.MCP_AUTH_MODE_NONE) {
130
+ return true;
131
+ }
132
+ if (config.authMode === auth_mode_js_1.MCP_AUTH_MODE_SHARED_KEY) {
133
+ const result = (0, shared_key_middleware_js_1.authenticateSharedKey)(req, config);
134
+ if (!result.ok) {
135
+ (0, http_response_js_1.sendJson)(res, result.status, result.body);
136
+ return false;
137
+ }
138
+ return true;
139
+ }
140
+ const result = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(req, config, mcpPath);
141
+ if (!result.ok) {
142
+ (0, lightdash_oauth_middleware_js_1.writeOAuthAuthFailure)(res, result);
143
+ return false;
144
+ }
145
+ req.lightdashOAuth = result;
146
+ return true;
147
+ }
148
+ function getOAuthAuditContext(req) {
149
+ const oauth = req.lightdashOAuth;
150
+ if (!(oauth === null || oauth === void 0 ? void 0 : oauth.ok)) {
151
+ return {};
152
+ }
153
+ return {
154
+ tokenHash: (0, token_hash_js_1.hashToken)(oauth.accessToken),
155
+ subject: oauth.user.userUuid,
156
+ };
157
+ }
158
+ function verifySessionAuth(req, res, config, mcpPath, entry) {
159
+ var _a, _b;
160
+ if (!entry || config.authMode !== auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH) {
161
+ return true;
162
+ }
163
+ const oauth = req.lightdashOAuth;
164
+ if (!(oauth === null || oauth === void 0 ? void 0 : oauth.accessToken)) {
165
+ (0, lightdash_oauth_middleware_js_1.writeOAuthAuthFailure)(res, (0, lightdash_oauth_middleware_js_1.buildBearerRequiredFailure)(config, mcpPath));
166
+ return false;
167
+ }
168
+ if (entry.auth.subject && entry.auth.subject !== oauth.user.userUuid) {
169
+ (0, lightdash_oauth_middleware_js_1.writeOAuthAuthFailure)(res, (0, lightdash_oauth_middleware_js_1.buildInvalidTokenFailure)(config, mcpPath, 'Session subject mismatch'));
170
+ return false;
171
+ }
172
+ const previousOrg = (_a = entry.auth.organizationUuid) !== null && _a !== void 0 ? _a : null;
173
+ const nextOrg = (_b = oauth.user.organizationUuid) !== null && _b !== void 0 ? _b : null;
174
+ if (previousOrg !== nextOrg) {
175
+ (0, lightdash_oauth_middleware_js_1.writeOAuthAuthFailure)(res, (0, lightdash_oauth_middleware_js_1.buildInvalidTokenFailure)(config, mcpPath, 'Session organization mismatch'));
176
+ return false;
177
+ }
178
+ const nextTokenHash = (0, token_hash_js_1.hashToken)(oauth.accessToken);
179
+ if (entry.auth.tokenHash !== nextTokenHash) {
180
+ entry.auth.tokenHash = nextTokenHash;
181
+ if (entry.contextProvider instanceof bearer_context_provider_js_1.BearerContextProvider) {
182
+ entry.contextProvider.updateAccessToken(oauth.accessToken);
183
+ }
184
+ }
185
+ return true;
186
+ }
187
+ async function handleExistingSessionPost(ctx, sid, body) {
188
+ var _a, _b;
189
+ const { req, res, config, sessionStore, persona } = ctx;
190
+ const entry = sessionStore.get(sid);
191
+ if (!entry) {
192
+ (0, http_response_js_1.sendJson)(res, 404, { error: ERROR_SESSION_NOT_FOUND });
193
+ return;
194
+ }
195
+ if (entry.personaId !== persona.id) {
196
+ (0, http_response_js_1.sendJson)(res, 404, { error: ERROR_SESSION_NOT_FOUND });
197
+ return;
198
+ }
199
+ if (!verifySessionAuth(req, res, config, persona.path, entry))
200
+ return;
201
+ sessionStore.touch(sid);
202
+ const auditAuth = getOAuthAuditContext(req);
203
+ await (0, tool_audit_context_js_1.runWithToolAuditAuthAsync)({
204
+ tokenHash: (_a = auditAuth.tokenHash) !== null && _a !== void 0 ? _a : entry.auth.tokenHash,
205
+ subject: (_b = auditAuth.subject) !== null && _b !== void 0 ? _b : entry.auth.subject,
206
+ }, () => entry.transport.handleRequest(req, res, body));
207
+ }
208
+ async function handleInitializePost(ctx, body) {
209
+ const { req, res, config, sessionStore, persona } = ctx;
210
+ const oauth = config.authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH
211
+ ? req.lightdashOAuth
212
+ : undefined;
213
+ const sessionSubject = (oauth === null || oauth === void 0 ? void 0 : oauth.ok) ? oauth.user.userUuid : undefined;
214
+ if (!sessionStore.canAcceptNewSession(sessionSubject, (entry, sessionId) => {
215
+ closeSessionEntry(entry, sessionId, 'expired');
216
+ })) {
217
+ (0, http_response_js_1.sendJson)(res, 503, { error: 'Service Unavailable: max sessions reached' });
218
+ return;
219
+ }
220
+ if (config.authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH) {
221
+ // ensureEndpointAuth already ran; oauth must be present for this auth mode.
222
+ if (!(oauth === null || oauth === void 0 ? void 0 : oauth.ok)) {
223
+ (0, lightdash_oauth_middleware_js_1.writeOAuthAuthFailure)(res, (0, lightdash_oauth_middleware_js_1.buildBearerRequiredFailure)(config, persona.path));
224
+ return;
225
+ }
226
+ const contextProvider = (0, bearer_context_provider_js_1.createOAuthBearerProvider)(config, {
227
+ accessToken: oauth.accessToken,
228
+ subject: oauth.user.userUuid,
229
+ });
230
+ const transport = createSessionTransport(contextProvider, sessionStore, {
231
+ mode: auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH,
232
+ tokenHash: contextProvider.getTokenHash(),
233
+ subject: oauth.user.userUuid,
234
+ organizationUuid: oauth.user.organizationUuid,
235
+ }, persona);
236
+ await (0, tool_audit_context_js_1.runWithToolAuditAuthAsync)({
237
+ tokenHash: contextProvider.getTokenHash(),
238
+ subject: oauth.user.userUuid,
239
+ }, () => transport.handleRequest(req, res, body));
240
+ return;
241
+ }
242
+ const transport = createSessionTransport(createEnvContextProvider(config), sessionStore, {
243
+ mode: config.authMode,
244
+ }, persona);
245
+ await transport.handleRequest(req, res, body);
246
+ }
247
+ async function handleMcpPost(ctx, sid) {
248
+ const { req, res, config, persona } = ctx;
249
+ if (config.authMode === auth_mode_js_1.MCP_AUTH_MODE_SHARED_KEY ||
250
+ config.authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH) {
251
+ if (!(await ensureEndpointAuth(req, res, config, persona.path))) {
252
+ (0, http_body_js_1.drainRequestBody)(req);
253
+ return;
254
+ }
255
+ }
256
+ const raw = await (0, http_body_js_1.readBody)(req, res, config.maxBodyBytes);
257
+ if (raw === undefined)
258
+ return;
259
+ let body;
260
+ if (raw.length > 0) {
261
+ try {
262
+ body = (0, http_body_js_1.parseJsonBody)(raw);
263
+ }
264
+ catch (_a) {
265
+ (0, http_response_js_1.sendJson)(res, 400, { error: 'Bad Request: invalid JSON body' });
266
+ return;
267
+ }
268
+ }
269
+ if (sid) {
270
+ await handleExistingSessionPost(ctx, sid, body);
271
+ return;
272
+ }
273
+ if (body !== undefined && (0, http_request_utils_js_1.isInitializeMessage)(body)) {
274
+ await handleInitializePost(ctx, body);
275
+ return;
276
+ }
277
+ (0, http_response_js_1.sendJson)(res, 400, {
278
+ error: 'Bad Request: Mcp-Session-Id required for non-initialize requests',
279
+ });
280
+ }
281
+ async function handleMcpGetOrDelete(ctx, sid) {
282
+ var _a, _b;
283
+ const { req, res, config, sessionStore, persona } = ctx;
284
+ if (!sid) {
285
+ (0, http_response_js_1.sendJson)(res, 400, { error: 'Bad Request: Mcp-Session-Id required' });
286
+ return;
287
+ }
288
+ if (config.authMode !== auth_mode_js_1.MCP_AUTH_MODE_NONE) {
289
+ if (!(await ensureEndpointAuth(req, res, config, persona.path)))
290
+ return;
291
+ }
292
+ const entry = sessionStore.get(sid);
293
+ if (!entry || entry.personaId !== persona.id) {
294
+ (0, http_response_js_1.sendJson)(res, 404, { error: ERROR_SESSION_NOT_FOUND });
295
+ return;
296
+ }
297
+ if (!verifySessionAuth(req, res, config, persona.path, entry))
298
+ return;
299
+ sessionStore.touch(sid);
300
+ const auditAuth = getOAuthAuditContext(req);
301
+ await (0, tool_audit_context_js_1.runWithToolAuditAuthAsync)({
302
+ tokenHash: (_a = auditAuth.tokenHash) !== null && _a !== void 0 ? _a : entry.auth.tokenHash,
303
+ subject: (_b = auditAuth.subject) !== null && _b !== void 0 ? _b : entry.auth.subject,
304
+ }, () => entry.transport.handleRequest(req, res));
305
+ }
306
+ async function createStreamableHttpServer(config) {
307
+ var _a;
308
+ const inputConfig = config !== null && config !== void 0 ? config : (0, load_mcp_config_js_1.loadMcpHttpConfig)();
309
+ (0, load_mcp_config_js_1.emitMcpHttpSecurityWarnings)(inputConfig);
310
+ (0, audit_js_1.initAuditLog)((0, runtime_js_1.getAuditLogPath)());
311
+ const sessionStore = new session_store_js_1.SessionStore(inputConfig.sessionTtlMs, inputConfig.maxSessions, inputConfig.maxSessionsPerSubject);
312
+ let httpConfig = inputConfig;
313
+ const cleanupTimer = setInterval(() => {
314
+ sessionStore.cleanupExpired((entry, sessionId) => {
315
+ closeSessionEntry(entry, sessionId, 'expired');
316
+ });
317
+ }, inputConfig.sessionCleanupMs);
318
+ cleanupTimer.unref();
319
+ let oauthBroker;
320
+ const server = (0, node_http_1.createServer)((req, res) => {
321
+ handleHttpRequest(req, res, httpConfig, sessionStore, oauthBroker).catch((err) => {
322
+ console.error('MCP HTTP handler error:', err);
323
+ if (!res.headersSent) {
324
+ (0, http_response_js_1.sendJson)(res, 500, { error: 'Internal Server Error' });
325
+ }
326
+ });
327
+ });
328
+ await listen(server, inputConfig.port, inputConfig.host);
329
+ const address = server.address();
330
+ const port = typeof address === 'object' && address !== null ? address.port : inputConfig.port;
331
+ httpConfig = resolveHttpConfig(inputConfig, port);
332
+ const baseUrl = (_a = httpConfig.publicUrl) !== null && _a !== void 0 ? _a : `http://${resolveListenHost(httpConfig.host)}:${port}`;
333
+ if (httpConfig.authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH) {
334
+ oauthBroker = (0, routes_js_1.createOAuthBroker)(httpConfig);
335
+ }
336
+ return {
337
+ port,
338
+ baseUrl,
339
+ config: httpConfig,
340
+ close: () => new Promise((resolve, reject) => {
341
+ clearInterval(cleanupTimer);
342
+ sessionStore.drainAll((entry, sessionId) => {
343
+ closeSessionEntry(entry, sessionId, 'shutdown');
344
+ });
345
+ server.close((err) => {
346
+ if (err)
347
+ reject(err);
348
+ else
349
+ resolve();
350
+ });
351
+ }),
352
+ };
353
+ }
354
+ function startStreamableHttpServer(config) {
355
+ void createStreamableHttpServer(config)
356
+ .then(({ baseUrl, config: httpConfig }) => {
357
+ const paths = (0, index_js_1.listPersonaPaths)()
358
+ .map((p) => `${baseUrl}${p}`)
359
+ .join(', ');
360
+ console.error(`Lightdash MCP server listening on ${paths} (auth: ${httpConfig.authMode})`);
361
+ if (httpConfig.authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH) {
362
+ console.error(`OAuth PRM: ${(0, oauth_protected_resource_js_1.getProtectedResourceMetadataUrl)(httpConfig)}`);
363
+ console.error(`OAuth callback (register in Lightdash): ${(0, load_mcp_config_js_1.getOAuthCallbackUrl)(httpConfig)}`);
364
+ }
365
+ })
366
+ .catch((err) => {
367
+ console.error('Failed to start MCP HTTP server:', err);
368
+ process.exit(1);
369
+ });
370
+ }
371
+ function requestOrigin(req) {
372
+ return typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
373
+ }
374
+ /**
375
+ * Applies CORS reflect headers without blocking.
376
+ * When `reflectAnyOrigin` is true (OAuth AS / PRM), always echo Origin and ignore
377
+ * `ALLOWED_ORIGINS` so Cursor loopback (`http://localhost:8787`) can read token JSON
378
+ * even if persona MCP routes use a browser allowlist.
379
+ */
380
+ function applyOptionalCorsHeaders(req, res, config, reflectAnyOrigin = false) {
381
+ const allowed = reflectAnyOrigin ? [] : config.allowedOrigins;
382
+ (0, http_response_js_1.applyResponseHeaders)(res, (0, http_response_js_1.buildCorsHeaders)(requestOrigin(req), allowed, reflectAnyOrigin));
383
+ }
384
+ /**
385
+ * Validates Origin and applies CORS headers for persona MCP routes.
386
+ * Short-circuits OPTIONS preflight with 204; returns true when the request is fully handled.
387
+ */
388
+ function applyOriginGuardAndCors(req, res, config) {
389
+ const origin = requestOrigin(req);
390
+ if (!(0, http_response_js_1.checkOrigin)(origin, config.allowedOrigins)) {
391
+ (0, http_response_js_1.sendJson)(res, 403, { error: 'Forbidden: origin not allowed' });
392
+ return true;
393
+ }
394
+ const corsHeaders = (0, http_response_js_1.buildCorsHeaders)(origin, config.allowedOrigins);
395
+ (0, http_response_js_1.applyResponseHeaders)(res, corsHeaders);
396
+ if (req.method === 'OPTIONS') {
397
+ res.writeHead(204, corsHeaders).end();
398
+ return true;
399
+ }
400
+ return false;
401
+ }
402
+ /**
403
+ * Health, OAuth broker, and PRM discovery — no Origin allowlist gate.
404
+ * Returns true when the request was fully handled.
405
+ */
406
+ async function handlePublicHttpPaths(req, res, config, path, oauthBroker) {
407
+ if (path === '/health/live' || path === '/health/ready') {
408
+ applyOptionalCorsHeaders(req, res, config);
409
+ handleHealth(path, res, config);
410
+ return true;
411
+ }
412
+ if (oauthBroker !== undefined && (0, routes_js_1.isOAuthBrokerPath)(path)) {
413
+ applyOptionalCorsHeaders(req, res, config, true);
414
+ return oauthBroker.handle(req, res, path);
415
+ }
416
+ const prmMcpPath = config.authMode === auth_mode_js_1.MCP_AUTH_MODE_LIGHTDASH_OAUTH
417
+ ? (0, oauth_protected_resource_js_1.resolveProtectedResourceMcpPath)(path, config)
418
+ : undefined;
419
+ if (prmMcpPath !== undefined) {
420
+ applyOptionalCorsHeaders(req, res, config, true);
421
+ (0, http_response_js_1.sendJson)(res, 200, (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(config, prmMcpPath));
422
+ return true;
423
+ }
424
+ return false;
425
+ }
426
+ async function handleHttpRequest(req, res, config, sessionStore, oauthBroker) {
427
+ var _a, _b;
428
+ const path = (_b = ((_a = req.url) !== null && _a !== void 0 ? _a : '').split('?')[0]) !== null && _b !== void 0 ? _b : '';
429
+ if (await handlePublicHttpPaths(req, res, config, path, oauthBroker)) {
430
+ return;
431
+ }
432
+ // Persona MCP routes: Origin allowlist is enforced (CSRF / browser blast-radius).
433
+ if (applyOriginGuardAndCors(req, res, config)) {
434
+ return;
435
+ }
436
+ const persona = (0, index_js_1.getPersonaByPath)(path);
437
+ if (!persona) {
438
+ (0, http_response_js_1.sendJson)(res, 404, { error: 'Not Found' });
439
+ return;
440
+ }
441
+ const sid = getSessionId(req);
442
+ const pinnedProjectUuid = (0, project_pin_js_1.extractPinnedProjectFromRequest)(req);
443
+ await (0, project_pin_js_1.runWithProjectPinAsync)(pinnedProjectUuid, async () => {
444
+ if (req.method === 'POST') {
445
+ await handleMcpPost({ req, res, config, sessionStore, persona }, sid);
446
+ return;
447
+ }
448
+ if (req.method === 'GET' || req.method === 'DELETE') {
449
+ await handleMcpGetOrDelete({ req, res, config, sessionStore, persona }, sid);
450
+ return;
451
+ }
452
+ res.writeHead(405, { Allow: 'GET, POST, DELETE' }).end();
453
+ });
454
+ }
@@ -0,0 +1 @@
1
+ export {};