plugin-elastic-report 0.7.0 → 0.9.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 (70) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/{ai → dist/ai}/skills/elastic-report/SKILLS.md +52 -34
  6. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  7. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +2 -1
  10. package/dist/locale/en-US.json +213 -198
  11. package/dist/locale/vi-VN.json +213 -198
  12. package/dist/locale/zh-CN.json +213 -198
  13. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  14. package/dist/server/mcp/ElasticReportToolCatalog.js +6 -4
  15. package/dist/server/plugin.js +4 -4
  16. package/dist/server/report-block-tools.js +340 -0
  17. package/dist/server/services/ElasticReportService.js +12 -6
  18. package/dist/shared/constants.js +9 -0
  19. package/package.json +2 -3
  20. package/server.d.ts +2 -2
  21. package/server.js +1 -1
  22. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  23. package/src/client/index.tsx +34 -34
  24. package/src/client/workflow-instructions.tsx +44 -44
  25. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -791
  26. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -178
  27. package/src/client-v2/api.ts +320 -320
  28. package/src/client-v2/bus/DashboardFilterBus.ts +212 -212
  29. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -652
  30. package/src/client-v2/components/ElasticFilterBar.tsx +372 -372
  31. package/src/client-v2/components/ElasticKqlInput.tsx +421 -421
  32. package/src/client-v2/components/ElasticReportBlock.tsx +306 -306
  33. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -1257
  34. package/src/client-v2/components/HighlightText.tsx +50 -50
  35. package/src/client-v2/components/ReportSelect.tsx +85 -85
  36. package/src/client-v2/index.tsx +14 -14
  37. package/src/client-v2/locale.ts +23 -23
  38. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -115
  39. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -118
  40. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1453
  41. package/src/client-v2/plugin.tsx +107 -72
  42. package/src/client-v2/report-destination.tsx +126 -0
  43. package/src/client-v2/utils/kqlAutocomplete.ts +861 -861
  44. package/src/client-v2/workflow/instructions.tsx +149 -149
  45. package/src/index.ts +11 -11
  46. package/src/locale/en-US.json +213 -198
  47. package/src/locale/vi-VN.json +213 -198
  48. package/src/locale/zh-CN.json +213 -198
  49. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  50. package/src/server/__tests__/query-compiler.test.ts +620 -620
  51. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -645
  52. package/src/server/acl-guard.ts +194 -194
  53. package/src/server/collections/es-report-data-views.ts +64 -64
  54. package/src/server/collections/es-reports.ts +80 -80
  55. package/src/server/index.ts +15 -15
  56. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  57. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -663
  58. package/src/server/plugin.ts +599 -599
  59. package/src/server/report-block-tools.ts +400 -0
  60. package/src/server/services/ElasticReportService.ts +494 -486
  61. package/src/server/services/ElasticsearchConnectionService.ts +728 -728
  62. package/src/server/services/ReportExportService.ts +282 -282
  63. package/src/server/services/ReportQueryCompiler.ts +1552 -1552
  64. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -124
  65. package/src/shared/constants.ts +39 -36
  66. package/src/shared/types.ts +272 -272
  67. package/dist/client-v2/851.142c93fc6d666b28.js +0 -10
  68. package/dist/client-v2/877.f4095a3dbcadf98f.js +0 -10
  69. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  70. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,599 +1,599 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import { resolve } from 'path';
