plugin-elastic-report 0.1.1 → 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 (80) 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/dist/ai/skills/elastic-report/SKILLS.md +52 -0
  6. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  7. package/dist/client/index.js +1 -1
  8. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  9. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  10. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  11. package/dist/client-v2/index.js +1 -1
  12. package/dist/externalVersion.js +5 -3
  13. package/dist/locale/en-US.json +213 -99
  14. package/dist/locale/vi-VN.json +213 -99
  15. package/dist/locale/zh-CN.json +213 -99
  16. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  17. package/dist/server/acl-guard.js +97 -25
  18. package/dist/server/collections/es-report-data-views.js +6 -0
  19. package/dist/server/collections/es-reports.js +6 -0
  20. package/dist/server/mcp/ElasticReportToolCatalog.js +238 -14
  21. package/dist/server/plugin.js +156 -22
  22. package/dist/server/report-block-tools.js +340 -0
  23. package/dist/server/services/ElasticReportService.js +137 -17
  24. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  25. package/dist/server/services/ReportExportService.js +243 -0
  26. package/dist/server/services/ReportQueryCompiler.js +532 -91
  27. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  28. package/dist/shared/constants.js +26 -2
  29. package/package.json +3 -3
  30. package/server.d.ts +2 -2
  31. package/server.js +1 -1
  32. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  33. package/src/client/index.tsx +34 -19
  34. package/src/client/workflow-instructions.tsx +44 -0
  35. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -311
  36. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  37. package/src/client-v2/api.ts +320 -224
  38. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  39. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -399
  40. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  41. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  42. package/src/client-v2/components/ElasticReportBlock.tsx +306 -160
  43. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -707
  44. package/src/client-v2/components/HighlightText.tsx +50 -50
  45. package/src/client-v2/components/ReportSelect.tsx +85 -72
  46. package/src/client-v2/index.tsx +14 -14
  47. package/src/client-v2/locale.ts +23 -23
  48. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  49. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -85
  50. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1047
  51. package/src/client-v2/plugin.tsx +107 -52
  52. package/src/client-v2/report-destination.tsx +126 -0
  53. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  54. package/src/client-v2/workflow/instructions.tsx +149 -0
  55. package/src/index.ts +11 -11
  56. package/src/locale/en-US.json +213 -99
  57. package/src/locale/vi-VN.json +213 -99
  58. package/src/locale/zh-CN.json +213 -99
  59. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  60. package/src/server/__tests__/query-compiler.test.ts +620 -231
  61. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -377
  62. package/src/server/acl-guard.ts +194 -103
  63. package/src/server/collections/es-report-data-views.ts +64 -58
  64. package/src/server/collections/es-reports.ts +80 -74
  65. package/src/server/index.ts +15 -15
  66. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  67. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -417
  68. package/src/server/plugin.ts +599 -431
  69. package/src/server/report-block-tools.ts +400 -0
  70. package/src/server/services/ElasticReportService.ts +494 -326
  71. package/src/server/services/ElasticsearchConnectionService.ts +728 -401
  72. package/src/server/services/ReportExportService.ts +282 -0
  73. package/src/server/services/ReportQueryCompiler.ts +1552 -1017
  74. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  75. package/src/shared/constants.ts +39 -29
  76. package/src/shared/types.ts +272 -175
  77. package/ai/skills/elastic-report/SKILLS.md +0 -32
  78. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
  79. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  80. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,417 +1,667 @@
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 type { Context } from '@nocobase/actions';
11
- import type { Application } from '@nocobase/server';
12
- import type { ID } from '../../shared/types';
13
- import { assertAuthenticated, assertCanManageReports, canManageReports } from '../acl-guard';
14
- import { extractCurrentUserId, type ElasticReportService } from '../services/ElasticReportService';
15
-
16
- export interface ElasticReportToolDefinition {
17
- name: string;
18
- title: string;
19
- description: string;
20
- defaultPermission: 'ALLOW' | 'ASK';
21
- inputSchema: Record<string, unknown>;
22
- execute: (args: Record<string, unknown>, ctx?: Partial<Context>) => Promise<unknown>;
23
- }
24
-
25
- function isRecord(value: unknown): value is Record<string, unknown> {
26
- return typeof value === 'object' && value !== null && !Array.isArray(value);
27
- }
28
-
29
- function requireId(value: unknown, fieldName: string): ID {
30
- if (typeof value === 'number' && Number.isFinite(value)) return value;
31
- if (typeof value === 'string' && value.trim()) return value.trim();
32
- throw new Error(`"${fieldName}" is required`);
33
- }
34
-
35
- export function createElasticReportToolCatalog(
36
- app: Application,
37
- reportService: ElasticReportService,
38
- ): ElasticReportToolDefinition[] {
39
- return [
40
- {
41
- name: 'es_list_connections',
42
- title: 'List Elasticsearch Connections',
43
- description:
44
- 'List Elasticsearch data source connections configured in NocoBase (via plugin-data-source-elasticsearch) and optionally list matching indices for a connection.',
45
- defaultPermission: 'ALLOW',
46
- inputSchema: {
47
- type: 'object',
48
- properties: {
49
- dataSourceKey: {
50
- type: 'string',
51
- description: 'Optional Elasticsearch dataSourceKey to also fetch matching index names.',
52
- },
53
- indexPattern: {
54
- type: 'string',
55
- description: 'Optional wildcard pattern when listing indices (default "*").',
56
- },
57
- },
58
- },
59
- async execute(args, ctx) {
60
- assertCanManageReports(app, ctx);
61
- const connections = await reportService.listConnections();
62
- const dsKey = typeof args.dataSourceKey === 'string' ? args.dataSourceKey.trim() : '';
63
- if (!dsKey) {
64
- return { connections };
65
- }
66
- const pattern =
67
- typeof args.indexPattern === 'string' && args.indexPattern.trim() ? args.indexPattern.trim() : '*';
68
- const indices = await reportService.listIndices(dsKey, pattern);
69
- return { connections, dataSourceKey: dsKey, indices };
70
- },
71
- },
72
- {
73
- name: 'es_list_data_views',
74
- title: 'List Elasticsearch Data Views',
75
- description:
76
- 'List configured Elasticsearch Data Views (index patterns + time fields) used as the foundation for Kibana-style reports.',
77
- defaultPermission: 'ALLOW',
78
- inputSchema: {
79
- type: 'object',
80
- properties: {},
81
- },
82
- async execute(_args, ctx) {
83
- assertAuthenticated(ctx);
84
- const dataViews = await reportService.listDataViews();
85
- return { dataViews };
86
- },
87
- },
88
- {
89
- name: 'es_upsert_data_view',
90
- title: 'Create or Update Elasticsearch Data View',
91
- description:
92
- 'Create or update an Elasticsearch Data View over an existing Elasticsearch dataSourceKey and indexPattern (e.g. "logs-*", "orders-*"), automatically introspecting field capabilities via _field_caps.',
93
- defaultPermission: 'ALLOW',
94
- inputSchema: {
95
- type: 'object',
96
- required: ['title', 'dataSourceKey', 'indexPattern'],
97
- properties: {
98
- id: {
99
- type: ['number', 'string'],
100
- description: 'Optional existing dataViewId to update.',
101
- },
102
- title: {
103
- type: 'string',
104
- description: 'Human-readable Data View title.',
105
- },
106
- dataSourceKey: {
107
- type: 'string',
108
- description: 'Key of an Elasticsearch connection from es_list_connections.',
109
- },
110
- indexPattern: {
111
- type: 'string',
112
- description: 'Elasticsearch index or wildcard pattern, such as "logs-*" or "events-*".',
113
- },
114
- timeField: {
115
- type: 'string',
116
- description: 'Optional primary date field (e.g. "@timestamp"). Auto-detected if omitted.',
117
- },
118
- description: {
119
- type: 'string',
120
- description: 'Optional description of the dataset.',
121
- },
122
- },
123
- },
124
- async execute(args, ctx) {
125
- assertCanManageReports(app, ctx);
126
- const dataView = await reportService.upsertDataView(
127
- {
128
- ...(args.id !== undefined ? { id: requireId(args.id, 'id') } : {}),
129
- title: typeof args.title === 'string' ? args.title : '',
130
- dataSourceKey: typeof args.dataSourceKey === 'string' ? args.dataSourceKey : '',
131
- indexPattern: typeof args.indexPattern === 'string' ? args.indexPattern : '',
132
- timeField: typeof args.timeField === 'string' ? args.timeField : null,
133
- description: typeof args.description === 'string' ? args.description : null,
134
- },
135
- extractCurrentUserId(ctx),
136
- );
137
- return {
138
- dataView,
139
- fieldCount: dataView.cachedFields?.length ?? 0,
140
- };
141
- },
142
- },
143
- {
144
- name: 'es_inspect_fields',
145
- title: 'Inspect Data View Field Capabilities',
146
- description:
147
- 'Inspect Elasticsearch field capabilities (_field_caps) for a Data View: field types, searchable/aggregatable flags, and .keyword subfields. ALWAYS call this before previewing or saving a report so you never guess field names or sort/group on non-aggregatable text fields.',
148
- defaultPermission: 'ALLOW',
149
- inputSchema: {
150
- type: 'object',
151
- required: ['dataViewId'],
152
- properties: {
153
- dataViewId: {
154
- type: ['number', 'string'],
155
- description: 'Target Data View ID from es_list_data_views.',
156
- },
157
- refresh: {
158
- type: 'boolean',
159
- description: 'Set true to re-fetch live _field_caps from Elasticsearch instead of cached metadata.',
160
- },
161
- },
162
- },
163
- async execute(args, ctx) {
164
- assertAuthenticated(ctx);
165
- const dataViewId = requireId(args.dataViewId, 'dataViewId');
166
- const refresh = args.refresh === true;
167
- if (refresh) {
168
- assertCanManageReports(app, ctx);
169
- }
170
- const { dataView, fields } = await reportService.inspectDataViewFields(dataViewId, refresh);
171
- return {
172
- dataView: {
173
- id: dataView.id,
174
- title: dataView.title,
175
- dataSourceKey: dataView.dataSourceKey,
176
- indexPattern: dataView.indexPattern,
177
- timeField: dataView.timeField,
178
- },
179
- fields,
180
- };
181
- },
182
- },
183
- {
184
- name: 'es_preview_report',
185
- title: 'Preview Elasticsearch Report Query',
186
- description:
187
- 'Execute a read-only preview of a Kibana-style ReportSpec (table, bar, line, area, pie, or metric) against Elasticsearch (capped at 20 sample rows) to verify total hits, aggregations, filters, KQL search, and sorting before saving.',
188
- defaultPermission: 'ALLOW',
189
- inputSchema: {
190
- type: 'object',
191
- required: ['dataViewId', 'spec'],
192
- properties: {
193
- dataViewId: {
194
- type: ['number', 'string'],
195
- description: 'Target Data View ID.',
196
- },
197
- spec: {
198
- type: 'object',
199
- description: 'Declarative ReportSpec configuration.',
200
- required: ['visualization'],
201
- properties: {
202
- visualization: {
203
- type: 'string',
204
- enum: ['table', 'bar', 'line', 'area', 'pie', 'metric'],
205
- },
206
- query: {
207
- type: 'string',
208
- description: 'KQL search expression, e.g. \'status >= 500 AND service: "checkout"\'.',
209
- },
210
- queryMode: {
211
- type: 'string',
212
- enum: ['kql', 'simple'],
213
- },
214
- filters: {
215
- type: 'array',
216
- items: {
217
- type: 'object',
218
- required: ['field', 'operator'],
219
- properties: {
220
- field: { type: 'string' },
221
- operator: {
222
- type: 'string',
223
- enum: [
224
- 'eq',
225
- 'ne',
226
- 'in',
227
- 'not_in',
228
- 'gt',
229
- 'gte',
230
- 'lt',
231
- 'lte',
232
- 'between',
233
- 'contains',
234
- 'exists',
235
- 'not_exists',
236
- ],
237
- },
238
- value: {},
239
- valueTo: {},
240
- },
241
- },
242
- },
243
- sort: {
244
- type: 'array',
245
- items: {
246
- type: 'object',
247
- required: ['field', 'order'],
248
- properties: {
249
- field: { type: 'string' },
250
- order: { type: 'string', enum: ['asc', 'desc'] },
251
- },
252
- },
253
- },
254
- timeRange: {
255
- type: 'object',
256
- properties: {
257
- preset: {
258
- type: 'string',
259
- enum: ['last_15m', 'last_1h', 'last_24h', 'last_7d', 'last_30d', 'last_90d', 'all', 'custom'],
260
- },
261
- from: { type: 'string' },
262
- to: { type: 'string' },
263
- },
264
- },
265
- columns: {
266
- type: 'array',
267
- items: { type: 'string' },
268
- },
269
- pageSize: {
270
- type: 'number',
271
- },
272
- chart: {
273
- type: 'object',
274
- properties: {
275
- bucketType: { type: 'string', enum: ['date_histogram', 'terms'] },
276
- bucketField: { type: 'string' },
277
- calendarInterval: {
278
- type: 'string',
279
- enum: ['auto', '1m', '5m', '15m', '1h', '1d', '1w', '1M'],
280
- },
281
- topN: { type: 'number' },
282
- metricType: {
283
- type: 'string',
284
- enum: ['count', 'sum', 'avg', 'min', 'max', 'cardinality'],
285
- },
286
- metricField: { type: 'string' },
287
- metricLabel: { type: 'string' },
288
- showHistogram: { type: 'boolean' },
289
- },
290
- },
291
- allowInteractiveControls: { type: 'boolean' },
292
- },
293
- },
294
- },
295
- },
296
- async execute(args, ctx) {
297
- assertCanManageReports(app, ctx);
298
- const dataViewId = requireId(args.dataViewId, 'dataViewId');
299
- const { dataView, result } = await reportService.previewReport({
300
- dataViewId,
301
- spec: isRecord(args.spec) ? args.spec : { visualization: 'table' },
302
- forMcp: true,
303
- });
304
- return {
305
- dataView: {
306
- id: dataView.id,
307
- title: dataView.title,
308
- indexPattern: dataView.indexPattern,
309
- },
310
- total: result.total,
311
- totalRelation: result.totalRelation,
312
- tookMs: result.tookMs,
313
- visualization: result.visualization,
314
- columns: result.columns,
315
- sampleRows: result.rows.slice(0, 10),
316
- series: result.series,
317
- histogram: result.histogram,
318
- metricValue: result.metricValue,
319
- metricLabel: result.metricLabel,
320
- compiledDsl: result.compiledDsl,
321
- };
322
- },
323
- },
324
- {
325
- name: 'es_save_report',
326
- title: 'Create or Update Saved Elasticsearch Report',
327
- description:
328
- 'Create or update a Saved Elasticsearch Report so users can immediately add an "Elastic Report" block on any NocoBase page and select this report.',
329
- defaultPermission: 'ALLOW',
330
- inputSchema: {
331
- type: 'object',
332
- required: ['title', 'dataViewId', 'spec'],
333
- properties: {
334
- id: {
335
- type: ['number', 'string'],
336
- description: 'Optional existing report ID when updating a report.',
337
- },
338
- title: {
339
- type: 'string',
340
- description: 'Clear report title displayed in the Elastic Report block picker.',
341
- },
342
- description: {
343
- type: 'string',
344
- description: 'Optional summary explaining what this report measures or filters.',
345
- },
346
- dataViewId: {
347
- type: ['number', 'string'],
348
- description: 'Target Data View ID.',
349
- },
350
- published: {
351
- type: 'boolean',
352
- description: 'Whether the report is published for selection in page blocks (default true).',
353
- },
354
- spec: {
355
- type: 'object',
356
- description: 'Validated ReportSpec object (same schema as es_preview_report.spec).',
357
- },
358
- },
359
- },
360
- async execute(args, ctx) {
361
- assertCanManageReports(app, ctx);
362
- const saved = await reportService.saveReport(
363
- {
364
- ...(args.id !== undefined ? { id: requireId(args.id, 'id') } : {}),
365
- title: typeof args.title === 'string' ? args.title : '',
366
- description: typeof args.description === 'string' ? args.description : null,
367
- dataViewId: requireId(args.dataViewId, 'dataViewId'),
368
- published: args.published !== false,
369
- spec: isRecord(args.spec) ? args.spec : { visualization: 'table' },
370
- },
371
- extractCurrentUserId(ctx),
372
- );
373
- return {
374
- report: saved,
375
- usageHint:
376
- 'Report saved and published. Users can open any NocoBase /v/ page, click Add Block -> Elastic Report, and select this report from the dropdown.',
377
- };
378
- },
379
- },
380
- {
381
- name: 'es_list_reports',
382
- title: 'List Saved Elasticsearch Reports',
383
- description:
384
- 'List Saved Elasticsearch Reports (or filter by title keyword) to inspect or refine existing reports.',
385
- defaultPermission: 'ALLOW',
386
- inputSchema: {
387
- type: 'object',
388
- properties: {
389
- search: {
390
- type: 'string',
391
- description: 'Optional keyword to filter reports by title.',
392
- },
393
- reportId: {
394
- type: ['number', 'string'],
395
- description: 'Optional specific reportId to retrieve full report spec.',
396
- },
397
- },
398
- },
399
- async execute(args, ctx) {
400
- assertAuthenticated(ctx);
401
- const isManager = canManageReports(app, ctx);
402
- if (args.reportId !== undefined && args.reportId !== null && String(args.reportId).trim() !== '') {
403
- const report = await reportService.getReport(requireId(args.reportId, 'reportId'));
404
- if (!isManager && !report.published) {
405
- throw new Error('Report not found');
406
- }
407
- return { report };
408
- }
409
- const reports = await reportService.listReports({
410
- publishedOnly: !isManager,
411
- search: typeof args.search === 'string' ? args.search : undefined,
412
- });
413
- return { reports };
414
- },
415
- },
416
- ];
417
- }
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 type { Context } from '@nocobase/actions';
11
+ import type { Application } from '@nocobase/server';
12
+ import type { ID, ReportRuntimeOverrides } from '../../shared/types';
13
+ import {
14
+ assertAuthenticated,
15
+ assertCanAccessDataView,
16
+ assertCanAccessReport,
17
+ assertCanManageReports,
18
+ canAccessDataView,
19
+ canAccessReport,
20
+ canManageReports,
21
+ normalizeRoleList,
22
+ } from '../acl-guard';
23
+ import {
24
+ extractCurrentUserId,
25
+ extractServerUserContext,
26
+ type ElasticReportService,
27
+ } from '../services/ElasticReportService';
28
+
29
+ export interface ElasticReportToolDefinition {
30
+ name: string;
31
+ title: string;
32
+ description: string;
33
+ defaultPermission: 'ALLOW' | 'ASK';
34
+ inputSchema: Record<string, unknown>;
35
+ execute: (args: Record<string, unknown>, ctx?: Partial<Context>) => Promise<unknown>;
36
+ }
37
+
38
+ function isRecord(value: unknown): value is Record<string, unknown> {
39
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
40
+ }
41
+
42
+ function requireId(value: unknown, fieldName: string): ID {
43
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
44
+ if (typeof value === 'string' && value.trim()) return value.trim();
45
+ throw new Error(`"${fieldName}" is required`);
46
+ }
47
+
48
+ export function createElasticReportToolCatalog(
49
+ app: Application,
50
+ reportService: ElasticReportService,
51
+ ): ElasticReportToolDefinition[] {
52
+ return [
53
+ {
54
+ name: 'es_list_connections',
55
+ title: 'List Elasticsearch Connections',
56
+ description:
57
+ 'List Elasticsearch data source connections configured in NocoBase (via plugin-data-source-elasticsearch) and optionally list matching indices for a connection.',
58
+ defaultPermission: 'ALLOW',
59
+ inputSchema: {
60
+ type: 'object',
61
+ properties: {
62
+ dataSourceKey: {
63
+ type: 'string',
64
+ description: 'Optional Elasticsearch dataSourceKey to also fetch matching index names.',
65
+ },
66
+ indexPattern: {
67
+ type: 'string',
68
+ description: 'Optional wildcard pattern when listing indices (default "*").',
69
+ },
70
+ },
71
+ },
72
+ async execute(args, ctx) {
73
+ assertCanManageReports(app, ctx);
74
+ const connections = await reportService.listConnections();
75
+ const dsKey = typeof args.dataSourceKey === 'string' ? args.dataSourceKey.trim() : '';
76
+ if (!dsKey) {
77
+ return { connections };
78
+ }
79
+ const pattern =
80
+ typeof args.indexPattern === 'string' && args.indexPattern.trim() ? args.indexPattern.trim() : '*';
81
+ const indices = await reportService.listIndices(dsKey, pattern);
82
+ return { connections, dataSourceKey: dsKey, indices };
83
+ },
84
+ },
85
+ {
86
+ name: 'es_list_data_views',
87
+ title: 'List Elasticsearch Data Views',
88
+ description:
89
+ 'List configured Elasticsearch Data Views (index patterns + time fields) used as the foundation for Kibana-style reports.',
90
+ defaultPermission: 'ALLOW',
91
+ inputSchema: {
92
+ type: 'object',
93
+ properties: {},
94
+ },
95
+ async execute(_args, ctx) {
96
+ assertAuthenticated(ctx);
97
+ const dataViews = await reportService.listDataViews();
98
+ return {
99
+ dataViews: dataViews.filter((dv) => canAccessDataView(app, ctx, dv)),
100
+ };
101
+ },
102
+ },
103
+ {
104
+ name: 'es_upsert_data_view',
105
+ title: 'Create or Update Elasticsearch Data View',
106
+ description:
107
+ 'Create or update an Elasticsearch Data View over an existing Elasticsearch dataSourceKey and indexPattern (e.g. "logs-*", "orders-*"), automatically introspecting field capabilities via _field_caps.',
108
+ defaultPermission: 'ALLOW',
109
+ inputSchema: {
110
+ type: 'object',
111
+ required: ['title', 'dataSourceKey', 'indexPattern'],
112
+ properties: {
113
+ id: {
114
+ type: ['number', 'string'],
115
+ description: 'Optional existing dataViewId to update.',
116
+ },
117
+ title: {
118
+ type: 'string',
119
+ description: 'Human-readable Data View title.',
120
+ },
121
+ dataSourceKey: {
122
+ type: 'string',
123
+ description: 'Key of an Elasticsearch connection from es_list_connections.',
124
+ },
125
+ indexPattern: {
126
+ type: 'string',
127
+ description: 'Elasticsearch index or wildcard pattern, such as "logs-*" or "events-*".',
128
+ },
129
+ timeField: {
130
+ type: 'string',
131
+ description: 'Optional primary date field (e.g. "@timestamp"). Auto-detected if omitted.',
132
+ },
133
+ description: {
134
+ type: 'string',
135
+ description: 'Optional description of the dataset.',
136
+ },
137
+ allowedRoles: {
138
+ type: 'array',
139
+ items: { type: 'string' },
140
+ description:
141
+ 'Optional role names allowed to access this Data View (empty means all authenticated viewers).',
142
+ },
143
+ },
144
+ },
145
+ async execute(args, ctx) {
146
+ assertCanManageReports(app, ctx);
147
+ const dataView = await reportService.upsertDataView(
148
+ {
149
+ ...(args.id !== undefined ? { id: requireId(args.id, 'id') } : {}),
150
+ title: typeof args.title === 'string' ? args.title : '',
151
+ dataSourceKey: typeof args.dataSourceKey === 'string' ? args.dataSourceKey : '',
152
+ indexPattern: typeof args.indexPattern === 'string' ? args.indexPattern : '',
153
+ timeField: typeof args.timeField === 'string' ? args.timeField : null,
154
+ description: typeof args.description === 'string' ? args.description : null,
155
+ ...(args.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(args.allowedRoles) } : {}),
156
+ },
157
+ extractCurrentUserId(ctx),
158
+ );
159
+ return {
160
+ dataView,
161
+ fieldCount: dataView.cachedFields?.length ?? 0,
162
+ };
163
+ },
164
+ },
165
+ {
166
+ name: 'es_inspect_fields',
167
+ title: 'Inspect Data View Field Capabilities',
168
+ description:
169
+ 'Inspect Elasticsearch field capabilities (_field_caps) for a Data View: field types, searchable/aggregatable flags, and .keyword subfields. ALWAYS call this before previewing or saving a report so you never guess field names or sort/group on non-aggregatable text fields.',
170
+ defaultPermission: 'ALLOW',
171
+ inputSchema: {
172
+ type: 'object',
173
+ required: ['dataViewId'],
174
+ properties: {
175
+ dataViewId: {
176
+ type: ['number', 'string'],
177
+ description: 'Target Data View ID from es_list_data_views.',
178
+ },
179
+ refresh: {
180
+ type: 'boolean',
181
+ description: 'Set true to re-fetch live _field_caps from Elasticsearch instead of cached metadata.',
182
+ },
183
+ },
184
+ },
185
+ async execute(args, ctx) {
186
+ assertAuthenticated(ctx);
187
+ const dataViewId = requireId(args.dataViewId, 'dataViewId');
188
+ const refresh = args.refresh === true;
189
+ if (refresh) {
190
+ assertCanManageReports(app, ctx);
191
+ } else {
192
+ const dv = await reportService.getDataView(dataViewId);
193
+ assertCanAccessDataView(app, ctx, dv);
194
+ }
195
+ const { dataView, fields } = await reportService.inspectDataViewFields(dataViewId, refresh);
196
+ return {
197
+ dataView: {
198
+ id: dataView.id,
199
+ title: dataView.title,
200
+ dataSourceKey: dataView.dataSourceKey,
201
+ indexPattern: dataView.indexPattern,
202
+ timeField: dataView.timeField,
203
+ },
204
+ fields,
205
+ };
206
+ },
207
+ },
208
+ {
209
+ name: 'es_preview_report',
210
+ title: 'Preview Elasticsearch Report Query',
211
+ description:
212
+ 'Execute a read-only preview of a Kibana-style ReportSpec (table, bar, line, area, pie, or metric) against Elasticsearch (capped at 20 sample rows) to verify total hits, aggregations, filters, KQL search, and sorting before saving.',
213
+ defaultPermission: 'ALLOW',
214
+ inputSchema: {
215
+ type: 'object',
216
+ required: ['dataViewId', 'spec'],
217
+ properties: {
218
+ dataViewId: {
219
+ type: ['number', 'string'],
220
+ description: 'Target Data View ID.',
221
+ },
222
+ spec: {
223
+ type: 'object',
224
+ description: 'Declarative ReportSpec configuration.',
225
+ required: ['visualization'],
226
+ properties: {
227
+ visualization: {
228
+ type: 'string',
229
+ enum: ['table', 'bar', 'line', 'area', 'pie', 'metric'],
230
+ },
231
+ query: {
232
+ type: 'string',
233
+ description: 'KQL search expression, e.g. \'status >= 500 AND service: "checkout"\'.',
234
+ },
235
+ queryMode: {
236
+ type: 'string',
237
+ enum: ['kql', 'simple'],
238
+ },
239
+ filters: {
240
+ type: 'array',
241
+ items: {
242
+ type: 'object',
243
+ required: ['field', 'operator'],
244
+ properties: {
245
+ field: { type: 'string' },
246
+ operator: {
247
+ type: 'string',
248
+ enum: [
249
+ 'eq',
250
+ 'ne',
251
+ 'in',
252
+ 'not_in',
253
+ 'gt',
254
+ 'gte',
255
+ 'lt',
256
+ 'lte',
257
+ 'between',
258
+ 'contains',
259
+ 'exists',
260
+ 'not_exists',
261
+ ],
262
+ },
263
+ value: {},
264
+ valueTo: {},
265
+ },
266
+ },
267
+ },
268
+ lockedFilters: {
269
+ type: 'array',
270
+ description:
271
+ 'Mandatory server-enforced filters (e.g. tenant or department isolation) that viewer interactive overrides can never remove or replace.',
272
+ items: {
273
+ type: 'object',
274
+ required: ['field', 'operator'],
275
+ properties: {
276
+ field: { type: 'string' },
277
+ operator: {
278
+ type: 'string',
279
+ enum: [
280
+ 'eq',
281
+ 'ne',
282
+ 'in',
283
+ 'not_in',
284
+ 'gt',
285
+ 'gte',
286
+ 'lt',
287
+ 'lte',
288
+ 'between',
289
+ 'contains',
290
+ 'exists',
291
+ 'not_exists',
292
+ ],
293
+ },
294
+ value: {},
295
+ valueTo: {},
296
+ },
297
+ },
298
+ },
299
+ sort: {
300
+ type: 'array',
301
+ items: {
302
+ type: 'object',
303
+ required: ['field', 'order'],
304
+ properties: {
305
+ field: { type: 'string' },
306
+ order: { type: 'string', enum: ['asc', 'desc'] },
307
+ },
308
+ },
309
+ },
310
+ timeRange: {
311
+ type: 'object',
312
+ properties: {
313
+ preset: {
314
+ type: 'string',
315
+ enum: ['last_15m', 'last_1h', 'last_24h', 'last_7d', 'last_30d', 'last_90d', 'all', 'custom'],
316
+ },
317
+ from: { type: 'string' },
318
+ to: { type: 'string' },
319
+ },
320
+ },
321
+ columns: {
322
+ type: 'array',
323
+ items: { type: 'string' },
324
+ },
325
+ pageSize: {
326
+ type: 'number',
327
+ },
328
+ chart: {
329
+ type: 'object',
330
+ properties: {
331
+ bucketType: { type: 'string', enum: ['date_histogram', 'terms'] },
332
+ bucketField: { type: 'string' },
333
+ calendarInterval: {
334
+ type: 'string',
335
+ enum: ['auto', '1m', '5m', '15m', '1h', '1d', '1w', '1M'],
336
+ },
337
+ topN: { type: 'number' },
338
+ metricType: {
339
+ type: 'string',
340
+ enum: ['count', 'sum', 'avg', 'min', 'max', 'cardinality', 'p50', 'p95', 'p99'],
341
+ },
342
+ metricField: { type: 'string' },
343
+ metricLabel: { type: 'string' },
344
+ showHistogram: { type: 'boolean' },
345
+ splitSeriesField: { type: 'string' },
346
+ splitSeriesTopN: { type: 'number' },
347
+ stackMode: { type: 'string', enum: ['none', 'stacked', 'percent'] },
348
+ comparePreviousPeriod: { type: 'boolean' },
349
+ },
350
+ },
351
+ fieldFormats: {
352
+ type: 'object',
353
+ description:
354
+ 'Optional map of fieldName -> format ("duration_ms" | "bytes" | "percent" | "number" | "status_badge" | "url").',
355
+ },
356
+ allowInteractiveControls: { type: 'boolean' },
357
+ allowExport: { type: 'boolean' },
358
+ },
359
+ },
360
+ },
361
+ },
362
+ async execute(args, ctx) {
363
+ assertCanManageReports(app, ctx);
364
+ const dataViewId = requireId(args.dataViewId, 'dataViewId');
365
+ const { dataView, result } = await reportService.previewReport({
366
+ dataViewId,
367
+ spec: isRecord(args.spec) ? args.spec : { visualization: 'table' },
368
+ forMcp: true,
369
+ userContext: extractServerUserContext(ctx),
370
+ });
371
+ return {
372
+ dataView: {
373
+ id: dataView.id,
374
+ title: dataView.title,
375
+ indexPattern: dataView.indexPattern,
376
+ },
377
+ total: result.total,
378
+ totalRelation: result.totalRelation,
379
+ tookMs: result.tookMs,
380
+ ...(result.timedOut ? { timedOut: true } : {}),
381
+ ...(result.shards ? { shards: result.shards } : {}),
382
+ ...(result.warnings && result.warnings.length > 0 ? { warnings: result.warnings } : {}),
383
+ visualization: result.visualization,
384
+ columns: result.columns,
385
+ sampleRows: result.rows.slice(0, 10),
386
+ series: result.series,
387
+ ...(result.seriesKeys ? { seriesKeys: result.seriesKeys } : {}),
388
+ histogram: result.histogram,
389
+ metricValue: result.metricValue,
390
+ ...(result.previousMetricValue !== undefined ? { previousMetricValue: result.previousMetricValue } : {}),
391
+ ...(result.deltaPercent !== undefined ? { deltaPercent: result.deltaPercent } : {}),
392
+ metricLabel: result.metricLabel,
393
+ compiledDsl: result.compiledDsl,
394
+ };
395
+ },
396
+ },
397
+ {
398
+ name: 'es_save_report',
399
+ title: 'Create or Update Saved Elasticsearch Report',
400
+ description:
401
+ 'Create or update a Saved Elasticsearch Report so users can immediately add an "Elastic Report" block on any NocoBase page and select this report.',
402
+ defaultPermission: 'ALLOW',
403
+ inputSchema: {
404
+ type: 'object',
405
+ required: ['title', 'dataViewId', 'spec'],
406
+ properties: {
407
+ id: {
408
+ type: ['number', 'string'],
409
+ description: 'Optional existing report ID when updating a report.',
410
+ },
411
+ title: {
412
+ type: 'string',
413
+ description: 'Clear report title displayed in the Elastic Report block picker.',
414
+ },
415
+ description: {
416
+ type: 'string',
417
+ description: 'Optional summary explaining what this report measures or filters.',
418
+ },
419
+ dataViewId: {
420
+ type: ['number', 'string'],
421
+ description: 'Target Data View ID.',
422
+ },
423
+ published: {
424
+ type: 'boolean',
425
+ description:
426
+ 'Publish for selection in blocks. Defaults to true for new reports. Omit to retain the current state on update.',
427
+ },
428
+ allowedRoles: {
429
+ type: 'array',
430
+ items: { type: 'string' },
431
+ description: 'Optional role names allowed to view/run this report (empty means all authenticated viewers).',
432
+ },
433
+ spec: {
434
+ type: 'object',
435
+ description: 'Validated ReportSpec object (same schema as es_preview_report.spec).',
436
+ },
437
+ },
438
+ },
439
+ async execute(args, ctx) {
440
+ assertCanManageReports(app, ctx);
441
+ const saved = await reportService.saveReport(
442
+ {
443
+ ...(args.id !== undefined ? { id: requireId(args.id, 'id') } : {}),
444
+ title: typeof args.title === 'string' ? args.title : '',
445
+ ...(typeof args.description === 'string' ? { description: args.description } : {}),
446
+ dataViewId: requireId(args.dataViewId, 'dataViewId'),
447
+ ...(typeof args.published === 'boolean' ? { published: args.published } : {}),
448
+ ...(args.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(args.allowedRoles) } : {}),
449
+ spec: isRecord(args.spec) ? args.spec : { visualization: 'table' },
450
+ },
451
+ extractCurrentUserId(ctx),
452
+ );
453
+ return {
454
+ report: saved,
455
+ usageHint: app.i18n.t(saved.published ? 'Published report ready for blocks' : 'Draft saved in Settings', {
456
+ ns: 'plugin-elastic-report',
457
+ }),
458
+ };
459
+ },
460
+ },
461
+ {
462
+ name: 'es_list_reports',
463
+ title: 'List Saved Elasticsearch Reports',
464
+ description:
465
+ 'List Saved Elasticsearch Reports (or filter by title keyword) to inspect or refine existing reports.',
466
+ defaultPermission: 'ALLOW',
467
+ inputSchema: {
468
+ type: 'object',
469
+ properties: {
470
+ search: {
471
+ type: 'string',
472
+ description: 'Optional keyword to filter reports by title.',
473
+ },
474
+ reportId: {
475
+ type: ['number', 'string'],
476
+ description: 'Optional specific reportId to retrieve full report spec.',
477
+ },
478
+ },
479
+ },
480
+ async execute(args, ctx) {
481
+ assertAuthenticated(ctx);
482
+ const isManager = canManageReports(app, ctx);
483
+ if (args.reportId !== undefined && args.reportId !== null && String(args.reportId).trim() !== '') {
484
+ const report = await reportService.getReport(requireId(args.reportId, 'reportId'));
485
+ const dataView = report.dataView ?? (await reportService.getDataView(report.dataViewId));
486
+ assertCanAccessReport(app, ctx, report, dataView);
487
+ return { report };
488
+ }
489
+ const reports = await reportService.listReports({
490
+ publishedOnly: !isManager,
491
+ search: typeof args.search === 'string' ? args.search : undefined,
492
+ });
493
+ return {
494
+ reports: reports.filter((r) => canAccessReport(app, ctx, r, r.dataView)),
495
+ };
496
+ },
497
+ },
498
+ {
499
+ name: 'es_analyze_report',
500
+ title: 'Execute & Analyze Saved Elasticsearch Report (Viewer-Safe)',
501
+ description:
502
+ "Execute a published Saved Elasticsearch Report under the caller's effective NocoBase role and mandatory server lockedFilters, optionally narrowing with KQL or timeRange overrides, to summarize anomalies, top buckets, KPI deltas, or sample logs.",
503
+ defaultPermission: 'ALLOW',
504
+ inputSchema: {
505
+ type: 'object',
506
+ required: ['reportId'],
507
+ properties: {
508
+ reportId: {
509
+ type: ['number', 'string'],
510
+ description: 'ID of the Saved Report from es_list_reports.',
511
+ },
512
+ query: {
513
+ type: 'string',
514
+ description: 'Optional KQL override when the report allows interactive controls.',
515
+ },
516
+ timePreset: {
517
+ type: 'string',
518
+ enum: ['last_15m', 'last_1h', 'last_24h', 'last_7d', 'last_30d', 'last_90d', 'all'],
519
+ description: 'Optional time preset override.',
520
+ },
521
+ },
522
+ },
523
+ async execute(args, ctx) {
524
+ assertAuthenticated(ctx);
525
+ const reportId = requireId(args.reportId, 'reportId');
526
+ const report = await reportService.getReport(reportId);
527
+ const dataView = report.dataView ?? (await reportService.getDataView(report.dataViewId));
528
+ assertCanAccessReport(app, ctx, report, dataView);
529
+
530
+ const overrides: ReportRuntimeOverrides = {};
531
+ if (typeof args.query === 'string') {
532
+ overrides.query = args.query;
533
+ }
534
+ if (typeof args.timePreset === 'string' && args.timePreset.trim()) {
535
+ overrides.timeRange = {
536
+ preset: args.timePreset as NonNullable<ReportRuntimeOverrides['timeRange']>['preset'],
537
+ };
538
+ }
539
+
540
+ const { result } = await reportService.runSavedReport({
541
+ reportId,
542
+ overrides: Object.keys(overrides).length > 0 ? overrides : undefined,
543
+ requirePublished: false,
544
+ forMcp: true,
545
+ userContext: extractServerUserContext(ctx),
546
+ });
547
+
548
+ return {
549
+ report: {
550
+ id: report.id,
551
+ title: report.title,
552
+ visualization: report.visualization,
553
+ dataViewTitle: dataView.title,
554
+ indexPattern: dataView.indexPattern,
555
+ },
556
+ total: result.total,
557
+ totalRelation: result.totalRelation,
558
+ tookMs: result.tookMs,
559
+ ...(result.warnings ? { warnings: result.warnings } : {}),
560
+ metricLabel: result.metricLabel,
561
+ metricValue: result.metricValue,
562
+ ...(result.previousMetricValue !== undefined ? { previousMetricValue: result.previousMetricValue } : {}),
563
+ ...(result.deltaPercent !== undefined ? { deltaPercent: result.deltaPercent } : {}),
564
+ series: result.series.slice(0, 15),
565
+ ...(result.seriesKeys ? { seriesKeys: result.seriesKeys } : {}),
566
+ histogram: result.histogram.slice(0, 24),
567
+ sampleRows: result.rows.slice(0, 15).map((r) => r.source),
568
+ };
569
+ },
570
+ },
571
+ {
572
+ name: 'es_create_dashboard_bundle',
573
+ title: 'Create Multi-Panel Elasticsearch Dashboard Bundle',
574
+ description:
575
+ 'Create a coordinated set of Saved Elasticsearch Reports (e.g. KPI with previous-period delta, trend line/area chart, stacked/grouped breakdown bar chart, and Discover table) sharing common Data View, lockedFilters, and allowedRoles, ready to combine with an Elastic Filter Bar on a NocoBase page.',
576
+ defaultPermission: 'ALLOW',
577
+ inputSchema: {
578
+ type: 'object',
579
+ required: ['dataViewId', 'panels'],
580
+ properties: {
581
+ dataViewId: {
582
+ type: ['number', 'string'],
583
+ description: 'Target Data View ID.',
584
+ },
585
+ allowedRoles: {
586
+ type: 'array',
587
+ items: { type: 'string' },
588
+ description: 'Optional role names applied to every report in the bundle.',
589
+ },
590
+ lockedFilters: {
591
+ type: 'array',
592
+ description: 'Optional mandatory server-enforced filters applied to every report in the bundle.',
593
+ items: {
594
+ type: 'object',
595
+ required: ['field', 'operator'],
596
+ properties: {
597
+ field: { type: 'string' },
598
+ operator: { type: 'string' },
599
+ value: {},
600
+ valueTo: {},
601
+ },
602
+ },
603
+ },
604
+ panels: {
605
+ type: 'array',
606
+ minItems: 1,
607
+ maxItems: 8,
608
+ items: {
609
+ type: 'object',
610
+ required: ['title', 'spec'],
611
+ properties: {
612
+ title: { type: 'string' },
613
+ description: { type: 'string' },
614
+ spec: { type: 'object' },
615
+ },
616
+ },
617
+ },
618
+ },
619
+ },
620
+ async execute(args, ctx) {
621
+ assertCanManageReports(app, ctx);
622
+ const dataViewId = requireId(args.dataViewId, 'dataViewId');
623
+ const panels = Array.isArray(args.panels) ? args.panels : [];
624
+ if (panels.length === 0 || panels.length > 8) {
625
+ throw new Error('"panels" must contain between 1 and 8 report definitions');
626
+ }
627
+ const sharedRoles = args.allowedRoles !== undefined ? normalizeRoleList(args.allowedRoles) : undefined;
628
+ const sharedLockedFilters = Array.isArray(args.lockedFilters) ? args.lockedFilters : undefined;
629
+ const userId = extractCurrentUserId(ctx);
630
+
631
+ const createdReports = [];
632
+ for (const panel of panels) {
633
+ if (!isRecord(panel)) continue;
634
+ const rawSpec: Record<string, unknown> = isRecord(panel.spec)
635
+ ? { ...panel.spec }
636
+ : { visualization: 'table' };
637
+ if (sharedLockedFilters && !Array.isArray(rawSpec.lockedFilters)) {
638
+ rawSpec.lockedFilters = sharedLockedFilters;
639
+ }
640
+ const saved = await reportService.saveReport(
641
+ {
642
+ title: typeof panel.title === 'string' ? panel.title : 'Dashboard Panel',
643
+ description: typeof panel.description === 'string' ? panel.description : null,
644
+ dataViewId,
645
+ published: true,
646
+ ...(sharedRoles !== undefined ? { allowedRoles: sharedRoles } : {}),
647
+ spec: rawSpec,
648
+ },
649
+ userId,
650
+ );
651
+ createdReports.push({
652
+ id: saved.id,
653
+ title: saved.title,
654
+ visualization: saved.visualization,
655
+ });
656
+ }
657
+
658
+ return {
659
+ createdCount: createdReports.length,
660
+ reports: createdReports,
661
+ usageHint:
662
+ 'Add an "Elastic Filter Bar" block at the top of a NocoBase /v/ page, then add an "Elastic Report" block for each created report so all panels cross-filter together.',
663
+ };
664
+ },
665
+ },
666
+ ];
667
+ }