@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,688 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_http_1 = require("node:http");
4
+ const client_1 = require("@lightdash-tools/client");
5
+ const vitest_1 = require("vitest");
6
+ const oauth_protected_resource_js_1 = require("./auth/resource-server/oauth-protected-resource.js");
7
+ const streamable_http_js_1 = require("./transports/streamable-http.js");
8
+ const TOKEN_A = scopedAccessToken('mcp:read mcp:write', 'token-a');
9
+ const TOKEN_B = scopedAccessToken('mcp:read mcp:write', 'token-b');
10
+ const TOKEN_A_REFRESHED = scopedAccessToken('mcp:read mcp:write', 'token-a-refreshed');
11
+ const TOKEN_READ_ONLY = scopedAccessToken('mcp:read', 'token-read-only');
12
+ const OPAQUE_TOKEN_A = 'opaque-token-user-a';
13
+ const OPAQUE_TOKEN_ORG_B = 'opaque-token-org-b';
14
+ const OPAQUE_TOKEN_A_NO_ORG = 'opaque-token-user-a-no-org';
15
+ const USER_A = { userUuid: 'user-a-uuid', email: 'a@example.com', organizationUuid: 'org-a-uuid' };
16
+ const USER_B = { userUuid: 'user-b-uuid', email: 'b@example.com', organizationUuid: 'org-b-uuid' };
17
+ const USER_A_ORG_B = {
18
+ userUuid: 'user-a-uuid',
19
+ email: 'a@example.com',
20
+ organizationUuid: 'org-b-uuid',
21
+ };
22
+ const USER_A_NO_ORG = { userUuid: 'user-a-uuid', email: 'a@example.com' };
23
+ function scopedAccessToken(scope, subject) {
24
+ const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
25
+ const payload = Buffer.from(JSON.stringify({ scope, sub: subject })).toString('base64url');
26
+ return `${header}.${payload}.signature`;
27
+ }
28
+ const INITIALIZE_BODY = {
29
+ jsonrpc: '2.0',
30
+ method: 'initialize',
31
+ params: {
32
+ protocolVersion: '2024-11-05',
33
+ capabilities: {},
34
+ clientInfo: { name: 'integration-test', version: '1.0.0' },
35
+ },
36
+ id: 1,
37
+ };
38
+ function listen(server, port, host) {
39
+ return new Promise((resolve, reject) => {
40
+ server.once('error', reject);
41
+ server.listen(port, host, () => {
42
+ server.removeListener('error', reject);
43
+ resolve();
44
+ });
45
+ });
46
+ }
47
+ async function startMockLightdashServer() {
48
+ const authorizationHeaders = [];
49
+ const users = {
50
+ [TOKEN_A]: USER_A,
51
+ [TOKEN_A_REFRESHED]: USER_A,
52
+ [TOKEN_B]: USER_B,
53
+ [TOKEN_READ_ONLY]: USER_A,
54
+ [OPAQUE_TOKEN_A]: USER_A,
55
+ [OPAQUE_TOKEN_ORG_B]: USER_A_ORG_B,
56
+ [OPAQUE_TOKEN_A_NO_ORG]: USER_A_NO_ORG,
57
+ };
58
+ let issuerBaseUrl = '';
59
+ const server = (0, node_http_1.createServer)((req, res) => {
60
+ var _a;
61
+ const authHeader = req.headers.authorization;
62
+ const auth = typeof authHeader === 'string' ? authHeader : ((_a = authHeader === null || authHeader === void 0 ? void 0 : authHeader[0]) !== null && _a !== void 0 ? _a : '');
63
+ authorizationHeaders.push(auth);
64
+ if (req.method === 'GET' && req.url === '/.well-known/oauth-authorization-server') {
65
+ res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({
66
+ issuer: issuerBaseUrl,
67
+ authorization_endpoint: `${issuerBaseUrl}/api/v1/oauth/authorize`,
68
+ token_endpoint: `${issuerBaseUrl}/api/v1/oauth/token`,
69
+ revocation_endpoint: `${issuerBaseUrl}/api/v1/oauth/revoke`,
70
+ registration_endpoint: `${issuerBaseUrl}/api/v1/oauth/register`,
71
+ userinfo_endpoint: `${issuerBaseUrl}/api/v1/oauth/userinfo`,
72
+ }));
73
+ return;
74
+ }
75
+ if (req.method === 'GET' && req.url === '/api/v1/user') {
76
+ const token = auth.startsWith('Bearer ') ? auth.slice('Bearer '.length).trim() : '';
77
+ const user = users[token];
78
+ if (!user) {
79
+ res.writeHead(401, { 'Content-Type': 'application/json' }).end(JSON.stringify({
80
+ status: 'error',
81
+ error: { statusCode: 401, name: 'Unauthorized', message: 'Invalid token' },
82
+ }));
83
+ return;
84
+ }
85
+ res
86
+ .writeHead(200, { 'Content-Type': 'application/json' })
87
+ .end(JSON.stringify({ status: 'ok', results: user }));
88
+ return;
89
+ }
90
+ if (req.method === 'GET' && req.url === '/api/v1/org/projects') {
91
+ const token = auth.startsWith('Bearer ') ? auth.slice('Bearer '.length).trim() : '';
92
+ if (!users[token]) {
93
+ res.writeHead(401, { 'Content-Type': 'application/json' }).end(JSON.stringify({
94
+ status: 'error',
95
+ error: { statusCode: 401, name: 'Unauthorized', message: 'Invalid token' },
96
+ }));
97
+ return;
98
+ }
99
+ res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({
100
+ status: 'ok',
101
+ results: [
102
+ {
103
+ projectUuid: 'project-a-uuid',
104
+ name: 'Project A',
105
+ type: 'DEFAULT',
106
+ },
107
+ ],
108
+ }));
109
+ return;
110
+ }
111
+ res.writeHead(404).end();
112
+ });
113
+ await listen(server, 0, '127.0.0.1');
114
+ const address = server.address();
115
+ issuerBaseUrl = `http://127.0.0.1:${address.port}`;
116
+ return {
117
+ baseUrl: issuerBaseUrl,
118
+ authorizationHeaders,
119
+ close: () => new Promise((resolve, reject) => {
120
+ server.close((err) => {
121
+ if (err)
122
+ reject(err);
123
+ else
124
+ resolve();
125
+ });
126
+ }),
127
+ };
128
+ }
129
+ function baseOAuthConfig(lightdashUrl) {
130
+ return {
131
+ lightdashUrl,
132
+ host: '127.0.0.1',
133
+ port: 0,
134
+ publicUrl: 'http://127.0.0.1:0',
135
+ mcpPath: '/semantic-layer/v1/mcp',
136
+ authMode: 'lightdash-oauth',
137
+ oauthClientId: 'test-client-id',
138
+ oauthClientSecret: new client_1.SecretString('test-client-secret'),
139
+ allowedOrigins: [],
140
+ maxBodyBytes: 1024 * 1024,
141
+ sessionTtlMs: 60000,
142
+ maxSessions: 10,
143
+ maxSessionsPerSubject: 10,
144
+ sessionCleanupMs: 60000,
145
+ requiredScopes: [],
146
+ scopesSupported: [],
147
+ validateToken: true,
148
+ tokenValidationCacheTtlMs: 30000,
149
+ };
150
+ }
151
+ async function postMcp(baseUrl, body, options) {
152
+ const headers = {
153
+ 'Content-Type': 'application/json',
154
+ Accept: 'application/json, text/event-stream',
155
+ };
156
+ if (options === null || options === void 0 ? void 0 : options.token) {
157
+ headers.Authorization = `Bearer ${options.token}`;
158
+ }
159
+ if (options === null || options === void 0 ? void 0 : options.sessionId) {
160
+ headers['Mcp-Session-Id'] = options.sessionId;
161
+ }
162
+ return fetch(`${baseUrl}/semantic-layer/v1/mcp`, {
163
+ method: 'POST',
164
+ headers,
165
+ body: JSON.stringify(body),
166
+ });
167
+ }
168
+ async function parseMcpResponse(response) {
169
+ var _a;
170
+ const contentType = (_a = response.headers.get('content-type')) !== null && _a !== void 0 ? _a : '';
171
+ const text = await response.text();
172
+ if (contentType.includes('application/json')) {
173
+ return JSON.parse(text);
174
+ }
175
+ const dataLines = text.split('\n').filter((line) => line.startsWith('data: '));
176
+ const last = dataLines.length > 0 ? dataLines[dataLines.length - 1] : undefined;
177
+ if (!last)
178
+ return text;
179
+ return JSON.parse(last.slice('data: '.length));
180
+ }
181
+ (0, vitest_1.describe)('MCP HTTP OAuth integration (RFC §16.3 matrix)', () => {
182
+ let mockLightdash;
183
+ let mcpServer;
184
+ (0, vitest_1.beforeEach)(async () => {
185
+ vitest_1.vi.spyOn(console, 'warn').mockImplementation(() => undefined);
186
+ vitest_1.vi.spyOn(console, 'error').mockImplementation(() => undefined);
187
+ mockLightdash = await startMockLightdashServer();
188
+ mcpServer = await (0, streamable_http_js_1.createStreamableHttpServer)(Object.assign({}, baseOAuthConfig(mockLightdash.baseUrl)));
189
+ });
190
+ (0, vitest_1.afterEach)(async () => {
191
+ await mcpServer.close();
192
+ await mockLightdash.close();
193
+ vitest_1.vi.restoreAllMocks();
194
+ });
195
+ (0, vitest_1.it)('returns 401 with WWW-Authenticate resource_metadata when OAuth token is missing', async () => {
196
+ const response = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY);
197
+ (0, vitest_1.expect)(response.status).toBe(401);
198
+ const wwwAuthenticate = response.headers.get('www-authenticate');
199
+ (0, vitest_1.expect)(wwwAuthenticate).toContain('resource_metadata=');
200
+ (0, vitest_1.expect)(wwwAuthenticate).toContain(`${mcpServer.baseUrl}/.well-known/oauth-protected-resource/semantic-layer/v1/mcp`);
201
+ });
202
+ (0, vitest_1.it)('returns 401 without echoing invalid bearer token in response body', async () => {
203
+ const invalidToken = 'not-a-valid-token';
204
+ const response = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: invalidToken });
205
+ (0, vitest_1.expect)(response.status).toBe(401);
206
+ const body = await response.text();
207
+ (0, vitest_1.expect)(body).not.toContain(invalidToken);
208
+ (0, vitest_1.expect)(response.headers.get('www-authenticate')).toContain('invalid_token');
209
+ });
210
+ (0, vitest_1.it)('initializes MCP session with valid OAuth bearer and validates upstream Authorization', async () => {
211
+ const response = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
212
+ (0, vitest_1.expect)(response.status).toBe(200);
213
+ (0, vitest_1.expect)(response.headers.get('mcp-session-id')).toBeTruthy();
214
+ (0, vitest_1.expect)(mockLightdash.authorizationHeaders).toContain(`Bearer ${TOKEN_A}`);
215
+ });
216
+ (0, vitest_1.it)('returns 401 before 404 for unknown session without auth', async () => {
217
+ const response = await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { sessionId: 'unknown-session-id' });
218
+ (0, vitest_1.expect)(response.status).toBe(401);
219
+ (0, vitest_1.expect)(response.headers.get('www-authenticate')).toContain('resource_metadata=');
220
+ });
221
+ (0, vitest_1.it)('returns 401 Session subject mismatch when resuming with a different user bearer', async () => {
222
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
223
+ const sessionId = initResponse.headers.get('mcp-session-id');
224
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
225
+ const resumeResponse = await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: TOKEN_B, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
226
+ (0, vitest_1.expect)(resumeResponse.status).toBe(401);
227
+ (0, vitest_1.expect)(await resumeResponse.json()).toEqual({
228
+ error: 'invalid_token',
229
+ error_description: 'Session subject mismatch',
230
+ });
231
+ (0, vitest_1.expect)(resumeResponse.headers.get('www-authenticate')).toContain('invalid_token');
232
+ });
233
+ (0, vitest_1.it)('returns 401 Session organization mismatch when resuming with a different org context', async () => {
234
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, {
235
+ token: OPAQUE_TOKEN_A,
236
+ });
237
+ const sessionId = initResponse.headers.get('mcp-session-id');
238
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
239
+ const resumeResponse = await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: OPAQUE_TOKEN_ORG_B, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
240
+ (0, vitest_1.expect)(resumeResponse.status).toBe(401);
241
+ (0, vitest_1.expect)(await resumeResponse.json()).toEqual({
242
+ error: 'invalid_token',
243
+ error_description: 'Session organization mismatch',
244
+ });
245
+ (0, vitest_1.expect)(resumeResponse.headers.get('www-authenticate')).toContain('invalid_token');
246
+ });
247
+ (0, vitest_1.it)('returns 401 Session organization mismatch when org disappears on resume', async () => {
248
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, {
249
+ token: OPAQUE_TOKEN_A,
250
+ });
251
+ const sessionId = initResponse.headers.get('mcp-session-id');
252
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
253
+ const resumeResponse = await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: OPAQUE_TOKEN_A_NO_ORG, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
254
+ (0, vitest_1.expect)(resumeResponse.status).toBe(401);
255
+ (0, vitest_1.expect)(await resumeResponse.json()).toEqual({
256
+ error: 'invalid_token',
257
+ error_description: 'Session organization mismatch',
258
+ });
259
+ });
260
+ (0, vitest_1.it)('protected-resource metadata authorization_servers points at MCP broker AS metadata', async () => {
261
+ const response = await fetch(`${mcpServer.baseUrl}/.well-known/oauth-protected-resource`);
262
+ (0, vitest_1.expect)(response.status).toBe(200);
263
+ const metadata = (await response.json());
264
+ (0, vitest_1.expect)(metadata.authorization_servers).toEqual([mcpServer.baseUrl]);
265
+ const asMetadataUrl = (0, oauth_protected_resource_js_1.getAuthorizationServerMetadataUrl)(metadata.authorization_servers[0]);
266
+ (0, vitest_1.expect)(asMetadataUrl).toBe(`${mcpServer.baseUrl}/.well-known/oauth-authorization-server`);
267
+ const asResponse = await fetch(asMetadataUrl);
268
+ (0, vitest_1.expect)(asResponse.status).toBe(200);
269
+ const asMetadata = (await asResponse.json());
270
+ (0, vitest_1.expect)(asMetadata.authorization_endpoint).toBe(`${mcpServer.baseUrl}/oauth/authorize`);
271
+ (0, vitest_1.expect)(asMetadata.token_endpoint).toBe(`${mcpServer.baseUrl}/oauth/token`);
272
+ (0, vitest_1.expect)(asMetadata.registration_endpoint).toBe(`${mcpServer.baseUrl}/oauth/register`);
273
+ });
274
+ (0, vitest_1.it)('allows token refresh for the same OAuth subject within a session', async () => {
275
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
276
+ const sessionId = initResponse.headers.get('mcp-session-id');
277
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
278
+ const resumeResponse = await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: TOKEN_A_REFRESHED, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
279
+ (0, vitest_1.expect)([200, 202]).toContain(resumeResponse.status);
280
+ (0, vitest_1.expect)(mockLightdash.authorizationHeaders).toContain(`Bearer ${TOKEN_A_REFRESHED}`);
281
+ });
282
+ (0, vitest_1.it)('returns 401 before parsing malformed JSON when OAuth token is missing', async () => {
283
+ const response = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
284
+ method: 'POST',
285
+ headers: {
286
+ 'Content-Type': 'application/json',
287
+ Accept: 'application/json, text/event-stream',
288
+ },
289
+ body: '{not-json',
290
+ });
291
+ (0, vitest_1.expect)(response.status).toBe(401);
292
+ (0, vitest_1.expect)(response.headers.get('www-authenticate')).toContain('resource_metadata=');
293
+ });
294
+ (0, vitest_1.it)('returns 401 invalid_token for invalid bearer before accepting valid JSON', async () => {
295
+ const response = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, {
296
+ token: 'not-a-valid-token',
297
+ });
298
+ (0, vitest_1.expect)(response.status).toBe(401);
299
+ (0, vitest_1.expect)(response.headers.get('www-authenticate')).toContain('invalid_token');
300
+ });
301
+ (0, vitest_1.it)('returns 400 for malformed JSON only after successful OAuth authentication', async () => {
302
+ const response = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
303
+ method: 'POST',
304
+ headers: {
305
+ 'Content-Type': 'application/json',
306
+ Accept: 'application/json, text/event-stream',
307
+ Authorization: `Bearer ${TOKEN_A}`,
308
+ },
309
+ body: '{not-json',
310
+ });
311
+ (0, vitest_1.expect)(response.status).toBe(400);
312
+ (0, vitest_1.expect)(await response.json()).toEqual({ error: 'Bad Request: invalid JSON body' });
313
+ });
314
+ (0, vitest_1.it)('serves OAuth protected resource metadata at /.well-known/oauth-protected-resource', async () => {
315
+ const response = await fetch(`${mcpServer.baseUrl}/.well-known/oauth-protected-resource`);
316
+ (0, vitest_1.expect)(response.status).toBe(200);
317
+ const metadata = await response.json();
318
+ (0, vitest_1.expect)(metadata).toEqual({
319
+ resource: `${mcpServer.baseUrl}/semantic-layer/v1/mcp`,
320
+ authorization_servers: [mcpServer.baseUrl],
321
+ bearer_methods_supported: ['header'],
322
+ scopes_supported: [],
323
+ });
324
+ });
325
+ (0, vitest_1.it)('serves path-specific OAuth protected resource metadata', async () => {
326
+ const response = await fetch(`${mcpServer.baseUrl}/.well-known/oauth-protected-resource/semantic-layer/v1/mcp`);
327
+ (0, vitest_1.expect)(response.status).toBe(200);
328
+ const metadata = await response.json();
329
+ (0, vitest_1.expect)(metadata.resource).toBe(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`);
330
+ });
331
+ (0, vitest_1.it)('serves organization-audit path-specific OAuth protected resource metadata', async () => {
332
+ const response = await fetch(`${mcpServer.baseUrl}/.well-known/oauth-protected-resource/organization-audit/v1/mcp`);
333
+ (0, vitest_1.expect)(response.status).toBe(200);
334
+ const metadata = await response.json();
335
+ (0, vitest_1.expect)(metadata.resource).toBe(`${mcpServer.baseUrl}/organization-audit/v1/mcp`);
336
+ });
337
+ (0, vitest_1.it)('returns 401 with organization-audit resource_metadata on that persona path', async () => {
338
+ const response = await fetch(`${mcpServer.baseUrl}/organization-audit/v1/mcp`, {
339
+ method: 'POST',
340
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
341
+ body: JSON.stringify(INITIALIZE_BODY),
342
+ });
343
+ (0, vitest_1.expect)(response.status).toBe(401);
344
+ const wwwAuthenticate = response.headers.get('www-authenticate');
345
+ (0, vitest_1.expect)(wwwAuthenticate).toContain(`${mcpServer.baseUrl}/.well-known/oauth-protected-resource/organization-audit/v1/mcp`);
346
+ (0, vitest_1.expect)(wwwAuthenticate).not.toContain('semantic-layer/v1/mcp');
347
+ });
348
+ (0, vitest_1.it)('maps token-a and token-b to distinct authenticated users upstream', async () => {
349
+ const responseA = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
350
+ const responseB = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_B });
351
+ (0, vitest_1.expect)(responseA.status).toBe(200);
352
+ (0, vitest_1.expect)(responseB.status).toBe(200);
353
+ (0, vitest_1.expect)(mockLightdash.authorizationHeaders).toContain(`Bearer ${TOKEN_A}`);
354
+ (0, vitest_1.expect)(mockLightdash.authorizationHeaders).toContain(`Bearer ${TOKEN_B}`);
355
+ });
356
+ (0, vitest_1.it)('returns 503 when Lightdash user validation is unavailable', async () => {
357
+ const unavailableServer = (0, node_http_1.createServer)((_req, res) => {
358
+ res.writeHead(503, { 'Content-Type': 'application/json' }).end(JSON.stringify({
359
+ status: 'error',
360
+ error: { statusCode: 503, name: 'ServiceUnavailable', message: 'Down' },
361
+ }));
362
+ });
363
+ await listen(unavailableServer, 0, '127.0.0.1');
364
+ const unavailableAddress = unavailableServer.address();
365
+ const unavailableUrl = `http://127.0.0.1:${unavailableAddress.port}`;
366
+ const downServer = await (0, streamable_http_js_1.createStreamableHttpServer)(Object.assign({}, baseOAuthConfig(unavailableUrl)));
367
+ try {
368
+ const response = await postMcp(downServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
369
+ (0, vitest_1.expect)(response.status).toBe(503);
370
+ (0, vitest_1.expect)(await response.json()).toEqual({
371
+ error: 'temporarily_unavailable',
372
+ error_description: 'Lightdash is temporarily unavailable',
373
+ });
374
+ }
375
+ finally {
376
+ await downServer.close();
377
+ await new Promise((resolve, reject) => {
378
+ unavailableServer.close((err) => {
379
+ if (err)
380
+ reject(err);
381
+ else
382
+ resolve();
383
+ });
384
+ });
385
+ }
386
+ });
387
+ });
388
+ (0, vitest_1.describe)('MCP HTTP CORS integration', () => {
389
+ let mockLightdash;
390
+ let mcpServer;
391
+ (0, vitest_1.beforeEach)(async () => {
392
+ vitest_1.vi.spyOn(console, 'warn').mockImplementation(() => undefined);
393
+ vitest_1.vi.spyOn(console, 'error').mockImplementation(() => undefined);
394
+ mockLightdash = await startMockLightdashServer();
395
+ mcpServer = await (0, streamable_http_js_1.createStreamableHttpServer)(Object.assign(Object.assign({}, baseOAuthConfig(mockLightdash.baseUrl)), { allowedOrigins: ['https://app.example.com'] }));
396
+ });
397
+ (0, vitest_1.afterEach)(async () => {
398
+ await mcpServer.close();
399
+ await mockLightdash.close();
400
+ vitest_1.vi.restoreAllMocks();
401
+ });
402
+ (0, vitest_1.it)('sets CORS headers for allowed origins on metadata', async () => {
403
+ const response = await fetch(`${mcpServer.baseUrl}/.well-known/oauth-protected-resource`, {
404
+ headers: { Origin: 'https://app.example.com' },
405
+ });
406
+ (0, vitest_1.expect)(response.status).toBe(200);
407
+ (0, vitest_1.expect)(response.headers.get('access-control-allow-origin')).toBe('https://app.example.com');
408
+ (0, vitest_1.expect)(response.headers.get('vary')).toBe('Origin');
409
+ });
410
+ (0, vitest_1.it)('handles CORS preflight OPTIONS requests', async () => {
411
+ const response = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
412
+ method: 'OPTIONS',
413
+ headers: { Origin: 'https://app.example.com' },
414
+ });
415
+ (0, vitest_1.expect)(response.status).toBe(204);
416
+ (0, vitest_1.expect)(response.headers.get('access-control-allow-origin')).toBe('https://app.example.com');
417
+ (0, vitest_1.expect)(response.headers.get('access-control-allow-methods')).toContain('POST');
418
+ (0, vitest_1.expect)(response.headers.get('access-control-allow-headers')).toContain('MCP-Protocol-Version');
419
+ });
420
+ (0, vitest_1.it)('returns 403 for disallowed origins', async () => {
421
+ const response = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
422
+ method: 'OPTIONS',
423
+ headers: { Origin: 'https://evil.example.com' },
424
+ });
425
+ (0, vitest_1.expect)(response.status).toBe(403);
426
+ (0, vitest_1.expect)(response.headers.get('access-control-allow-origin')).toBeNull();
427
+ const body = (await response.json());
428
+ (0, vitest_1.expect)(body.error).toContain('origin not allowed');
429
+ });
430
+ });
431
+ (0, vitest_1.describe)('MCP HTTP OAuth integration (continued)', () => {
432
+ let mockLightdash;
433
+ let mcpServer;
434
+ (0, vitest_1.beforeEach)(async () => {
435
+ vitest_1.vi.spyOn(console, 'warn').mockImplementation(() => undefined);
436
+ vitest_1.vi.spyOn(console, 'error').mockImplementation(() => undefined);
437
+ mockLightdash = await startMockLightdashServer();
438
+ mcpServer = await (0, streamable_http_js_1.createStreamableHttpServer)(Object.assign({}, baseOAuthConfig(mockLightdash.baseUrl)));
439
+ });
440
+ (0, vitest_1.afterEach)(async () => {
441
+ await mcpServer.close();
442
+ await mockLightdash.close();
443
+ vitest_1.vi.restoreAllMocks();
444
+ });
445
+ (0, vitest_1.it)('calls lightdash_list_projects over an OAuth HTTP session', async () => {
446
+ var _a, _b, _c, _d;
447
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
448
+ const sessionId = initResponse.headers.get('mcp-session-id');
449
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
450
+ const userCallsBefore = mockLightdash.authorizationHeaders.length;
451
+ await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: TOKEN_A, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
452
+ const callResponse = await postMcp(mcpServer.baseUrl, {
453
+ jsonrpc: '2.0',
454
+ method: 'tools/call',
455
+ params: { name: 'lightdash_list_projects', arguments: {} },
456
+ id: 2,
457
+ }, { token: TOKEN_A, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
458
+ (0, vitest_1.expect)(callResponse.status).toBe(200);
459
+ const payload = (await parseMcpResponse(callResponse));
460
+ const text = (_d = (_c = (_b = (_a = payload.result) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.text) !== null && _d !== void 0 ? _d : '';
461
+ (0, vitest_1.expect)(text).toContain('project-a-uuid');
462
+ (0, vitest_1.expect)(text).not.toContain(TOKEN_A);
463
+ (0, vitest_1.expect)(mockLightdash.authorizationHeaders.length).toBeGreaterThan(userCallsBefore);
464
+ (0, vitest_1.expect)(mockLightdash.authorizationHeaders).toContain(`Bearer ${TOKEN_A}`);
465
+ });
466
+ (0, vitest_1.it)('forwards refreshed bearer token to Lightdash on tool calls after session resume', async () => {
467
+ var _a, _b, _c, _d;
468
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
469
+ const sessionId = initResponse.headers.get('mcp-session-id');
470
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
471
+ await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: TOKEN_A_REFRESHED, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
472
+ const headersBeforeTool = mockLightdash.authorizationHeaders.length;
473
+ const callResponse = await postMcp(mcpServer.baseUrl, {
474
+ jsonrpc: '2.0',
475
+ method: 'tools/call',
476
+ params: { name: 'lightdash_list_projects', arguments: {} },
477
+ id: 6,
478
+ }, { token: TOKEN_A_REFRESHED, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
479
+ (0, vitest_1.expect)(callResponse.status).toBe(200);
480
+ const payload = (await parseMcpResponse(callResponse));
481
+ (0, vitest_1.expect)((_d = (_c = (_b = (_a = payload.result) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.text) !== null && _d !== void 0 ? _d : '').toContain('project-a-uuid');
482
+ const toolHeaders = mockLightdash.authorizationHeaders.slice(headersBeforeTool);
483
+ (0, vitest_1.expect)(toolHeaders).toContain(`Bearer ${TOKEN_A_REFRESHED}`);
484
+ (0, vitest_1.expect)(toolHeaders).not.toContain(`Bearer ${TOKEN_A}`);
485
+ });
486
+ (0, vitest_1.it)('initializes MCP session with opaque OAuth bearer when endpoint scopes are unset', async () => {
487
+ const response = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: OPAQUE_TOKEN_A });
488
+ (0, vitest_1.expect)(response.status).toBe(200);
489
+ (0, vitest_1.expect)(response.headers.get('mcp-session-id')).toBeTruthy();
490
+ (0, vitest_1.expect)(mockLightdash.authorizationHeaders).toContain(`Bearer ${OPAQUE_TOKEN_A}`);
491
+ });
492
+ (0, vitest_1.it)('lists nine semantic-layer tools under mcp:read-only JWT scopes', async () => {
493
+ var _a, _b, _c;
494
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, {
495
+ token: TOKEN_READ_ONLY,
496
+ });
497
+ const sessionId = initResponse.headers.get('mcp-session-id');
498
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
499
+ await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: TOKEN_READ_ONLY, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
500
+ const listResponse = await postMcp(mcpServer.baseUrl, {
501
+ jsonrpc: '2.0',
502
+ method: 'tools/list',
503
+ id: 3,
504
+ }, { token: TOKEN_READ_ONLY, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
505
+ (0, vitest_1.expect)(listResponse.status).toBe(200);
506
+ const payload = (await parseMcpResponse(listResponse));
507
+ (0, vitest_1.expect)((_a = payload.result) === null || _a === void 0 ? void 0 : _a.tools).toHaveLength(9);
508
+ (0, vitest_1.expect)((_c = (_b = payload.result) === null || _b === void 0 ? void 0 : _b.tools) === null || _c === void 0 ? void 0 : _c.every((t) => t.name.startsWith('lightdash_'))).toBe(true);
509
+ });
510
+ (0, vitest_1.it)('allows read tools when JWT scopes include mcp:read only', async () => {
511
+ var _a, _b, _c, _d, _e;
512
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, {
513
+ token: TOKEN_READ_ONLY,
514
+ });
515
+ const sessionId = initResponse.headers.get('mcp-session-id');
516
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
517
+ await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: TOKEN_READ_ONLY, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
518
+ const callResponse = await postMcp(mcpServer.baseUrl, {
519
+ jsonrpc: '2.0',
520
+ method: 'tools/call',
521
+ params: { name: 'lightdash_list_projects', arguments: {} },
522
+ id: 4,
523
+ }, { token: TOKEN_READ_ONLY, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
524
+ (0, vitest_1.expect)(callResponse.status).toBe(200);
525
+ const payload = (await parseMcpResponse(callResponse));
526
+ (0, vitest_1.expect)((_a = payload.result) === null || _a === void 0 ? void 0 : _a.isError).not.toBe(true);
527
+ (0, vitest_1.expect)((_e = (_d = (_c = (_b = payload.result) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.text) !== null && _e !== void 0 ? _e : '').toContain('project-a-uuid');
528
+ });
529
+ (0, vitest_1.it)('does not block read tools for opaque OAuth credentials without local scope claims', async () => {
530
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
531
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, {
532
+ token: OPAQUE_TOKEN_A,
533
+ });
534
+ const sessionId = initResponse.headers.get('mcp-session-id');
535
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
536
+ await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: OPAQUE_TOKEN_A, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
537
+ const callResponse = await postMcp(mcpServer.baseUrl, {
538
+ jsonrpc: '2.0',
539
+ method: 'tools/call',
540
+ params: { name: 'lightdash_list_projects', arguments: {} },
541
+ id: 5,
542
+ }, { token: OPAQUE_TOKEN_A, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
543
+ (0, vitest_1.expect)(callResponse.status).toBe(200);
544
+ const payload = (await parseMcpResponse(callResponse));
545
+ (0, vitest_1.expect)((_a = payload.result) === null || _a === void 0 ? void 0 : _a.isError).not.toBe(true);
546
+ (0, vitest_1.expect)((_e = (_d = (_c = (_b = payload.result) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.text) !== null && _e !== void 0 ? _e : '').not.toContain('insufficient_scope');
547
+ (0, vitest_1.expect)((_j = (_h = (_g = (_f = payload.result) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.text) !== null && _j !== void 0 ? _j : '').toContain('project-a-uuid');
548
+ });
549
+ });
550
+ (0, vitest_1.describe)('MCP HTTP OAuth transport lifecycle', () => {
551
+ let mockLightdash;
552
+ let mcpServer;
553
+ (0, vitest_1.beforeEach)(async () => {
554
+ vitest_1.vi.spyOn(console, 'warn').mockImplementation(() => undefined);
555
+ vitest_1.vi.spyOn(console, 'error').mockImplementation(() => undefined);
556
+ mockLightdash = await startMockLightdashServer();
557
+ mcpServer = await (0, streamable_http_js_1.createStreamableHttpServer)(Object.assign(Object.assign({}, baseOAuthConfig(mockLightdash.baseUrl)), { maxBodyBytes: 512 }));
558
+ });
559
+ (0, vitest_1.afterEach)(async () => {
560
+ await mcpServer.close();
561
+ await mockLightdash.close();
562
+ vitest_1.vi.restoreAllMocks();
563
+ });
564
+ (0, vitest_1.it)('supports initialize → notification → GET on the same OAuth session', async () => {
565
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
566
+ const sessionId = initResponse.headers.get('mcp-session-id');
567
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
568
+ const notifyResponse = await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: TOKEN_A, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
569
+ (0, vitest_1.expect)([200, 202]).toContain(notifyResponse.status);
570
+ const getResponse = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
571
+ method: 'GET',
572
+ headers: {
573
+ Accept: 'application/json, text/event-stream',
574
+ Authorization: `Bearer ${TOKEN_A}`,
575
+ 'Mcp-Session-Id': sessionId !== null && sessionId !== void 0 ? sessionId : '',
576
+ },
577
+ });
578
+ (0, vitest_1.expect)(getResponse.status).not.toBe(401);
579
+ (0, vitest_1.expect)(getResponse.status).not.toBe(404);
580
+ });
581
+ (0, vitest_1.it)('returns 413 for oversized JSON body after OAuth authentication', async () => {
582
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
583
+ const sessionId = initResponse.headers.get('mcp-session-id');
584
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
585
+ const hugeBody = JSON.stringify({
586
+ jsonrpc: '2.0',
587
+ method: 'notifications/initialized',
588
+ params: { padding: 'x'.repeat(1024) },
589
+ });
590
+ const response = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
591
+ method: 'POST',
592
+ headers: {
593
+ 'Content-Type': 'application/json',
594
+ Accept: 'application/json, text/event-stream',
595
+ Authorization: `Bearer ${TOKEN_A}`,
596
+ 'Mcp-Session-Id': sessionId !== null && sessionId !== void 0 ? sessionId : '',
597
+ },
598
+ body: hugeBody,
599
+ });
600
+ (0, vitest_1.expect)(response.status).toBe(413);
601
+ (0, vitest_1.expect)(await response.json()).toEqual({ error: 'Payload Too Large' });
602
+ });
603
+ (0, vitest_1.it)('closes session on DELETE and rejects subsequent resume with 404', async () => {
604
+ const initResponse = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, { token: TOKEN_A });
605
+ const sessionId = initResponse.headers.get('mcp-session-id');
606
+ (0, vitest_1.expect)(sessionId).toBeTruthy();
607
+ const deleteResponse = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
608
+ method: 'DELETE',
609
+ headers: {
610
+ Accept: 'application/json, text/event-stream',
611
+ Authorization: `Bearer ${TOKEN_A}`,
612
+ 'Mcp-Session-Id': sessionId !== null && sessionId !== void 0 ? sessionId : '',
613
+ },
614
+ });
615
+ (0, vitest_1.expect)([200, 202, 204]).toContain(deleteResponse.status);
616
+ const resumeResponse = await postMcp(mcpServer.baseUrl, { jsonrpc: '2.0', method: 'notifications/initialized' }, { token: TOKEN_A, sessionId: sessionId !== null && sessionId !== void 0 ? sessionId : undefined });
617
+ (0, vitest_1.expect)(resumeResponse.status).toBe(404);
618
+ (0, vitest_1.expect)(await resumeResponse.json()).toEqual({ error: 'Session not found' });
619
+ });
620
+ });
621
+ (0, vitest_1.describe)('MCP HTTP shared-key integration', () => {
622
+ let mcpServer;
623
+ const originalEnv = Object.assign({}, process.env);
624
+ (0, vitest_1.beforeEach)(async () => {
625
+ vitest_1.vi.spyOn(console, 'warn').mockImplementation(() => undefined);
626
+ vitest_1.vi.spyOn(console, 'error').mockImplementation(() => undefined);
627
+ process.env.LIGHTDASH_URL = 'https://app.lightdash.cloud';
628
+ process.env.LIGHTDASH_API_KEY = 'ldpat_test_key';
629
+ mcpServer = await (0, streamable_http_js_1.createStreamableHttpServer)({
630
+ lightdashUrl: 'https://app.lightdash.cloud',
631
+ host: '127.0.0.1',
632
+ port: 0,
633
+ mcpPath: '/semantic-layer/v1/mcp',
634
+ authMode: 'shared-key',
635
+ sharedKey: new client_1.SecretString('shared-secret'),
636
+ allowedOrigins: [],
637
+ maxBodyBytes: 1024 * 1024,
638
+ sessionTtlMs: 60000,
639
+ maxSessions: 10,
640
+ maxSessionsPerSubject: 10,
641
+ sessionCleanupMs: 60000,
642
+ requiredScopes: [],
643
+ scopesSupported: ['mcp:read'],
644
+ validateToken: false,
645
+ tokenValidationCacheTtlMs: 30000,
646
+ });
647
+ });
648
+ (0, vitest_1.afterEach)(async () => {
649
+ await mcpServer.close();
650
+ process.env = Object.assign({}, originalEnv);
651
+ vitest_1.vi.restoreAllMocks();
652
+ });
653
+ (0, vitest_1.it)('requires shared key on MCP endpoint', async () => {
654
+ const unauthorized = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY);
655
+ (0, vitest_1.expect)(unauthorized.status).toBe(401);
656
+ const authorized = await postMcp(mcpServer.baseUrl, INITIALIZE_BODY, {
657
+ token: 'shared-secret',
658
+ });
659
+ (0, vitest_1.expect)(authorized.status).toBe(200);
660
+ (0, vitest_1.expect)(authorized.headers.get('mcp-session-id')).toBeTruthy();
661
+ });
662
+ (0, vitest_1.it)('returns 401 before reading oversized bodies when shared key is missing', async () => {
663
+ const hugeBody = JSON.stringify(Object.assign(Object.assign({}, INITIALIZE_BODY), { params: Object.assign(Object.assign({}, INITIALIZE_BODY.params), { padding: 'x'.repeat(2048) }) }));
664
+ const response = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
665
+ method: 'POST',
666
+ headers: {
667
+ 'Content-Type': 'application/json',
668
+ Accept: 'application/json, text/event-stream',
669
+ },
670
+ body: hugeBody,
671
+ });
672
+ (0, vitest_1.expect)(response.status).toBe(401);
673
+ (0, vitest_1.expect)(await response.json()).toEqual({ error: 'Unauthorized' });
674
+ });
675
+ (0, vitest_1.it)('accepts shared key via X-API-Key header', async () => {
676
+ const response = await fetch(`${mcpServer.baseUrl}/semantic-layer/v1/mcp`, {
677
+ method: 'POST',
678
+ headers: {
679
+ 'Content-Type': 'application/json',
680
+ Accept: 'application/json, text/event-stream',
681
+ 'X-API-Key': 'shared-secret',
682
+ },
683
+ body: JSON.stringify(INITIALIZE_BODY),
684
+ });
685
+ (0, vitest_1.expect)(response.status).toBe(200);
686
+ (0, vitest_1.expect)(response.headers.get('mcp-session-id')).toBeTruthy();
687
+ });
688
+ });