@lightdash-tools/mcp 0.1.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 (49) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +53 -0
  3. package/dist/config.d.ts +11 -0
  4. package/dist/config.js +16 -0
  5. package/dist/errors.d.ts +8 -0
  6. package/dist/errors.js +29 -0
  7. package/dist/http.d.ts +5 -0
  8. package/dist/http.js +172 -0
  9. package/dist/index.d.ts +5 -0
  10. package/dist/index.js +36 -0
  11. package/dist/index.test.d.ts +1 -0
  12. package/dist/index.test.js +9 -0
  13. package/dist/tools/charts.d.ts +6 -0
  14. package/dist/tools/charts.js +55 -0
  15. package/dist/tools/dashboards.d.ts +6 -0
  16. package/dist/tools/dashboards.js +28 -0
  17. package/dist/tools/explores.d.ts +6 -0
  18. package/dist/tools/explores.js +40 -0
  19. package/dist/tools/groups.d.ts +6 -0
  20. package/dist/tools/groups.js +41 -0
  21. package/dist/tools/index.d.ts +6 -0
  22. package/dist/tools/index.js +24 -0
  23. package/dist/tools/projects.d.ts +6 -0
  24. package/dist/tools/projects.js +37 -0
  25. package/dist/tools/query.d.ts +6 -0
  26. package/dist/tools/query.js +34 -0
  27. package/dist/tools/shared.d.ts +39 -0
  28. package/dist/tools/shared.js +68 -0
  29. package/dist/tools/spaces.d.ts +6 -0
  30. package/dist/tools/spaces.js +40 -0
  31. package/dist/tools/users.d.ts +6 -0
  32. package/dist/tools/users.js +50 -0
  33. package/package.json +23 -0
  34. package/src/config.ts +16 -0
  35. package/src/errors.ts +27 -0
  36. package/src/http.ts +184 -0
  37. package/src/index.test.ts +8 -0
  38. package/src/index.ts +28 -0
  39. package/src/tools/charts.ts +85 -0
  40. package/src/tools/dashboards.ts +25 -0
  41. package/src/tools/explores.ts +46 -0
  42. package/src/tools/groups.ts +49 -0
  43. package/src/tools/index.ts +25 -0
  44. package/src/tools/projects.ts +39 -0
  45. package/src/tools/query.ts +47 -0
  46. package/src/tools/shared.ts +101 -0
  47. package/src/tools/spaces.ts +46 -0
  48. package/src/tools/users.ts +64 -0
  49. package/tsconfig.json +13 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # @lightdash-tools/mcp
