@lightdash-tools/mcp 0.6.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
@@ -1,365 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import { registerToolSafe, READ_ONLY_DEFAULT, WRITE_DESTRUCTIVE, WRITE_IDEMPOTENT } from './shared';
3
- import { SafetyMode } from '@lightdash-tools/common';
4
- import { setStaticSafetyMode, setStaticAllowedProjectUuids, setDryRunMode } from '../config.js';
5
-
6
- // Silence audit log output during tests
7
- vi.mock('@lightdash-tools/common', async (importOriginal) => {
8
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
- const actual = await importOriginal<any>();
10
- return {
11
- ...actual,
12
- getSessionId: () => 'test-session',
13
- logAuditEntry: vi.fn(),
14
- initAuditLog: vi.fn(),
15
- };
16
- });
17
-
18
- describe('registerToolSafe', () => {
19
- const mockServer = {
20
- registerTool: vi.fn(),
21
- };
22
-
23
- const mockHandler = vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'success' }] });
24
-
25
- beforeEach(() => {
26
- mockServer.registerTool.mockClear();
27
- mockHandler.mockClear();
28
- // Reset globals to safe defaults
29
- setStaticSafetyMode(SafetyMode.WRITE_DESTRUCTIVE);
30
- setStaticAllowedProjectUuids([]);
31
- setDryRunMode(false);
32
- process.env.LIGHTDASH_TOOLS_SAFETY_MODE = SafetyMode.WRITE_DESTRUCTIVE;
33
- delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
34
- delete process.env.LIGHTDASH_TOOLS_DRY_RUN;
35
- });
36
-
37
- afterEach(() => {
38
- delete process.env.LIGHTDASH_TOOLS_SAFETY_MODE;
39
- });
40
-
41
- it('should allow read-only tool in read-only mode', async () => {
42
- process.env.LIGHTDASH_TOOLS_SAFETY_MODE = SafetyMode.READ_ONLY;
43
- setStaticSafetyMode(SafetyMode.WRITE_DESTRUCTIVE); // static = allow all
44
-
45
- registerToolSafe(
46
- mockServer,
47
- 'test_tool',
48
- {
49
- description: 'Test description',
50
- inputSchema: {},
51
- annotations: READ_ONLY_DEFAULT,
52
- },
53
- mockHandler,
54
- );
55
-
56
- expect(mockServer.registerTool).toHaveBeenCalled();
57
- const [name, options, handler] = mockServer.registerTool.mock.calls[0];
58
-
59
- expect(name).toContain('test_tool');
60
- expect(options.description).toBe('Test description');
61
-
62
- const result = await handler({});
63
- expect(result.content[0].text).toBe('success');
64
- });
65
-
66
- it('should block destructive tool in read-only mode', async () => {
67
- process.env.LIGHTDASH_TOOLS_SAFETY_MODE = SafetyMode.READ_ONLY;
68
- setStaticSafetyMode(SafetyMode.WRITE_DESTRUCTIVE);
69
-
70
- registerToolSafe(
71
- mockServer,
72
- 'delete_tool',
73
- {
74
- description: 'Delete something',
75
- inputSchema: {},
76
- annotations: WRITE_DESTRUCTIVE,
77
- },
78
- mockHandler,
79
- );
80
-
81
- const [, options, handler] = mockServer.registerTool.mock.calls[0];
82
-
83
- expect(options.description).toContain('[DISABLED in read-only mode]');
84
-
85
- const result = await handler({});
86
- expect(result.isError).toBe(true);
87
- expect(result.content[0].text).toContain('disabled in read-only mode');
88
- });
89
-
90
- it('should allow destructive tool in write-destructive mode', async () => {
91
- process.env.LIGHTDASH_TOOLS_SAFETY_MODE = SafetyMode.WRITE_DESTRUCTIVE;
92
- setStaticSafetyMode(SafetyMode.WRITE_DESTRUCTIVE);
93
-
94
- registerToolSafe(
95
- mockServer,
96
- 'delete_tool_2',
97
- {
98
- description: 'Delete something 2',
99
- inputSchema: {},
100
- annotations: WRITE_DESTRUCTIVE,
101
- },
102
- mockHandler,
103
- );
104
-
105
- const [, options, handler] = mockServer.registerTool.mock.calls[0];
106
-
107
- expect(options.description).toBe('Delete something 2');
108
-
109
- const result = await handler({});
110
- expect(result.content[0].text).toBe('success');
111
- });
112
-
113
- it('should reject invalid projectUuid before calling handler', async () => {
114
- registerToolSafe(
115
- mockServer,
116
- 'list_tool',
117
- {
118
- description: 'List something',
119
- inputSchema: {},
120
- annotations: READ_ONLY_DEFAULT,
121
- },
122
- mockHandler,
123
- );
124
-
125
- const [, , handler] = mockServer.registerTool.mock.calls[0];
126
- const result = await handler({ projectUuid: 'uuid?fields=name' });
127
-
128
- expect(mockHandler).not.toHaveBeenCalled();
129
- expect(result.isError).toBe(true);
130
- expect(result.content[0].text).toContain('Invalid resource ID');
131
- });
132
-
133
- describe('static filtering (safety-mode)', () => {
134
- it('should skip registration if tool is more permissive than binded mode', () => {
135
- setStaticSafetyMode(SafetyMode.READ_ONLY);
136
- mockServer.registerTool.mockClear();
137
-
138
- registerToolSafe(
139
- mockServer,
140
- 'destructive_tool_static',
141
- {
142
- description: 'Destructive',
143
- inputSchema: {},
144
- annotations: WRITE_DESTRUCTIVE,
145
- },
146
- mockHandler,
147
- );
148
-
149
- expect(mockServer.registerTool).not.toHaveBeenCalled();
150
- });
151
-
152
- it('should allow registration if tool matches binded mode', () => {
153
- setStaticSafetyMode(SafetyMode.READ_ONLY);
154
- mockServer.registerTool.mockClear();
155
-
156
- registerToolSafe(
157
- mockServer,
158
- 'readonly_tool_static',
159
- {
160
- description: 'Read-only',
161
- inputSchema: {},
162
- annotations: READ_ONLY_DEFAULT,
163
- },
164
- mockHandler,
165
- );
166
-
167
- expect(mockServer.registerTool).toHaveBeenCalled();
168
- });
169
-
170
- it('should allow everything if binded mode is write-destructive', () => {
171
- setStaticSafetyMode(SafetyMode.WRITE_DESTRUCTIVE);
172
- mockServer.registerTool.mockClear();
173
-
174
- registerToolSafe(
175
- mockServer,
176
- 'any_tool_static',
177
- {
178
- description: 'Any',
179
- inputSchema: {},
180
- annotations: WRITE_DESTRUCTIVE,
181
- },
182
- mockHandler,
183
- );
184
-
185
- expect(mockServer.registerTool).toHaveBeenCalled();
186
- });
187
- });
188
-
189
- describe('project UUID allowlist', () => {
190
- it('should allow calls when allowlist is empty (all projects permitted)', async () => {
191
- setStaticAllowedProjectUuids([]);
192
-
193
- registerToolSafe(
194
- mockServer,
195
- 'list_charts',
196
- { description: 'List charts', inputSchema: {}, annotations: READ_ONLY_DEFAULT },
197
- mockHandler,
198
- );
199
-
200
- const [, , handler] = mockServer.registerTool.mock.calls[0];
201
- const result = await handler({ projectUuid: 'any-uuid' });
202
- expect(result.isError).toBeUndefined();
203
- expect(result.content[0].text).toBe('success');
204
- });
205
-
206
- it('should allow calls for a singular projectUuid in the allowlist', async () => {
207
- setStaticAllowedProjectUuids(['uuid-allowed', 'uuid-other']);
208
-
209
- registerToolSafe(
210
- mockServer,
211
- 'list_charts_allowed',
212
- { description: 'List charts', inputSchema: {}, annotations: READ_ONLY_DEFAULT },
213
- mockHandler,
214
- );
215
-
216
- const [, , handler] = mockServer.registerTool.mock.calls[0];
217
- const result = await handler({ projectUuid: 'uuid-allowed' });
218
- expect(result.isError).toBeUndefined();
219
- expect(result.content[0].text).toBe('success');
220
- });
221
-
222
- it('should block calls for a singular projectUuid not in the allowlist', async () => {
223
- setStaticAllowedProjectUuids(['uuid-allowed']);
224
-
225
- registerToolSafe(
226
- mockServer,
227
- 'list_charts_blocked',
228
- { description: 'List charts', inputSchema: {}, annotations: READ_ONLY_DEFAULT },
229
- mockHandler,
230
- );
231
-
232
- const [, , handler] = mockServer.registerTool.mock.calls[0];
233
- const result = await handler({ projectUuid: 'uuid-denied' });
234
- expect(result.isError).toBe(true);
235
- expect(result.content[0].text).toContain('not in the list of allowed projects');
236
- expect(result.content[0].text).toContain('uuid-denied');
237
- });
238
-
239
- it('should allow calls with no projectUuid arg even when allowlist is set', async () => {
240
- setStaticAllowedProjectUuids(['uuid-allowed']);
241
-
242
- registerToolSafe(
243
- mockServer,
244
- 'list_projects_no_uuid',
245
- { description: 'List projects', inputSchema: {}, annotations: READ_ONLY_DEFAULT },
246
- mockHandler,
247
- );
248
-
249
- const [, , handler] = mockServer.registerTool.mock.calls[0];
250
- // No projectUuid in args → allowlist does not apply
251
- const result = await handler({});
252
- expect(result.isError).toBeUndefined();
253
- expect(result.content[0].text).toBe('success');
254
- });
255
-
256
- it('should allow when all projectUuids[] are in the allowlist', async () => {
257
- setStaticAllowedProjectUuids(['uuid-a', 'uuid-b']);
258
-
259
- registerToolSafe(
260
- mockServer,
261
- 'search_content_allowed',
262
- { description: 'Search content', inputSchema: {}, annotations: READ_ONLY_DEFAULT },
263
- mockHandler,
264
- );
265
-
266
- const [, , handler] = mockServer.registerTool.mock.calls[0];
267
- const result = await handler({ projectUuids: ['uuid-a', 'uuid-b'] });
268
- expect(result.isError).toBeUndefined();
269
- expect(result.content[0].text).toBe('success');
270
- });
271
-
272
- it('should block when any UUID in projectUuids[] is not in the allowlist', async () => {
273
- setStaticAllowedProjectUuids(['uuid-a']);
274
-
275
- registerToolSafe(
276
- mockServer,
277
- 'search_content_blocked',
278
- { description: 'Search content', inputSchema: {}, annotations: READ_ONLY_DEFAULT },
279
- mockHandler,
280
- );
281
-
282
- const [, , handler] = mockServer.registerTool.mock.calls[0];
283
- const result = await handler({ projectUuids: ['uuid-a', 'uuid-denied'] });
284
- expect(result.isError).toBe(true);
285
- expect(result.content[0].text).toContain('uuid-denied');
286
- expect(result.content[0].text).toContain('not in the list of allowed projects');
287
- });
288
-
289
- it('should block when all projectUuids[] are outside the allowlist', async () => {
290
- setStaticAllowedProjectUuids(['uuid-allowed']);
291
-
292
- registerToolSafe(
293
- mockServer,
294
- 'search_content_all_blocked',
295
- { description: 'Search content', inputSchema: {}, annotations: READ_ONLY_DEFAULT },
296
- mockHandler,
297
- );
298
-
299
- const [, , handler] = mockServer.registerTool.mock.calls[0];
300
- const result = await handler({ projectUuids: ['uuid-x', 'uuid-y'] });
301
- expect(result.isError).toBe(true);
302
- expect(result.content[0].text).toContain('not in the list of allowed projects');
303
- });
304
- });
305
-
306
- describe('dry-run mode', () => {
307
- it('should not affect read-only tools in dry-run mode', async () => {
308
- setDryRunMode(true);
309
-
310
- registerToolSafe(
311
- mockServer,
312
- 'list_things_dry',
313
- { description: 'List things', inputSchema: {}, annotations: READ_ONLY_DEFAULT },
314
- mockHandler,
315
- );
316
-
317
- const [, options, handler] = mockServer.registerTool.mock.calls[0];
318
- expect(options.description).not.toContain('[DRY-RUN]');
319
-
320
- const result = await handler({});
321
- expect(result.content[0].text).toBe('success');
322
- });
323
-
324
- it('should simulate write-idempotent tools in dry-run mode', async () => {
325
- setDryRunMode(true);
326
- process.env.LIGHTDASH_TOOLS_SAFETY_MODE = SafetyMode.WRITE_DESTRUCTIVE;
327
-
328
- registerToolSafe(
329
- mockServer,
330
- 'upsert_thing_dry',
331
- { description: 'Upsert thing', inputSchema: {}, annotations: WRITE_IDEMPOTENT },
332
- mockHandler,
333
- );
334
-
335
- const [, options, handler] = mockServer.registerTool.mock.calls[0];
336
- expect(options.description).toContain('[DRY-RUN]');
337
-
338
- const result = await handler({ projectUuid: 'uuid-x', slug: 'my-chart' });
339
- expect(result.isError).toBeUndefined();
340
- expect(result.content[0].text).toContain('[DRY-RUN]');
341
- expect(result.content[0].text).toContain('No changes were made');
342
- // Verify the underlying handler was NOT called
343
- expect(mockHandler).not.toHaveBeenCalled();
344
- });
345
-
346
- it('should simulate destructive tools in dry-run mode', async () => {
347
- setDryRunMode(true);
348
- process.env.LIGHTDASH_TOOLS_SAFETY_MODE = SafetyMode.WRITE_DESTRUCTIVE;
349
-
350
- registerToolSafe(
351
- mockServer,
352
- 'delete_thing_dry',
353
- { description: 'Delete thing', inputSchema: {}, annotations: WRITE_DESTRUCTIVE },
354
- mockHandler,
355
- );
356
-
357
- const [, options, handler] = mockServer.registerTool.mock.calls[0];
358
- expect(options.description).toContain('[DRY-RUN]');
359
-
360
- const result = await handler({ projectUuid: 'uuid-x' });
361
- expect(result.content[0].text).toContain('No changes were made');
362
- expect(mockHandler).not.toHaveBeenCalled();
363
- });
364
- });
365
- });
@@ -1,274 +0,0 @@
1
- /**
2
- * Shared types and helpers for MCP tool registration.
3
- *
4
- * Guardrail layers applied by registerToolSafe (outer → inner):
5
- * 1. Audit log wrapper — captures timing and outcome for every call.
6
- * 2. Project allowlist — rejects calls targeting disallowed project UUIDs at runtime.
7
- * 3. Input validation — rejects invalid resource IDs (control chars, ?, #, %, path traversal).
8
- * 4. Dry-run wrapper — simulates writes without executing them (registration-time).
9
- * 5. Safety-mode wrapper — disables tools that exceed the configured safety level.
10
- * 6. Raw handler — the actual tool implementation.
11
- */
12
-
13
- import type { LightdashClient } from '@lightdash-tools/client';
14
- import {
15
- isAllowed,
16
- areAllProjectsAllowed,
17
- extractProjectUuids,
18
- READ_ONLY_DEFAULT,
19
- logAuditEntry,
20
- getSessionId,
21
- validateResourceId,
22
- } from '@lightdash-tools/common';
23
- import type { ToolAnnotations } from '@lightdash-tools/common';
24
- import type { z } from 'zod';
25
- import { toMcpErrorMessage } from '../errors.js';
26
- import {
27
- getStaticSafetyMode,
28
- getSafetyMode,
29
- getAllowedProjectUuids,
30
- isDryRunMode,
31
- } from '../config.js';
32
-
33
- /** Prefix for all MCP tool names (disambiguation when multiple servers are connected). */
34
- export const TOOL_PREFIX = 'ldt__';
35
-
36
- export type TextContent = {
37
- content: Array<{ type: 'text'; text: string }>;
38
- isError?: boolean;
39
- };
40
-
41
- /** Tool handler type used to avoid deep instantiation with SDK/Zod. Accepts (args, extra) for SDK compatibility. */
42
- export type ToolHandler = (args: unknown, extra?: unknown) => Promise<TextContent>;
43
-
44
- /** Options for registerTool; inputSchema typed as ZodRawShapeCompat for SDK compatibility. Pass annotations explicitly (e.g. READ_ONLY_DEFAULT or WRITE_IDEMPOTENT) for visibility. */
45
- export type ToolOptions = {
46
- description: string;
47
- inputSchema: Record<string, z.ZodTypeAny>;
48
- title?: string;
49
- annotations?: ToolAnnotations;
50
- };
51
-
52
- // Re-export presets for convenience and backward compatibility in tools
53
- export { READ_ONLY_DEFAULT, WRITE_IDEMPOTENT, WRITE_DESTRUCTIVE } from '@lightdash-tools/common';
54
-
55
- /** Internal default for mergeAnnotations; READ_ONLY_DEFAULT is the exported preset. */
56
- const DEFAULT_ANNOTATIONS: ToolAnnotations = READ_ONLY_DEFAULT;
57
-
58
- type RegisterToolFn = (name: string, options: ToolOptions, handler: ToolHandler) => void;
59
-
60
- /** Merges per-tool annotations with defaults; per-tool values win. */
61
- function mergeAnnotations(overrides?: ToolAnnotations): ToolAnnotations {
62
- return { ...DEFAULT_ANNOTATIONS, ...overrides };
63
- }
64
-
65
- /**
66
- * Internal marker attached to responses produced by a guardrail (safety-mode block,
67
- * dry-run simulation, or project-allowlist denial). The audit wrapper reads this flag
68
- * to set status = 'blocked', then strips it before returning to the MCP client.
69
- */
70
- type BlockedContent = TextContent & { readonly _lightdashBlocked: true };
71
-
72
- function isGuardrailBlocked(result: TextContent): result is BlockedContent {
73
- return (
74
- '_lightdashBlocked' in result &&
75
- (result as Record<string, unknown>)['_lightdashBlocked'] === true
76
- );
77
- }
78
-
79
- /**
80
- * Registers a tool with prefix and annotations, applying all guardrail layers.
81
- * shortName is prefixed to become TOOL_PREFIX + shortName.
82
- * Pass annotations explicitly (e.g. READ_ONLY_DEFAULT, WRITE_IDEMPOTENT, or WRITE_DESTRUCTIVE).
83
- *
84
- * CLI flag --allowed-projects always takes priority over LIGHTDASH_TOOLS_ALLOWED_PROJECTS.
85
- */
86
- export function registerToolSafe(
87
- server: unknown,
88
- shortName: string,
89
- options: ToolOptions,
90
- handler: ToolHandler,
91
- ): void {
92
- const name = TOOL_PREFIX + shortName;
93
- const annotations = mergeAnnotations(options.annotations);
94
-
95
- // ── Static Filtering ──────────────────────────────────────────────────────
96
- // Skip registration entirely if the tool exceeds the static safety mode.
97
- const staticMode = getStaticSafetyMode();
98
- if (staticMode && !isAllowed(staticMode, annotations)) {
99
- return;
100
- }
101
-
102
- // ── Safety-mode wrapper ───────────────────────────────────────────────────
103
- // Tool is registered but calls are rejected at runtime when the dynamic mode
104
- // does not permit the operation.
105
- const mode = getSafetyMode();
106
- const isToolAllowed = isAllowed(mode, annotations);
107
- const isReadOnly = !!annotations.readOnlyHint;
108
-
109
- let finalHandler: ToolHandler = handler;
110
- let finalDescription = options.description;
111
-
112
- if (!isToolAllowed) {
113
- finalDescription = `[DISABLED in ${mode} mode] ${options.description}`;
114
- finalHandler = async (): Promise<BlockedContent> => ({
115
- content: [
116
- {
117
- type: 'text',
118
- text: `Error: Tool '${name}' is disabled in ${mode} mode. To enable it, change LIGHTDASH_TOOLS_SAFETY_MODE.`,
119
- },
120
- ],
121
- isError: true,
122
- _lightdashBlocked: true,
123
- });
124
- } else if (isDryRunMode() && !isReadOnly) {
125
- // ── Dry-run wrapper ─────────────────────────────────────────────────────
126
- // Write operations are simulated; no API calls are made.
127
- finalDescription = `[DRY-RUN] ${options.description}`;
128
- finalHandler = async (args): Promise<BlockedContent> => ({
129
- content: [
130
- {
131
- type: 'text',
132
- text: `[DRY-RUN] Tool '${name}' would be called with: ${JSON.stringify(args, null, 2)}. No changes were made.`,
133
- },
134
- ],
135
- _lightdashBlocked: true,
136
- });
137
- }
138
-
139
- // ── Input validation wrapper ─────────────────────────────────────────────
140
- // Validate resource IDs (projectUuid, slug, etc.) before handler.
141
- const validatedInner = finalHandler;
142
- finalHandler = async (args, extra): Promise<TextContent> => {
143
- const projectUuids = extractProjectUuids(args);
144
- for (const uuid of projectUuids) {
145
- try {
146
- validateResourceId(uuid);
147
- } catch (err) {
148
- return {
149
- content: [
150
- {
151
- type: 'text',
152
- text: `Error: Invalid resource ID: ${err instanceof Error ? err.message : String(err)}`,
153
- },
154
- ],
155
- isError: true,
156
- _lightdashBlocked: true,
157
- } as BlockedContent;
158
- }
159
- }
160
- const a = args as Record<string, unknown>;
161
- if (typeof a?.slug === 'string') {
162
- try {
163
- validateResourceId(a.slug);
164
- } catch (err) {
165
- return {
166
- content: [
167
- {
168
- type: 'text',
169
- text: `Error: Invalid slug: ${err instanceof Error ? err.message : String(err)}`,
170
- },
171
- ],
172
- isError: true,
173
- _lightdashBlocked: true,
174
- } as BlockedContent;
175
- }
176
- }
177
- return validatedInner(args, extra);
178
- };
179
-
180
- // ── Project allowlist wrapper ─────────────────────────────────────────────
181
- // Reject calls targeting project UUIDs not in the configured allowlist.
182
- // Covers both singular (projectUuid) and plural (projectUuids[]) arg shapes.
183
- // CLI --allowed-projects takes priority over LIGHTDASH_TOOLS_ALLOWED_PROJECTS.
184
- const allowedProjects = getAllowedProjectUuids();
185
- if (allowedProjects.length > 0) {
186
- const innerHandler = finalHandler;
187
- finalHandler = async (args, extra): Promise<TextContent> => {
188
- const projectUuids = extractProjectUuids(args);
189
- const deniedUuids = projectUuids.filter(
190
- (uuid) => !areAllProjectsAllowed(allowedProjects, [uuid]),
191
- );
192
- if (deniedUuids.length > 0) {
193
- return {
194
- content: [
195
- {
196
- type: 'text',
197
- text: `Error: Project(s) [${deniedUuids.join(', ')}] are not in the list of allowed projects. Allowed: [${allowedProjects.join(', ')}].`,
198
- },
199
- ],
200
- isError: true,
201
- _lightdashBlocked: true,
202
- } as BlockedContent;
203
- }
204
- return innerHandler(args, extra);
205
- };
206
- }
207
-
208
- // ── Audit log wrapper ─────────────────────────────────────────────────────
209
- // Outermost layer: records timing and outcome for every call.
210
- const auditedInner = finalHandler;
211
- finalHandler = async (args, extra): Promise<TextContent> => {
212
- const start = Date.now();
213
- const projectUuids = extractProjectUuids(args);
214
- let status: 'success' | 'error' | 'blocked' = 'success';
215
- let result: TextContent;
216
-
217
- try {
218
- result = await auditedInner(args, extra);
219
- if (isGuardrailBlocked(result)) {
220
- status = 'blocked';
221
- } else if (result.isError) {
222
- status = 'error';
223
- }
224
- } catch (err) {
225
- status = 'error';
226
- logAuditEntry({
227
- timestamp: new Date().toISOString(),
228
- sessionId: getSessionId(),
229
- tool: name,
230
- projectUuids: projectUuids.length > 0 ? projectUuids : undefined,
231
- status,
232
- durationMs: Date.now() - start,
233
- });
234
- throw err;
235
- }
236
-
237
- logAuditEntry({
238
- timestamp: new Date().toISOString(),
239
- sessionId: getSessionId(),
240
- tool: name,
241
- projectUuids: projectUuids.length > 0 ? projectUuids : undefined,
242
- status,
243
- durationMs: Date.now() - start,
244
- });
245
-
246
- // Strip the internal marker before returning to the MCP client.
247
- const { content, isError } = result;
248
- return { content, isError };
249
- };
250
-
251
- const mergedOptions: ToolOptions = {
252
- ...options,
253
- description: finalDescription,
254
- title: options.title ?? options.annotations?.title,
255
- annotations,
256
- };
257
- (server as { registerTool: RegisterToolFn }).registerTool(name, mergedOptions, finalHandler);
258
- }
259
-
260
- export function wrapTool<T>(
261
- client: LightdashClient,
262
- fn: (client: LightdashClient) => (args: T) => Promise<TextContent>,
263
- ): ToolHandler {
264
- const handler = fn(client);
265
- return async (args: unknown, extra?: unknown) => {
266
- void extra;
267
- try {
268
- return await handler(args as T);
269
- } catch (err) {
270
- const text = toMcpErrorMessage(err);
271
- return { content: [{ type: 'text', text }], isError: true };
272
- }
273
- };
274
- }