11
- import type { Context, Next } from '@nocobase/actions';
12
- import type WorkflowPlugin from '@nocobase/plugin-workflow';
13
- import { Plugin, type InstallOptions } from '@nocobase/server';
14
- import {
15
- ACL_SNIPPET,
16
- DATA_VIEWS_COLLECTION,
17
- MCP_RELATIVE_PATH,
18
- MCP_RESOURCE_NAME,
19
- MCP_SERVER_NAME,
20
- REPORTS_COLLECTION,
21
- SERVICE_RESOURCE,
22
- WORKFLOW_INSTRUCTION_TYPE,
23
- } from '../shared/constants';
24
- import type { ExportFormat, ID, ReportRuntimeOverrides } from '../shared/types';
25
- import {
26
- assertCanAccessDataView,
27
- assertCanAccessReport,
28
- assertCanManageReports,
29
- canAccessReport,
30
- normalizeRoleList,
31
- } from './acl-guard';
32
- import { ElasticReportMcpServer } from './mcp/ElasticReportMcpServer';
33
- import { createElasticReportToolCatalog, type ElasticReportToolDefinition } from './mcp/ElasticReportToolCatalog';
34
- import { ElasticsearchConnectionService } from './services/ElasticsearchConnectionService';
35
- import { ElasticReportService, extractCurrentUserId, extractServerUserContext } from './services/ElasticReportService';
36
- import { ReportExportService } from './services/ReportExportService';
37
- import { ElasticReportQueryInstruction } from './workflow/ElasticReportQueryInstruction';
38
-
39
- interface AIToolsManagerLike {
40
- registerTools: (
41
- tools: Array<{
42
- scope: 'CUSTOM' | 'GENERAL' | 'SPECIFIED';
43
- defaultPermission: 'ALLOW' | 'ASK';
44
- execution: 'backend' | 'frontend';
45
- introduction: { title: string; about: string };
46
- definition: { name: string; description: string; schema: Record<string, unknown> };
47
- invoke: (ctx: Context, args: Record<string, unknown>) => Promise<unknown>;
48
- }>,
49
- ) => void;
50
- }
51
-
52
- interface AIMcpManagerLike {
53
- registerMCP: (registration: Record<string, unknown>) => Promise<void>;
54
- }
55
-
56
- function isRecord(value: unknown): value is Record<string, unknown> {
57
- return typeof value === 'object' && value !== null && !Array.isArray(value);
58
- }
59
-
60
- function getActionPayload(ctx: Context): Record<string, unknown> {
61
- const query = isRecord(ctx.request?.query) ? ctx.request.query : {};
62
- const actionParams = isRecord(ctx.action?.params) ? ctx.action.params : {};
63
- const body = isRecord(ctx.request?.body) ? ctx.request.body : {};
64
- const paramValues = isRecord(actionParams.values) ? actionParams.values : {};
65
- return {
66
- ...query,
67
- ...actionParams,
68
- ...body,
69
- ...paramValues,
70
- };
71
- }
72
-
73
- function parseIdParam(value: unknown, label: string): ID {
74
- if (typeof value === 'number' && Number.isFinite(value)) return value;
75
- if (typeof value === 'string' && value.trim()) return value.trim();
76
- const err = new Error(`${label} is required`) as Error & { status?: number };
77
- err.status = 400;
78
- throw err;
79
- }
80
-
81
- function parseOverridesParam(raw: unknown): ReportRuntimeOverrides | undefined {
82
- if (isRecord(raw)) {
83
- return raw as ReportRuntimeOverrides;
84
- }
85
- if (typeof raw === 'string' && raw.trim()) {
86
- try {
87
- const parsed = JSON.parse(raw);
88
- return isRecord(parsed) ? (parsed as ReportRuntimeOverrides) : undefined;
89
- } catch {
90
- return undefined;
91
- }
92
- }
93
- return undefined;
94
- }
95
-
96
- export class PluginElasticReportServer extends Plugin {
97
- public connectionService!: ElasticsearchConnectionService;
98
- public reportService!: ElasticReportService;
99
- public exportService!: ReportExportService;
100
- public mcpServer!: ElasticReportMcpServer;
101
- private toolsCatalog: ElasticReportToolDefinition[] = [];
102
- private readonly schemaCollections = [DATA_VIEWS_COLLECTION, REPORTS_COLLECTION];
103
-
104
- async beforeLoad() {
105
- await this.db.import({
106
- directory: resolve(__dirname, 'collections'),
107
- });
108
- this.connectionService = new ElasticsearchConnectionService(this.app);
109
- this.reportService = new ElasticReportService(this.app, this.connectionService);
110
- this.exportService = new ReportExportService(this.connectionService, this.reportService);
111
- this.toolsCatalog = createElasticReportToolCatalog(this.app, this.reportService);
112
- this.mcpServer = new ElasticReportMcpServer({
113
- version: this.options?.version || '0.7.0',
114
- tools: this.toolsCatalog,
115
- logger: this.app.logger,
116
- });
117
- }
118
-
119
- async load() {
120
- this.registerServiceResource();
121
- this.registerMcpEndpoint();
122
- this.registerAclRules();
123
- this.registerWorkflowInstructions();
124
- this.registerAITools();
125
- await this.registerPluginMcpClientEntry();
126
-
127
- this.app.on('beforeStop', async () => {
128
- await this.connectionService?.close();
129
- });
130
- }
131
-
132
- private registerWorkflowInstructions() {
133
- const workflow = this.app.pm.get('workflow') as WorkflowPlugin | undefined;
134
- if (!workflow || typeof workflow.registerInstruction !== 'function') {
135
- return;
136
- }
137
- workflow.registerInstruction(
138
- WORKFLOW_INSTRUCTION_TYPE,
139
- new ElasticReportQueryInstruction(workflow, this.reportService),
140
- );
141
- }
142
-
143
- async install(_options?: InstallOptions) {
144
- await this.ensureSchema();
145
- }
146
-
147
- async upgrade() {
148
- await this.ensureSchema();
149
- }
150
-
151
- private getApiBasePath(): string {
152
- const rawPrefix = this.app.resourcer?.options?.prefix ?? process.env.API_BASE_PATH ?? '/api';
153
- const cleaned = rawPrefix.replace(/\/+/g, '/').replace(/\/$/, '');
154
- return cleaned;
155
- }
156
-
157
- private getMcpEndpointPath(): string {
158
- return `${this.getApiBasePath()}${MCP_RELATIVE_PATH}`;
159
- }
160
-
161
- private resolveInternalMcpUrl(): string {
162
- const port = process.env.APP_PORT || '13000';
163
- const host = process.env.ELASTIC_REPORT_MCP_INTERNAL_HOST || `http://127.0.0.1:${port}`;
164
- return `${host.replace(/\/$/, '')}${this.getMcpEndpointPath()}`;
165
- }
166
-
167
- private registerServiceResource() {
168
- this.app.resourceManager.define({
169
- name: SERVICE_RESOURCE,
170
- actions: {
171
- listConnections: async (ctx: Context, next: Next) => {
172
- assertCanManageReports(this.app, ctx);
173
- ctx.body = await this.reportService.listConnections();
174
- await next();
175
- },
176
-
177
- testConnection: async (ctx: Context, next: Next) => {
178
- assertCanManageReports(this.app, ctx);
179
- const payload = getActionPayload(ctx);
180
- const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
181
- if (!dataSourceKey) {
182
- ctx.throw(400, 'dataSourceKey is required');
183
- }
184
- const indexPattern =
185
- typeof payload.indexPattern === 'string' && payload.indexPattern.trim() ? payload.indexPattern.trim() : '*';
186
- try {
187
- ctx.body = await this.reportService.testConnection(dataSourceKey, indexPattern);
188
- } catch (error) {
189
- ctx.throw(400, error instanceof Error ? error.message : String(error));
190
- }
191
- await next();
192
- },
193
-
194
- listRoles: async (ctx: Context, next: Next) => {
195
- assertCanManageReports(this.app, ctx);
196
- ctx.body = await this.reportService.listAvailableRoles();
197
- await next();
198
- },
199
-
200
- listIndices: async (ctx: Context, next: Next) => {
201
- assertCanManageReports(this.app, ctx);
202
- const payload = getActionPayload(ctx);
203
- const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
204
- if (!dataSourceKey) {
205
- ctx.throw(400, 'dataSourceKey is required');
206
- }
207
- const indexPattern =
208
- typeof payload.indexPattern === 'string' && payload.indexPattern.trim() ? payload.indexPattern.trim() : '*';
209
- try {
210
- ctx.body = await this.reportService.listIndices(dataSourceKey, indexPattern);
211
- } catch (error) {
212
- ctx.throw(400, error instanceof Error ? error.message : String(error));
213
- }
214
- await next();
215
- },
216
-
217
- inspectFields: async (ctx: Context, next: Next) => {
218
- const payload = getActionPayload(ctx);
219
- try {
220
- if (payload.dataViewId !== undefined && payload.dataViewId !== null && String(payload.dataViewId).trim()) {
221
- const dvId = parseIdParam(payload.dataViewId, 'dataViewId');
222
- const refresh = payload.refresh === true || payload.refresh === 'true';
223
- if (refresh) {
224
- assertCanManageReports(this.app, ctx);
225
- } else {
226
- const dv = await this.reportService.getDataView(dvId);
227
- assertCanAccessDataView(this.app, ctx, dv);
228
- }
229
- ctx.body = await this.reportService.inspectDataViewFields(dvId, refresh);
230
- } else {
231
- assertCanManageReports(this.app, ctx);
232
- const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
233
- const indexPattern = typeof payload.indexPattern === 'string' ? payload.indexPattern.trim() : '';
234
- if (!dataSourceKey || !indexPattern) {
235
- ctx.throw(400, 'Either dataViewId or (dataSourceKey + indexPattern) is required');
236
- }
237
- const fields = await this.reportService.inspectFieldsBySource(dataSourceKey, indexPattern);
238
- ctx.body = { fields };
239
- }
240
- } catch (error) {
241
- const status = (error as { status?: number } | undefined)?.status ?? 400;
242
- ctx.throw(status, error instanceof Error ? error.message : String(error));
243
- }
244
- await next();
245
- },
246
-
247
- upsertDataView: async (ctx: Context, next: Next) => {
248
- assertCanManageReports(this.app, ctx);
249
- const payload = getActionPayload(ctx);
250
- try {
251
- ctx.body = await this.reportService.upsertDataView(
252
- {
253
- ...(payload.id !== undefined && payload.id !== null && String(payload.id).trim() !== ''
254
- ? { id: parseIdParam(payload.id, 'id') }
255
- : {}),
256
- title: typeof payload.title === 'string' ? payload.title : '',
257
- dataSourceKey: typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey : '',
258
- indexPattern: typeof payload.indexPattern === 'string' ? payload.indexPattern : '',
259
- timeField: typeof payload.timeField === 'string' ? payload.timeField : null,
260
- description: typeof payload.description === 'string' ? payload.description : null,
261
- ...(payload.allowedRoles !== undefined
262
- ? { allowedRoles: normalizeRoleList(payload.allowedRoles) }
263
- : {}),
264
- },
265
- extractCurrentUserId(ctx),
266
- );
267
- } catch (error) {
268
- const status = (error as { status?: number } | undefined)?.status ?? 400;
269
- ctx.throw(status, error instanceof Error ? error.message : String(error));
270
- }
271
- await next();
272
- },
273
-
274
- previewReport: async (ctx: Context, next: Next) => {
275
- assertCanManageReports(this.app, ctx);
276
- const payload = getActionPayload(ctx);
277
- try {
278
- const dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
279
- ctx.body = await this.reportService.previewReport({
280
- dataViewId,
281
- spec: payload.spec,
282
- overrides: parseOverridesParam(payload.overrides),
283
- userContext: extractServerUserContext(ctx),
284
- });
285
- } catch (error) {
286
- const status = (error as { status?: number } | undefined)?.status ?? 400;
287
- ctx.throw(status, error instanceof Error ? error.message : String(error));
288
- }
289
- await next();
290
- },
291
-
292
- saveReport: async (ctx: Context, next: Next) => {
293
- assertCanManageReports(this.app, ctx);
294
- const payload = getActionPayload(ctx);
295
- try {
296
- ctx.body = await this.reportService.saveReport(
297
- {
298
- ...(payload.id !== undefined && payload.id !== null && String(payload.id).trim() !== ''
299
- ? { id: parseIdParam(payload.id, 'id') }
300
- : {}),
301
- title: typeof payload.title === 'string' ? payload.title : '',
302
- description: typeof payload.description === 'string' ? payload.description : null,
303
- dataViewId: parseIdParam(payload.dataViewId, 'dataViewId'),
304
- spec: payload.spec,
305
- published: payload.published !== false,
306
- ...(payload.allowedRoles !== undefined
307
- ? { allowedRoles: normalizeRoleList(payload.allowedRoles) }
308
- : {}),
309
- },
310
- extractCurrentUserId(ctx),
311
- );
312
- } catch (error) {
313
- const status = (error as { status?: number } | undefined)?.status ?? 400;
314
- ctx.throw(status, error instanceof Error ? error.message : String(error));
315
- }
316
- await next();
317
- },
318
-
319
- listPublishedReports: async (ctx: Context, next: Next) => {
320
- const payload = getActionPayload(ctx);
321
- const search = typeof payload.search === 'string' ? payload.search : undefined;
322
- const publishedReports = await this.reportService.listReports({
323
- publishedOnly: true,
324
- search,
325
- });
326
- ctx.body = publishedReports.filter((report) => canAccessReport(this.app, ctx, report, report.dataView));
327
- await next();
328
- },
329
-
330
- getReportMeta: async (ctx: Context, next: Next) => {
331
- const payload = getActionPayload(ctx);
332
- const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
333
- try {
334
- const reportId = parseIdParam(rawId, 'reportId');
335
- const report = await this.reportService.getReport(reportId);
336
- const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
337
- assertCanAccessReport(this.app, ctx, report, dataView);
338
- ctx.body = { report, dataView, fields };
339
- } catch (error) {
340
- const status = (error as { status?: number } | undefined)?.status ?? 400;
341
- ctx.throw(status, error instanceof Error ? error.message : String(error));
342
- }
343
- await next();
344
- },
345
-
346
- runReport: async (ctx: Context, next: Next) => {
347
- const payload = getActionPayload(ctx);
348
- const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
349
- try {
350
- const reportId = parseIdParam(rawId, 'reportId');
351
- const report = await this.reportService.getReport(reportId);
352
- const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
353
- assertCanAccessReport(this.app, ctx, report, dataView);
354
- ctx.body = await this.reportService.runSavedReport({
355
- reportId,
356
- overrides: parseOverridesParam(payload.overrides),
357
- requirePublished: false,
358
- userContext: extractServerUserContext(ctx),
359
- });
360
- } catch (error) {
361
- const status = (error as { status?: number } | undefined)?.status ?? 400;
362
- ctx.throw(status, error instanceof Error ? error.message : String(error));
363
- }
364
- await next();
365
- },
366
-
367
- inspectTopValues: async (ctx: Context, next: Next) => {
368
- const payload = getActionPayload(ctx);
369
- try {
370
- const field = typeof payload.field === 'string' ? payload.field.trim() : '';
371
- if (!field) {
372
- ctx.throw(400, 'field is required');
373
- }
374
- let dataViewId: ID;
375
- let reportId: ID | undefined;
376
- if (payload.reportId !== undefined && payload.reportId !== null && String(payload.reportId).trim() !== '') {
377
- reportId = parseIdParam(payload.reportId, 'reportId');
378
- const report = await this.reportService.getReport(reportId);
379
- const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
380
- assertCanAccessReport(this.app, ctx, report, dataView);
381
- dataViewId = report.dataViewId;
382
- } else {
383
- dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
384
- const dataView = await this.reportService.getDataView(dataViewId);
385
- assertCanAccessDataView(this.app, ctx, dataView);
386
- }
387
-
388
- ctx.body = await this.reportService.inspectFieldTopValues({
389
- dataViewId,
390
- ...(reportId !== undefined ? { reportId } : {}),
391
- field,
392
- size: typeof payload.size === 'number' ? payload.size : Number(payload.size) || 10,
393
- overrides: parseOverridesParam(payload.overrides),
394
- userContext: extractServerUserContext(ctx),
395
- });
396
- } catch (error) {
397
- const status = (error as { status?: number } | undefined)?.status ?? 400;
398
- ctx.throw(status, error instanceof Error ? error.message : String(error));
399
- }
400
- await next();
401
- },
402
-
403
- exportReport: async (ctx: Context, next: Next) => {
404
- const payload = getActionPayload(ctx);
405
- const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
406
- try {
407
- const reportId = parseIdParam(rawId, 'reportId');
408
- const report = await this.reportService.getReport(reportId);
409
- const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
410
- assertCanAccessReport(this.app, ctx, report, dataView);
411
-
412
- const format: ExportFormat = payload.format === 'ndjson' ? 'ndjson' : 'csv';
413
- const columns = Array.isArray(payload.columns)
414
- ? payload.columns.filter((c): c is string => typeof c === 'string' && Boolean(c.trim()))
415
- : typeof payload.columns === 'string' && payload.columns.trim()
416
- ? payload.columns
417
- .split(',')
418
- .map((c) => c.trim())
419
- .filter(Boolean)
420
- : undefined;
421
- const maxRows =
422
- typeof payload.maxRows === 'number'
423
- ? payload.maxRows
424
- : payload.maxRows !== undefined
425
- ? Number(payload.maxRows)
426
- : undefined;
427
-
428
- const { stream, filename, contentType } = await this.exportService.createExportStream({
429
- reportId,
430
- format,
431
- overrides: parseOverridesParam(payload.overrides),
432
- ...(columns ? { columns } : {}),
433
- ...(maxRows !== undefined && Number.isFinite(maxRows) ? { maxRows } : {}),
434
- userContext: extractServerUserContext(ctx),
435
- });
436
-
437
- ctx.withoutDataWrapping = true;
438
- ctx.status = 200;
439
- ctx.type = contentType;
440
- ctx.set('Content-Disposition', `attachment; filename="${filename}"`);
441
- ctx.body = stream;
442
- } catch (error) {
443
- const status = (error as { status?: number } | undefined)?.status ?? 400;
444
- ctx.throw(status, error instanceof Error ? error.message : String(error));
445
- }
446
- await next();
447
- },
448
-
449
- getMcpInfo: async (ctx: Context, next: Next) => {
450
- ctx.body = {
451
- serverName: MCP_SERVER_NAME,
452
- endpointPath: this.getMcpEndpointPath(),
453
- internalUrl: this.resolveInternalMcpUrl(),
454
- useUserContext: true,
455
- tools: this.mcpServer.getToolsMetadata(),
456
- };
457
- await next();
458
- },
459
- },
460
- });
461
- }
462
-
463
- private registerMcpEndpoint() {
464
- const mcpActionHandler = async (ctx: Context) => {
465
- await this.mcpServer.handleRequest(ctx);
466
- };
467
-
468
- this.app.resourceManager.define({
469
- name: MCP_RESOURCE_NAME,
470
- actions: {
471
- list: mcpActionHandler,
472
- create: mcpActionHandler,
473
- },
474
- only: ['list', 'create'],
475
- });
476
- }
477
-
478
- private registerAclRules() {
479
- // Viewers on pages can list published reports, inspect report metadata/top-values, run, and export published reports.
480
- this.app.acl.allow(
481
- SERVICE_RESOURCE,
482
- ['listPublishedReports', 'getReportMeta', 'runReport', 'inspectTopValues', 'exportReport'],
483
- 'loggedIn',
484
- );
485
- // Dedicated MCP endpoint requires authentication; tool-level ACL enforces read vs manage permissions.
486
- this.app.acl.allow(MCP_RESOURCE_NAME, '*', 'loggedIn');
487
-
488
- // Full studio & data-view management is grouped under the plugin settings snippet.
489
- this.app.acl.registerSnippet({
490
- name: ACL_SNIPPET,
491
- actions: [
492
- `${DATA_VIEWS_COLLECTION}:list`,
493
- `${DATA_VIEWS_COLLECTION}:get`,
494
- `${DATA_VIEWS_COLLECTION}:create`,
495
- `${DATA_VIEWS_COLLECTION}:update`,
496
- `${DATA_VIEWS_COLLECTION}:destroy`,
497
- `${REPORTS_COLLECTION}:list`,
498
- `${REPORTS_COLLECTION}:get`,
499
- `${REPORTS_COLLECTION}:create`,
500
- `${REPORTS_COLLECTION}:update`,
501
- `${REPORTS_COLLECTION}:destroy`,
502
- `${SERVICE_RESOURCE}:*`,
503
- ],
504
- });
505
- }
506
-
507
- private registerAITools() {
508
- const toolsManager = (this.app as unknown as { aiManager?: { toolsManager?: AIToolsManagerLike } }).aiManager
509
- ?.toolsManager;
510
- if (!toolsManager) {
511
- this.app.logger?.info?.(
512
- '[plugin-elastic-report] aiManager.toolsManager is not present; skipping direct AI tool registration',
513
- );
514
- return;
515
- }
516
-
517
- toolsManager.registerTools(
518
- this.toolsCatalog.map((tool) => ({
519
- scope: 'CUSTOM',
520
- defaultPermission: tool.defaultPermission,
521
- execution: 'backend',
522
- introduction: {
523
- title: tool.title,
524
- about: tool.description,
525
- },
526
- definition: {
527
- name: `${MCP_SERVER_NAME}-${tool.name}`,
528
- description: tool.description,
529
- schema: tool.inputSchema,
530
- },
531
- invoke: async (ctx: Context, args: Record<string, unknown>) => {
532
- return tool.execute(isRecord(args) ? args : {}, ctx);
533
- },
534
- })),
535
- );
536
- }
537
-
538
- private async registerPluginMcpClientEntry() {
539
- const mcpManager = (this.app as unknown as { aiManager?: { mcpManager?: AIMcpManagerLike } }).aiManager?.mcpManager;
540
- if (!mcpManager || typeof mcpManager.registerMCP !== 'function') {
541
- return;
542
- }
543
-
544
- try {
545
- await mcpManager.registerMCP({
546
- [MCP_SERVER_NAME]: {
547
- title: 'Elastic Report MCP',
548
- description: 'Dedicated MCP server for Kibana-style Elasticsearch reports and Data Views',
549
- transport: 'http',
550
- url: this.resolveInternalMcpUrl(),
551
- headers: {
552
- Authorization: 'Bearer {{ctx.request.token}}',
553
- 'X-Role': '{{ctx.request.headers.x-role}}',
554
- },
555
- useUserContext: true,
556
- enabled: true,
557
- },
558
- });
559
- } catch (error) {
560
- this.app.logger?.warn?.('[plugin-elastic-report] Could not pre-register MCP client entry:', error);
561
- }
562
- }
563
-
564
- private async ensureCollectionSchema(collectionName: string) {
565
- const collection = this.db.getCollection(collectionName);
566
- if (!collection) return;
567
-
568
- const queryInterface = this.db.sequelize.getQueryInterface();
569
- const tableName = collection.getTableNameWithSchema();
570
- let columns: Record<string, unknown> | null = null;
571
-
572
- try {
573
- columns = await queryInterface.describeTable(tableName);
574
- } catch {
575
- await collection.model.sync();
576
- columns = await queryInterface.describeTable(tableName);
577
- }
578
-
579
- const attributes = collection.model.rawAttributes as Record<string, Record<string, unknown> & { field?: string }>;
580
- for (const [attributeName, attribute] of Object.entries(attributes)) {
581
- const columnName = attribute.field || attributeName;
582
- if (columns && columnName in columns) {
583
- continue;
584
- }
585
- const columnDefinition = { ...attribute };
586
- delete columnDefinition.Model;
587
- delete columnDefinition.fieldName;
588
- await queryInterface.addColumn(tableName, columnName, columnDefinition);
589
- }
590
- }
591
-
592
- private async ensureSchema() {
593
- for (const collectionName of this.schemaCollections) {
594
- await this.ensureCollectionSchema(collectionName);
595
- }
596
- }
597
- }
598
-
599
- export default PluginElasticReportServer;
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { resolve } from 'path';
11
+ import type { Context, Next } from '@nocobase/actions';
12
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
13
+ import { Plugin, type InstallOptions } from '@nocobase/server';
14
+ import {
15
+ ACL_SNIPPET,
16
+ DATA_VIEWS_COLLECTION,
17
+ MCP_RELATIVE_PATH,
18
+ MCP_RESOURCE_NAME,
19
+ MCP_SERVER_NAME,
20
+ REPORTS_COLLECTION,
21
+ SERVICE_RESOURCE,
22
+ WORKFLOW_INSTRUCTION_TYPE,
23
+ } from '../shared/constants';
24
+ import type { ExportFormat, ID, ReportRuntimeOverrides } from '../shared/types';
25
+ import {
26
+ assertCanAccessDataView,
27
+ assertCanAccessReport,
28
+ assertCanManageReports,
29
+ canAccessReport,
30
+ normalizeRoleList,
31
+ } from './acl-guard';
32
+ import { ElasticReportMcpServer } from './mcp/ElasticReportMcpServer';
33
+ import { createReportBlockTools } from './report-block-tools';
34
+ import { createElasticReportToolCatalog, type ElasticReportToolDefinition } from './mcp/ElasticReportToolCatalog';
35
+ import { ElasticsearchConnectionService } from './services/ElasticsearchConnectionService';
36
+ import { ElasticReportService, extractCurrentUserId, extractServerUserContext } from './services/ElasticReportService';
37
+ import { ReportExportService } from './services/ReportExportService';
38
+ import { ElasticReportQueryInstruction } from './workflow/ElasticReportQueryInstruction';
39
+
40
+ interface AIToolsManagerLike {
41
+ registerTools: (
42
+ tools: Array<{
43
+ scope: 'CUSTOM' | 'GENERAL' | 'SPECIFIED';
44
+ defaultPermission: 'ALLOW' | 'ASK';
45
+ execution: 'backend' | 'frontend';
46
+ introduction: { title: string; about: string };
47
+ definition: { name: string; description: string; schema: Record<string, unknown> };
48
+ invoke: (ctx: Context, args: Record<string, unknown>) => Promise<unknown>;
49
+ }>,
50
+ ) => void;
51
+ }
52
+
53
+ interface AIMcpManagerLike {
54
+ registerMCP: (registration: Record<string, unknown>) => Promise<void>;
55
+ }
56
+
57
+ function isRecord(value: unknown): value is Record<string, unknown> {
58
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
59
+ }
60
+
61
+ function getActionPayload(ctx: Context): Record<string, unknown> {
62
+ const query = isRecord(ctx.request?.query) ? ctx.request.query : {};
63
+ const actionParams = isRecord(ctx.action?.params) ? ctx.action.params : {};
64
+ const body = isRecord(ctx.request?.body) ? ctx.request.body : {};
65
+ const paramValues = isRecord(actionParams.values) ? actionParams.values : {};
66
+ return {
67
+ ...query,
68
+ ...actionParams,
69
+ ...body,
70
+ ...paramValues,
71
+ };
72
+ }
73
+
74
+ function parseIdParam(value: unknown, label: string): ID {
75
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
76
+ if (typeof value === 'string' && value.trim()) return value.trim();
77
+ const err = new Error(`${label} is required`) as Error & { status?: number };
78
+ err.status = 400;
79
+ throw err;
80
+ }
81
+
82
+ function parseOverridesParam(raw: unknown): ReportRuntimeOverrides | undefined {
83
+ if (isRecord(raw)) {
84
+ return raw as ReportRuntimeOverrides;
85
+ }
86
+ if (typeof raw === 'string' && raw.trim()) {
87
+ try {
88
+ const parsed = JSON.parse(raw);
89
+ return isRecord(parsed) ? (parsed as ReportRuntimeOverrides) : undefined;
90
+ } catch {
91
+ return undefined;
92
+ }
93
+ }
94
+ return undefined;
95
+ }
96
+
97
+ export class PluginElasticReportServer extends Plugin {
98
+ public connectionService!: ElasticsearchConnectionService;
99
+ public reportService!: ElasticReportService;
100
+ public exportService!: ReportExportService;
101
+ public mcpServer!: ElasticReportMcpServer;
102
+ private toolsCatalog: ElasticReportToolDefinition[] = [];
103
+ private readonly schemaCollections = [DATA_VIEWS_COLLECTION, REPORTS_COLLECTION];
104
+
105
+ async beforeLoad() {
106
+ await this.db.import({
107
+ directory: resolve(__dirname, 'collections'),
108
+ });
109
+ this.connectionService = new ElasticsearchConnectionService(this.app);
110
+ this.reportService = new ElasticReportService(this.app, this.connectionService);
111
+ this.exportService = new ReportExportService(this.connectionService, this.reportService);
112
+ this.toolsCatalog = createElasticReportToolCatalog(this.app, this.reportService);
113
+ this.mcpServer = new ElasticReportMcpServer({
114
+ version: this.options?.version || '0.8.0',
115
+ tools: this.toolsCatalog,
116
+ logger: this.app.logger,
117
+ });
118
+ }
119
+
120
+ async load() {
121
+ this.registerServiceResource();
122
+ this.registerMcpEndpoint();
123
+ this.registerAclRules();
124
+ this.registerWorkflowInstructions();
125
+ this.registerAITools();
126
+ await this.registerPluginMcpClientEntry();
127
+
128
+ this.app.on('beforeStop', async () => {
129
+ await this.connectionService?.close();
130
+ });
131
+ }
132
+
133
+ private registerWorkflowInstructions() {
134
+ const workflow = this.app.pm.get('workflow') as WorkflowPlugin | undefined;
135
+ if (!workflow || typeof workflow.registerInstruction !== 'function') {
136
+ return;
137
+ }
138
+ workflow.registerInstruction(
139
+ WORKFLOW_INSTRUCTION_TYPE,
140
+ new ElasticReportQueryInstruction(workflow, this.reportService),
141
+ );
142
+ }
143
+
144
+ async install(_options?: InstallOptions) {
145
+ await this.ensureSchema();
146
+ }
147
+
148
+ async upgrade() {
149
+ await this.ensureSchema();
150
+ }
151
+
152
+ private getApiBasePath(): string {
153
+ const rawPrefix = this.app.resourcer?.options?.prefix ?? process.env.API_BASE_PATH ?? '/api';
154
+ const cleaned = rawPrefix.replace(/\/+/g, '/').replace(/\/$/, '');
155
+ return cleaned;
156
+ }
157
+
158
+ private getMcpEndpointPath(): string {
159
+ return `${this.getApiBasePath()}${MCP_RELATIVE_PATH}`;
160
+ }
161
+
162
+ private resolveInternalMcpUrl(): string {
163
+ const port = process.env.APP_PORT || '13000';
164
+ const host = process.env.ELASTIC_REPORT_MCP_INTERNAL_HOST || `http://127.0.0.1:${port}`;
165
+ return `${host.replace(/\/$/, '')}${this.getMcpEndpointPath()}`;
166
+ }
167
+
168
+ private registerServiceResource() {
169
+ this.app.resourceManager.define({
170
+ name: SERVICE_RESOURCE,
171
+ actions: {
172
+ listConnections: async (ctx: Context, next: Next) => {
173
+ assertCanManageReports(this.app, ctx);
174
+ ctx.body = await this.reportService.listConnections();
175
+ await next();
176
+ },
177
+
178
+ testConnection: async (ctx: Context, next: Next) => {
179
+ assertCanManageReports(this.app, ctx);
180
+ const payload = getActionPayload(ctx);
181
+ const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
182
+ if (!dataSourceKey) {
183
+ ctx.throw(400, 'dataSourceKey is required');
184
+ }
185
+ const indexPattern =
186
+ typeof payload.indexPattern === 'string' && payload.indexPattern.trim() ? payload.indexPattern.trim() : '*';
187
+ try {
188
+ ctx.body = await this.reportService.testConnection(dataSourceKey, indexPattern);
189
+ } catch (error) {
190
+ ctx.throw(400, error instanceof Error ? error.message : String(error));
191
+ }
192
+ await next();
193
+ },
194
+
195
+ listRoles: async (ctx: Context, next: Next) => {
196
+ assertCanManageReports(this.app, ctx);
197
+ ctx.body = await this.reportService.listAvailableRoles();
198
+ await next();
199
+ },
200
+
201
+ listIndices: async (ctx: Context, next: Next) => {
202
+ assertCanManageReports(this.app, ctx);
203
+ const payload = getActionPayload(ctx);
204
+ const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
205
+ if (!dataSourceKey) {
206
+ ctx.throw(400, 'dataSourceKey is required');
207
+ }
208
+ const indexPattern =
209
+ typeof payload.indexPattern === 'string' && payload.indexPattern.trim() ? payload.indexPattern.trim() : '*';
210
+ try {
211
+ ctx.body = await this.reportService.listIndices(dataSourceKey, indexPattern);
212
+ } catch (error) {
213
+ ctx.throw(400, error instanceof Error ? error.message : String(error));
214
+ }
215
+ await next();
216
+ },
217
+
218
+ inspectFields: async (ctx: Context, next: Next) => {
219
+ const payload = getActionPayload(ctx);
220
+ try {
221
+ if (payload.dataViewId !== undefined && payload.dataViewId !== null && String(payload.dataViewId).trim()) {
222
+ const dvId = parseIdParam(payload.dataViewId, 'dataViewId');
223
+ const refresh = payload.refresh === true || payload.refresh === 'true';
224
+ if (refresh) {
225
+ assertCanManageReports(this.app, ctx);
226
+ } else {
227
+ const dv = await this.reportService.getDataView(dvId);
228
+ assertCanAccessDataView(this.app, ctx, dv);
229
+ }
230
+ ctx.body = await this.reportService.inspectDataViewFields(dvId, refresh);
231
+ } else {
232
+ assertCanManageReports(this.app, ctx);
233
+ const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
234
+ const indexPattern = typeof payload.indexPattern === 'string' ? payload.indexPattern.trim() : '';
235
+ if (!dataSourceKey || !indexPattern) {
236
+ ctx.throw(400, 'Either dataViewId or (dataSourceKey + indexPattern) is required');
237
+ }
238
+ const fields = await this.reportService.inspectFieldsBySource(dataSourceKey, indexPattern);
239
+ ctx.body = { fields };
240
+ }
241
+ } catch (error) {
242
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
243
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
244
+ }
245
+ await next();
246
+ },
247
+
248
+ upsertDataView: async (ctx: Context, next: Next) => {
249
+ assertCanManageReports(this.app, ctx);
250
+ const payload = getActionPayload(ctx);
251
+ try {
252
+ ctx.body = await this.reportService.upsertDataView(
253
+ {
254
+ ...(payload.id !== undefined && payload.id !== null && String(payload.id).trim() !== ''
255
+ ? { id: parseIdParam(payload.id, 'id') }
256
+ : {}),
257
+ title: typeof payload.title === 'string' ? payload.title : '',
258
+ dataSourceKey: typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey : '',
259
+ indexPattern: typeof payload.indexPattern === 'string' ? payload.indexPattern : '',
260
+ timeField: typeof payload.timeField === 'string' ? payload.timeField : null,
261
+ description: typeof payload.description === 'string' ? payload.description : null,
262
+ ...(payload.allowedRoles !== undefined
263
+ ? { allowedRoles: normalizeRoleList(payload.allowedRoles) }
264
+ : {}),
265
+ },
266
+ extractCurrentUserId(ctx),
267
+ );
268
+ } catch (error) {
269
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
270
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
271
+ }
272
+ await next();
273
+ },
274
+
275
+ previewReport: async (ctx: Context, next: Next) => {
276
+ assertCanManageReports(this.app, ctx);
277
+ const payload = getActionPayload(ctx);
278
+ try {
279
+ const dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
280
+ ctx.body = await this.reportService.previewReport({
281
+ dataViewId,
282
+ spec: payload.spec,
283
+ overrides: parseOverridesParam(payload.overrides),
284
+ userContext: extractServerUserContext(ctx),
285
+ });
286
+ } catch (error) {
287
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
288
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
289
+ }
290
+ await next();
291
+ },
292
+
293
+ saveReport: async (ctx: Context, next: Next) => {
294
+ assertCanManageReports(this.app, ctx);
295
+ const payload = getActionPayload(ctx);
296
+ try {
297
+ ctx.body = await this.reportService.saveReport(
298
+ {
299
+ ...(payload.id !== undefined && payload.id !== null && String(payload.id).trim() !== ''
300
+ ? { id: parseIdParam(payload.id, 'id') }
301
+ : {}),
302
+ title: typeof payload.title === 'string' ? payload.title : '',
303
+ description: typeof payload.description === 'string' ? payload.description : null,
304
+ dataViewId: parseIdParam(payload.dataViewId, 'dataViewId'),
305
+ spec: payload.spec,
306
+ published: payload.published !== false,
307
+ ...(payload.allowedRoles !== undefined
308
+ ? { allowedRoles: normalizeRoleList(payload.allowedRoles) }
309
+ : {}),
310
+ },
311
+ extractCurrentUserId(ctx),
312
+ );
313
+ } catch (error) {
314
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
315
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
316
+ }
317
+ await next();
318
+ },
319
+
320
+ listPublishedReports: async (ctx: Context, next: Next) => {
321
+ const payload = getActionPayload(ctx);
322
+ const search = typeof payload.search === 'string' ? payload.search : undefined;
323
+ const publishedReports = await this.reportService.listReports({
324
+ publishedOnly: true,
325
+ search,
326
+ });
327
+ ctx.body = publishedReports.filter((report) => canAccessReport(this.app, ctx, report, report.dataView));
328
+ await next();
329
+ },
330
+
331
+ getReportMeta: async (ctx: Context, next: Next) => {
332
+ const payload = getActionPayload(ctx);
333
+ const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
334
+ try {
335
+ const reportId = parseIdParam(rawId, 'reportId');
336
+ const report = await this.reportService.getReport(reportId);
337
+ const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
338
+ assertCanAccessReport(this.app, ctx, report, dataView);
339
+ ctx.body = { report, dataView, fields };
340
+ } catch (error) {
341
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
342
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
343
+ }
344
+ await next();
345
+ },
346
+
347
+ runReport: async (ctx: Context, next: Next) => {
348
+ const payload = getActionPayload(ctx);
349
+ const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
350
+ try {
351
+ const reportId = parseIdParam(rawId, 'reportId');
352
+ const report = await this.reportService.getReport(reportId);
353
+ const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
354
+ assertCanAccessReport(this.app, ctx, report, dataView);
355
+ ctx.body = await this.reportService.runSavedReport({
356
+ reportId,
357
+ overrides: parseOverridesParam(payload.overrides),
358
+ requirePublished: false,
359
+ userContext: extractServerUserContext(ctx),
360
+ });
361
+ } catch (error) {
362
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
363
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
364
+ }
365
+ await next();
366
+ },
367
+
368
+ inspectTopValues: async (ctx: Context, next: Next) => {
369
+ const payload = getActionPayload(ctx);
370
+ try {
371
+ const field = typeof payload.field === 'string' ? payload.field.trim() : '';
372
+ if (!field) {
373
+ ctx.throw(400, 'field is required');
374
+ }
375
+ let dataViewId: ID;
376
+ let reportId: ID | undefined;
377
+ if (payload.reportId !== undefined && payload.reportId !== null && String(payload.reportId).trim() !== '') {
378
+ reportId = parseIdParam(payload.reportId, 'reportId');
379
+ const report = await this.reportService.getReport(reportId);
380
+ const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
381
+ assertCanAccessReport(this.app, ctx, report, dataView);
382
+ dataViewId = report.dataViewId;
383
+ } else {
384
+ dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
385
+ const dataView = await this.reportService.getDataView(dataViewId);
386
+ assertCanAccessDataView(this.app, ctx, dataView);
387
+ }
388
+
389
+ ctx.body = await this.reportService.inspectFieldTopValues({
390
+ dataViewId,
391
+ ...(reportId !== undefined ? { reportId } : {}),
392
+ field,
393
+ size: typeof payload.size === 'number' ? payload.size : Number(payload.size) || 10,
394
+ overrides: parseOverridesParam(payload.overrides),
395
+ userContext: extractServerUserContext(ctx),
396
+ });
397
+ } catch (error) {
398
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
399
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
400
+ }
401
+ await next();
402
+ },
403
+
404
+ exportReport: async (ctx: Context, next: Next) => {
405
+ const payload = getActionPayload(ctx);
406
+ const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
407
+ try {
408
+ const reportId = parseIdParam(rawId, 'reportId');
409
+ const report = await this.reportService.getReport(reportId);
410
+ const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
411
+ assertCanAccessReport(this.app, ctx, report, dataView);
412
+
413
+ const format: ExportFormat = payload.format === 'ndjson' ? 'ndjson' : 'csv';
414
+ const columns = Array.isArray(payload.columns)
415
+ ? payload.columns.filter((c): c is string => typeof c === 'string' && Boolean(c.trim()))
416
+ : typeof payload.columns === 'string' && payload.columns.trim()
417
+ ? payload.columns
418
+ .split(',')
419
+ .map((c) => c.trim())
420
+ .filter(Boolean)
421
+ : undefined;
422
+ const maxRows =
423
+ typeof payload.maxRows === 'number'
424
+ ? payload.maxRows
425
+ : payload.maxRows !== undefined
426
+ ? Number(payload.maxRows)
427
+ : undefined;
428
+
429
+ const { stream, filename, contentType } = await this.exportService.createExportStream({
430
+ reportId,
431
+ format,
432
+ overrides: parseOverridesParam(payload.overrides),
433
+ ...(columns ? { columns } : {}),
434
+ ...(maxRows !== undefined && Number.isFinite(maxRows) ? { maxRows } : {}),
435
+ userContext: extractServerUserContext(ctx),
436
+ });
437
+
438
+ ctx.withoutDataWrapping = true;
439
+ ctx.status = 200;
440
+ ctx.type = contentType;
441
+ ctx.set('Content-Disposition', `attachment; filename="${filename}"`);
442
+ ctx.body = stream;
443
+ } catch (error) {
444
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
445
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
446
+ }
447
+ await next();
448
+ },
449
+
450
+ getMcpInfo: async (ctx: Context, next: Next) => {
451
+ ctx.body = {
452
+ serverName: MCP_SERVER_NAME,
453
+ endpointPath: this.getMcpEndpointPath(),
454
+ internalUrl: this.resolveInternalMcpUrl(),
455
+ useUserContext: true,
456
+ tools: this.mcpServer.getToolsMetadata(),
457
+ };
458
+ await next();
459
+ },
460
+ },
461
+ });
462
+ }
463
+
464
+ private registerMcpEndpoint() {
465
+ const mcpActionHandler = async (ctx: Context) => {
466
+ await this.mcpServer.handleRequest(ctx);
467
+ };
468
+
469
+ this.app.resourceManager.define({
470
+ name: MCP_RESOURCE_NAME,
471
+ actions: {
472
+ list: mcpActionHandler,
473
+ create: mcpActionHandler,
474
+ },
475
+ only: ['list', 'create'],
476
+ });
477
+ }
478
+
479
+ private registerAclRules() {
480
+ // Viewers on pages can list published reports, inspect report metadata/top-values, run, and export published reports.
481
+ this.app.acl.allow(
482
+ SERVICE_RESOURCE,
483
+ ['listPublishedReports', 'getReportMeta', 'runReport', 'inspectTopValues', 'exportReport'],
484
+ 'loggedIn',
485
+ );
486
+ // Dedicated MCP endpoint requires authentication; tool-level ACL enforces read vs manage permissions.
487
+ this.app.acl.allow(MCP_RESOURCE_NAME, '*', 'loggedIn');
488
+
489
+ // Full studio & data-view management is grouped under the plugin settings snippet.
490
+ this.app.acl.registerSnippet({
491
+ name: ACL_SNIPPET,
492
+ actions: [
493
+ `${DATA_VIEWS_COLLECTION}:list`,
494
+ `${DATA_VIEWS_COLLECTION}:get`,
495
+ `${DATA_VIEWS_COLLECTION}:create`,
496
+ `${DATA_VIEWS_COLLECTION}:update`,
497
+ `${DATA_VIEWS_COLLECTION}:destroy`,
498
+ `${REPORTS_COLLECTION}:list`,
499
+ `${REPORTS_COLLECTION}:get`,
500
+ `${REPORTS_COLLECTION}:create`,
501
+ `${REPORTS_COLLECTION}:update`,
502
+ `${REPORTS_COLLECTION}:destroy`,
503
+ `${SERVICE_RESOURCE}:*`,
504
+ ],
505
+ });
506
+ }
507
+
508
+ private registerAITools() {
509
+ const toolsManager = (this.app as unknown as { aiManager?: { toolsManager?: AIToolsManagerLike } }).aiManager
510
+ ?.toolsManager;
511
+ if (!toolsManager) {
512
+ this.app.logger?.info?.(
513
+ '[plugin-elastic-report] aiManager.toolsManager is not present; skipping direct AI tool registration',
514
+ );
515
+ return;
516
+ }
517
+
518
+ toolsManager.registerTools(
519
+ [...this.toolsCatalog, ...createReportBlockTools(this.app, this.reportService)].map((tool) => ({
520
+ scope: 'CUSTOM',
521
+ defaultPermission: tool.defaultPermission,
522
+ execution: 'backend',
523
+ introduction: {
524
+ title: tool.title,
525
+ about: tool.description,
526
+ },
527
+ definition: {
528
+ name: `${MCP_SERVER_NAME}-${tool.name}`,
529
+ description: tool.description,
530
+ schema: tool.inputSchema,
531
+ },
532
+ invoke: async (ctx: Context, args: Record<string, unknown>) => {
533
+ return tool.execute(isRecord(args) ? args : {}, ctx);
534
+ },
535
+ })),
536
+ );
537
+ }
538
+
539
+ private async registerPluginMcpClientEntry() {
540
+ const mcpManager = (this.app as unknown as { aiManager?: { mcpManager?: AIMcpManagerLike } }).aiManager?.mcpManager;
541
+ if (!mcpManager || typeof mcpManager.registerMCP !== 'function') {
542
+ return;
543
+ }
544
+
545
+ try {
546
+ await mcpManager.registerMCP({
547
+ [MCP_SERVER_NAME]: {
548
+ title: 'Elastic Report MCP',
549
+ description: 'Dedicated MCP server for Kibana-style Elasticsearch reports and Data Views',
550
+ transport: 'http',
551
+ url: this.resolveInternalMcpUrl(),
552
+ headers: {
553
+ Authorization: 'Bearer {{ctx.request.token}}',
554
+ 'X-Role': '{{ctx.request.headers.x-role}}',
555
+ },
556
+ useUserContext: true,
557
+ enabled: true,
558
+ },
559
+ });
560
+ } catch (error) {
561
+ this.app.logger?.warn?.('[plugin-elastic-report] Could not pre-register MCP client entry:', error);
562
+ }
563
+ }
564
+
565
+ private async ensureCollectionSchema(collectionName: string) {
566
+ const collection = this.db.getCollection(collectionName);
567
+ if (!collection) return;
568
+
569
+ const queryInterface = this.db.sequelize.getQueryInterface();
570
+ const tableName = collection.getTableNameWithSchema();
571
+ let columns: Record<string, unknown> | null = null;
572
+
573
+ try {
574
+ columns = await queryInterface.describeTable(tableName);
575
+ } catch {
576
+ await collection.model.sync();
577
+ columns = await queryInterface.describeTable(tableName);
578
+ }
579
+
580
+ for (const [attributeName, attribute] of Object.entries(collection.model.rawAttributes)) {
581
+ const columnName = attribute.field || attributeName;
582
+ if (columns && columnName in columns) {
583
+ continue;
584
+ }
585
+ const columnDefinition: typeof attribute & { Model?: unknown; fieldName?: string } = { ...attribute };
586
+ delete columnDefinition.Model;
587
+ delete columnDefinition.fieldName;
588
+ await queryInterface.addColumn(tableName, columnName, columnDefinition);
589
+ }
590
+ }
591
+
592
+ private async ensureSchema() {
593
+ for (const collectionName of this.schemaCollections) {
594
+ await this.ensureCollectionSchema(collectionName);
595
+ }
596
+ }
597
+ }
598
+
599
+ export default PluginElasticReportServer;