2
+
3
+ MCP server for Lightdash: exposes projects, charts, dashboards, spaces, users, and groups as tools. Uses `@lightdash-tools/client` for all API access.
4
+
5
+ ## Transports
6
+
7
+ - **Stdio** — for local use (e.g. Claude Desktop, IDE). One process per client.
8
+ - **Streamable HTTP** — for remote use. Session-based; supports optional endpoint auth.
9
+
10
+ ## Environment variables
11
+
12
+ ### Required (both modes)
13
+
14
+ - `LIGHTDASH_URL` — Lightdash instance base URL (e.g. `https://app.lightdash.cloud`).
15
+ - `LIGHTDASH_API_KEY` — Personal access token or API key.
16
+
17
+ ### Streamable HTTP only
18
+
19
+ - `MCP_HTTP_PORT` — Port for the HTTP server (default: `3100`).
20
+ - `MCP_AUTH_ENABLED` — Set to `1`, `true`, or `yes` to require auth on the MCP endpoint.
21
+ - `MCP_API_KEY` — When auth is enabled, requests must send this value via `Authorization: Bearer <MCP_API_KEY>` or `X-API-Key: <MCP_API_KEY>`.
22
+
23
+ ## Running
24
+
25
+ ### Stdio (local)
26
+
27
+ ```bash
28
+ pnpm build
29
+ pnpm start
30
+ # or: node dist/index.js
31
+ ```
32
+
33
+ Use with Claude Desktop or an IDE by configuring the MCP server command (e.g. `node` with path to `dist/index.js`). Logging goes to stderr only; stdout is JSON-RPC.
34
+
35
+ ### Streamable HTTP (remote)
36
+
37
+ ```bash
38
+ pnpm build
39
+ pnpm start:http
40
+ # or: node dist/http.js
41
+ ```
42
+
43
+ The server listens on `http://localhost:3100` (or `MCP_HTTP_PORT`). MCP endpoint: `POST/GET/DELETE /mcp`. Sessions are created on first `initialize`; subsequent requests must include the `Mcp-Session-Id` header returned by the server.
44
+
45
+ With auth disabled (default), any client can call the endpoint. With `MCP_AUTH_ENABLED` set, send `Authorization: Bearer <token>` or `X-API-Key: <key>` matching `MCP_API_KEY`; otherwise the server returns 401.
46
+
47
+ ## Tools
48
+
49
+ Same set in both modes: `list_projects`, `get_project`, `list_charts`, `list_dashboards`, `list_spaces`, `get_space`, `list_organization_members`, `get_member`, `delete_member`, `list_groups`, `get_group`.
50
+
51
+ ### Destructive tools
52
+
53
+ Tools with `destructiveHint: true` (e.g. `delete_member`) perform irreversible or high-impact actions. MCP clients should show a warning and/or require user confirmation before executing them. AI agents should ask the user for explicit confirmation before calling such tools.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * MCP server config: build Lightdash client config from environment.
3
+ * Uses same env vars as CLI: LIGHTDASH_URL, LIGHTDASH_API_KEY.
4
+ */
5
+ import { LightdashClient } from '@lightdash-tools/client';
6
+ import type { PartialLightdashClientConfig } from '@lightdash-tools/client';
7
+ /**
8
+ * Builds a LightdashClient from environment variables (and optional overrides).
9
+ * Throws if LIGHTDASH_URL or LIGHTDASH_API_KEY are missing.
10
+ */
11
+ export declare function getClient(config?: PartialLightdashClientConfig): LightdashClient;
package/dist/config.js ADDED
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ /**
3
+ * MCP server config: build Lightdash client config from environment.
4
+ * Uses same env vars as CLI: LIGHTDASH_URL, LIGHTDASH_API_KEY.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.getClient = getClient;
8
+ const client_1 = require("@lightdash-tools/client");
9
+ /**
10
+ * Builds a LightdashClient from environment variables (and optional overrides).
11
+ * Throws if LIGHTDASH_URL or LIGHTDASH_API_KEY are missing.
12
+ */
13
+ function getClient(config) {
14
+ const merged = (0, client_1.mergeConfig)(config);
15
+ return new client_1.LightdashClient(merged);
16
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Map Lightdash client errors to safe user-facing messages for MCP responses.
3
+ * Never expose stack traces or tokens.
4
+ */
5
+ /**
6
+ * Returns a short, safe message for MCP content from a client error.
7
+ */
8
+ export declare function toMcpErrorMessage(err: unknown): string;
package/dist/errors.js ADDED
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ /**
3
+ * Map Lightdash client errors to safe user-facing messages for MCP responses.
4
+ * Never expose stack traces or tokens.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.toMcpErrorMessage = toMcpErrorMessage;
8
+ const client_1 = require("@lightdash-tools/client");
9
+ /**
10
+ * Returns a short, safe message for MCP content from a client error.
11
+ */
12
+ function toMcpErrorMessage(err) {
13
+ var _a, _b;
14
+ if (err instanceof client_1.RateLimitError) {
15
+ const after = err.retryAfter != null ? ` Retry after ${err.retryAfter}s.` : '';
16
+ return `Rate limited (${err.statusCode}).${after}`;
17
+ }
18
+ if (err instanceof client_1.LightdashApiError) {
19
+ const msg = (_b = (_a = err.error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : `HTTP ${err.statusCode}`;
20
+ return `Lightdash API error: ${msg}`;
21
+ }
22
+ if (err instanceof client_1.NetworkError) {
23
+ return `Network error: ${err.message}`;
24
+ }
25
+ if (err instanceof Error) {
26
+ return err.message || 'Unknown error';
27
+ }
28
+ return String(err);
29
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * MCP server entrypoint (Streamable HTTP). Use LIGHTDASH_URL, LIGHTDASH_API_KEY.
3
+ * Optional: MCP_AUTH_ENABLED, MCP_API_KEY. Logging: stderr only.
4
+ */
5
+ export {};
package/dist/http.js ADDED
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ /**
3
+ * MCP server entrypoint (Streamable HTTP). Use LIGHTDASH_URL, LIGHTDASH_API_KEY.
4
+ * Optional: MCP_AUTH_ENABLED, MCP_API_KEY. Logging: stderr only.
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ var _a;
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ const node_http_1 = require("node:http");
18
+ const node_crypto_1 = require("node:crypto");
19
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
20
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
21
+ const config_js_1 = require("./config.js");
22
+ const index_js_1 = require("./tools/index.js");
23
+ const MCP_PATH = '/mcp';
24
+ const PORT = Number((_a = process.env.MCP_HTTP_PORT) !== null && _a !== void 0 ? _a : '3100');
25
+ const sessionMap = new Map();
26
+ const sharedClient = (0, config_js_1.getClient)();
27
+ function isAuthEnabled() {
28
+ const v = process.env.MCP_AUTH_ENABLED;
29
+ return v === '1' || v === 'true' || v === 'yes';
30
+ }
31
+ function getExpectedApiKey() {
32
+ return process.env.MCP_API_KEY;
33
+ }
34
+ function authMiddleware(req, res) {
35
+ if (!isAuthEnabled())
36
+ return true;
37
+ const expected = getExpectedApiKey();
38
+ if (!expected) {
39
+ console.error('MCP_AUTH_ENABLED is set but MCP_API_KEY is missing');
40
+ res
41
+ .writeHead(500, { 'Content-Type': 'application/json' })
42
+ .end(JSON.stringify({ error: 'Server auth misconfiguration' }));
43
+ return false;
44
+ }
45
+ const bearer = req.headers.authorization;
46
+ const apiKey = req.headers['x-api-key'];
47
+ const token = typeof bearer === 'string' && bearer.startsWith('Bearer ') ? bearer.slice(7).trim() : undefined;
48
+ const key = typeof apiKey === 'string' ? apiKey.trim() : undefined;
49
+ const provided = token !== null && token !== void 0 ? token : key;
50
+ if (!provided || provided !== expected) {
51
+ res
52
+ .writeHead(401, { 'Content-Type': 'application/json' })
53
+ .end(JSON.stringify({ error: 'Unauthorized' }));
54
+ return false;
55
+ }
56
+ return true;
57
+ }
58
+ function createSessionTransport() {
59
+ const server = new mcp_js_1.McpServer({ name: 'lightdash-mcp', version: '1.0.0' });
60
+ (0, index_js_1.registerTools)(server, sharedClient);
61
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
62
+ sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(),
63
+ onsessioninitialized: (sessionId) => {
64
+ sessionMap.set(sessionId, transport);
65
+ },
66
+ onsessionclosed: (sessionId) => {
67
+ sessionMap.delete(sessionId);
68
+ },
69
+ });
70
+ server.connect(transport).catch((err) => {
71
+ console.error('MCP server connect error:', err);
72
+ });
73
+ return transport;
74
+ }
75
+ function readBody(req) {
76
+ return new Promise((resolve, reject) => {
77
+ const chunks = [];
78
+ req.on('data', (chunk) => chunks.push(chunk));
79
+ req.on('end', () => resolve(Buffer.concat(chunks)));
80
+ req.on('error', reject);
81
+ });
82
+ }
83
+ function parseJsonBody(buffer) {
84
+ const text = buffer.toString('utf-8');
85
+ if (!text.trim())
86
+ return undefined;
87
+ return JSON.parse(text);
88
+ }
89
+ function isInitializeMessage(body) {
90
+ if (body === undefined)
91
+ return false;
92
+ const msg = Array.isArray(body) ? body[0] : body;
93
+ return (typeof msg === 'object' &&
94
+ msg !== null &&
95
+ 'method' in msg &&
96
+ msg.method === 'initialize');
97
+ }
98
+ function handleRequest(req, res) {
99
+ return __awaiter(this, void 0, void 0, function* () {
100
+ var _a;
101
+ if (!authMiddleware(req, res))
102
+ return;
103
+ const url = (_a = req.url) !== null && _a !== void 0 ? _a : '';
104
+ const path = url.split('?')[0];
105
+ if (path !== MCP_PATH) {
106
+ res
107
+ .writeHead(404, { 'Content-Type': 'application/json' })
108
+ .end(JSON.stringify({ error: 'Not Found' }));
109
+ return;
110
+ }
111
+ const sessionId = req.headers['mcp-session-id'];
112
+ const sid = typeof sessionId === 'string' ? sessionId : Array.isArray(sessionId) ? sessionId[0] : undefined;
113
+ if (req.method === 'POST') {
114
+ const raw = yield readBody(req);
115
+ const body = raw.length > 0 ? parseJsonBody(raw) : undefined;
116
+ if (sid) {
117
+ const transport = sessionMap.get(sid);
118
+ if (!transport) {
119
+ res
120
+ .writeHead(404, { 'Content-Type': 'application/json' })
121
+ .end(JSON.stringify({ error: 'Session not found' }));
122
+ return;
123
+ }
124
+ yield transport.handleRequest(req, res, body);
125
+ return;
126
+ }
127
+ if (body !== undefined && isInitializeMessage(body)) {
128
+ const transport = createSessionTransport();
129
+ yield transport.handleRequest(req, res, body);
130
+ return;
131
+ }
132
+ res.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({
133
+ error: 'Bad Request: Mcp-Session-Id required for non-initialize requests',
134
+ }));
135
+ return;
136
+ }
137
+ if (req.method === 'GET' || req.method === 'DELETE') {
138
+ if (!sid) {
139
+ res
140
+ .writeHead(400, { 'Content-Type': 'application/json' })
141
+ .end(JSON.stringify({ error: 'Bad Request: Mcp-Session-Id required' }));
142
+ return;
143
+ }
144
+ const transport = sessionMap.get(sid);
145
+ if (!transport) {
146
+ res
147
+ .writeHead(404, { 'Content-Type': 'application/json' })
148
+ .end(JSON.stringify({ error: 'Session not found' }));
149
+ return;
150
+ }
151
+ yield transport.handleRequest(req, res);
152
+ return;
153
+ }
154
+ res.writeHead(405, { Allow: 'GET, POST, DELETE' }).end();
155
+ });
156
+ }
157
+ function main() {
158
+ const server = (0, node_http_1.createServer)((req, res) => {
159
+ handleRequest(req, res).catch((err) => {
160
+ console.error('MCP HTTP handler error:', err);
161
+ if (!res.headersSent) {
162
+ res
163
+ .writeHead(500, { 'Content-Type': 'application/json' })
164
+ .end(JSON.stringify({ error: 'Internal Server Error' }));
165
+ }
166
+ });
167
+ });
168
+ server.listen(PORT, () => {
169
+ console.error(`Lightdash MCP server listening on http://localhost:${PORT}${MCP_PATH}`);
170
+ });
171
+ }
172
+ main();
@@ -0,0 +1,5 @@
1
+ /**
2
+ * MCP server entrypoint (Stdio). Use LIGHTDASH_URL and LIGHTDASH_API_KEY.
3
+ * Logging: stderr only (stdout is JSON-RPC).
4
+ */
5
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * MCP server entrypoint (Stdio). Use LIGHTDASH_URL and LIGHTDASH_API_KEY.
4
+ * Logging: stderr only (stdout is JSON-RPC).
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
17
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
18
+ const config_1 = require("./config");
19
+ const tools_1 = require("./tools");
20
+ function main() {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ const client = (0, config_1.getClient)();
23
+ const server = new mcp_js_1.McpServer({
24
+ name: 'lightdash-mcp',
25
+ version: '1.0.0',
26
+ });
27
+ (0, tools_1.registerTools)(server, client);
28
+ const transport = new stdio_js_1.StdioServerTransport();
29
+ yield server.connect(transport);
30
+ console.error('Lightdash MCP server running on stdio');
31
+ });
32
+ }
33
+ main().catch((err) => {
34
+ console.error('Fatal:', err);
35
+ process.exit(1);
36
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const tools_1 = require("./tools");
5
+ (0, vitest_1.describe)('MCP tools', () => {
6
+ (0, vitest_1.it)('registerTools is a function', () => {
7
+ (0, vitest_1.expect)(typeof tools_1.registerTools).toBe('function');
8
+ });
9
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * MCP tools: charts (list, charts-as-code list and upsert).
3
+ */
4
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import type { LightdashClient } from '@lightdash-tools/client';
6
+ export declare function registerChartTools(server: McpServer, client: LightdashClient): void;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ /**
3
+ * MCP tools: charts (list, charts-as-code list and upsert).
4
+ */
5
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
6
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7
+ return new (P || (P = Promise))(function (resolve, reject) {
8
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
12
+ });
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.registerChartTools = registerChartTools;
16
+ const zod_1 = require("zod");
17
+ const shared_js_1 = require("./shared.js");
18
+ function registerChartTools(server, client) {
19
+ (0, shared_js_1.registerToolSafe)(server, 'list_charts', {
20
+ title: 'List charts',
21
+ description: 'List charts in a project',
22
+ inputSchema: { projectUuid: zod_1.z.string().describe('Project UUID') },
23
+ annotations: shared_js_1.READ_ONLY_DEFAULT,
24
+ }, (0, shared_js_1.wrapTool)(client, (c) => (_a) => __awaiter(this, [_a], void 0, function* ({ projectUuid }) {
25
+ const charts = yield c.v1.charts.listCharts(projectUuid);
26
+ return { content: [{ type: 'text', text: JSON.stringify(charts, null, 2) }] };
27
+ })));
28
+ (0, shared_js_1.registerToolSafe)(server, 'list_charts_as_code', {
29
+ title: 'List charts as code',
30
+ description: 'Get charts in code representation for a project (for charts-as-code workflows)',
31
+ inputSchema: {
32
+ projectUuid: zod_1.z.string().describe('Project UUID'),
33
+ ids: zod_1.z.array(zod_1.z.string()).optional().describe('Optional chart IDs (slugs) to filter'),
34
+ },
35
+ annotations: shared_js_1.READ_ONLY_DEFAULT,
36
+ }, (0, shared_js_1.wrapTool)(client, (c) => (_a) => __awaiter(this, [_a], void 0, function* ({ projectUuid, ids }) {
37
+ const result = yield c.v1.charts.getChartsAsCode(projectUuid, { ids });
38
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
39
+ })));
40
+ (0, shared_js_1.registerToolSafe)(server, 'upsert_chart_as_code', {
41
+ title: 'Upsert chart as code',
42
+ description: 'Create or update a chart from its code representation (by slug)',
43
+ inputSchema: {
44
+ projectUuid: zod_1.z.string().describe('Project UUID'),
45
+ slug: zod_1.z.string().describe('Chart slug'),
46
+ chart: zod_1.z
47
+ .record(zod_1.z.string(), zod_1.z.unknown())
48
+ .describe('Chart-as-code payload (name, metricQuery, chartConfig, etc.)'),
49
+ },
50
+ annotations: shared_js_1.WRITE_IDEMPOTENT,
51
+ }, (0, shared_js_1.wrapTool)(client, (c) => (_a) => __awaiter(this, [_a], void 0, function* ({ projectUuid, slug, chart, }) {
52
+ const result = yield c.v1.charts.upsertChartAsCode(projectUuid, slug, chart);
53
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
54
+ })));
55
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * MCP tools: dashboards (list).
3
+ */
4
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import type { LightdashClient } from '@lightdash-tools/client';
6
+ export declare function registerDashboardTools(server: McpServer, client: LightdashClient): void;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ /**
3
+ * MCP tools: dashboards (list).
4
+ */
5
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
6
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7
+ return new (P || (P = Promise))(function (resolve, reject) {
8
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
12
+ });
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.registerDashboardTools = registerDashboardTools;
16
+ const zod_1 = require("zod");
17
+ const shared_js_1 = require("./shared.js");
18
+ function registerDashboardTools(server, client) {
19
+ (0, shared_js_1.registerToolSafe)(server, 'list_dashboards', {
20
+ title: 'List dashboards',
21
+ description: 'List dashboards in a project',
22
+ inputSchema: { projectUuid: zod_1.z.string().describe('Project UUID') },
23
+ annotations: shared_js_1.READ_ONLY_DEFAULT,
24
+ }, (0, shared_js_1.wrapTool)(client, (c) => (_a) => __awaiter(this, [_a], void 0, function* ({ projectUuid }) {
25
+ const dashboards = yield c.v1.dashboards.listDashboards(projectUuid);
26
+ return { content: [{ type: 'text', text: JSON.stringify(dashboards, null, 2) }] };
27
+ })));
28
+ }