farseer-cli 1.0.8 → 1.0.10

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 (41) hide show
  1. package/dist/commands/app.js +377 -0
  2. package/dist/commands/apps.js +91 -0
  3. package/dist/commands/checkout.js +164 -0
  4. package/dist/commands/config.js +141 -0
  5. package/dist/commands/diff.js +210 -0
  6. package/dist/commands/dimensions.js +130 -0
  7. package/dist/commands/files.js +88 -0
  8. package/dist/commands/install.js +82 -0
  9. package/dist/commands/list.js +77 -0
  10. package/dist/commands/login.js +109 -0
  11. package/dist/commands/logout.js +44 -0
  12. package/dist/commands/mcp-server.js +26 -0
  13. package/dist/commands/model.js +181 -0
  14. package/dist/commands/pull.js +286 -0
  15. package/dist/commands/push.js +235 -0
  16. package/dist/commands/run.js +336 -0
  17. package/dist/commands/status.js +178 -0
  18. package/dist/commands/variables.js +200 -0
  19. package/dist/commands/whoami.js +47 -0
  20. package/dist/index.js +163 -0
  21. package/dist/mcp/index.js +19 -0
  22. package/dist/mcp/prompts/workflows.js +403 -0
  23. package/dist/mcp/resources/documentation.js +158 -0
  24. package/dist/mcp/server.js +36 -0
  25. package/dist/mcp/tools/appTools.js +348 -0
  26. package/dist/mcp/tools/authTools.js +152 -0
  27. package/dist/mcp/tools/dataTools.js +358 -0
  28. package/dist/mcp/tools/modelTools.js +293 -0
  29. package/dist/mcp/tools/runTools.js +239 -0
  30. package/dist/mcp/tools/syncTools.js +383 -0
  31. package/dist/mcp/utils/helpers.js +142 -0
  32. package/dist/services/appSyncService.js +458 -0
  33. package/dist/services/configService.js +186 -0
  34. package/dist/services/farseerApi.js +426 -0
  35. package/dist/services/farseerFactory.js +297 -0
  36. package/dist/services/farseerService.js +647 -0
  37. package/dist/services/syncService.js +764 -0
  38. package/dist/utils/constants.js +21 -0
  39. package/dist/utils/helpers.js +446 -0
  40. package/dist/utils/logger.js +45 -0
  41. package/package.json +8 -1
@@ -0,0 +1,358 @@
1
+ "use strict";
2
+ /**
3
+ * Data Operation Tools
4
+ *
5
+ * MCP tools for data export, import jobs, and file management on Farseer instances.
6
+ * These use the native farseer-client for full API access.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.registerDataTools = registerDataTools;
10
+ const zod_1 = require("zod");
11
+ const farseerFactory_1 = require("../../services/farseerFactory");
12
+ const helpers_1 = require("../utils/helpers");
13
+ async function extractErrorMessage(error) {
14
+ if (error instanceof Error)
15
+ return error.message;
16
+ if (error && typeof error === 'object' && 'status' in error && 'statusText' in error) {
17
+ const resp = error;
18
+ const body = resp.text ? await resp.text() : '';
19
+ return `HTTP ${resp.status} ${resp.statusText}${body ? ': ' + body : ''}`;
20
+ }
21
+ return String(error);
22
+ }
23
+ // Define schemas outside of tool registration to avoid deep type instantiation
24
+ const exportVariableDataSchema = {
25
+ organisation: zod_1.z
26
+ .string()
27
+ .optional()
28
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
29
+ tenant: zod_1.z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),
30
+ variableName: zod_1.z.string().describe('Name of the variable to export'),
31
+ format: zod_1.z.enum(['csv', 'json']).optional().describe('Output format (default: csv)'),
32
+ limit: zod_1.z.number().optional().describe('Maximum number of rows to return'),
33
+ };
34
+ const loadVariableDataSchema = {
35
+ organisation: zod_1.z
36
+ .string()
37
+ .optional()
38
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
39
+ tenant: zod_1.z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),
40
+ variableName: zod_1.z.string().describe('Name of the variable to load'),
41
+ dimensions: zod_1.z.array(zod_1.z.string()).optional().describe('Dimension table names to include as columns in the export'),
42
+ };
43
+ const createImportJobSchema = {
44
+ organisation: zod_1.z
45
+ .string()
46
+ .optional()
47
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
48
+ tenant: zod_1.z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),
49
+ title: zod_1.z.string().describe('Import job title (shown in import history)'),
50
+ columns: zod_1.z
51
+ .array(zod_1.z.object({
52
+ type: zod_1.z.enum(['DIMENSION_TABLE', 'VARIABLE', 'DATE', 'DESCRIPTION']).describe('Column type'),
53
+ dimensionTableName: zod_1.z.string().optional().describe('For DIMENSION_TABLE: name of the dimension table'),
54
+ variableName: zod_1.z.string().optional().describe('For VARIABLE: name of the variable'),
55
+ columnName: zod_1.z.string().optional().describe('Column header name'),
56
+ dateFormat: zod_1.z.string().optional().describe('For DATE: date format string'),
57
+ dimensionsNames: zod_1.z
58
+ .array(zod_1.z.object({
59
+ tableName: zod_1.z.string(),
60
+ memberName: zod_1.z.string(),
61
+ }))
62
+ .optional()
63
+ .describe('For VARIABLE: fixed dimension members (filters) for this variable column'),
64
+ }))
65
+ .describe('Column definitions matching the data structure'),
66
+ rows: zod_1.z
67
+ .array(zod_1.z.array(zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.null()])))
68
+ .describe('Data rows - each row is an array of values matching column order'),
69
+ labels: zod_1.z
70
+ .array(zod_1.z.string())
71
+ .optional()
72
+ .describe('Labels for grouping import jobs (used by undoPrevious to revert jobs with same labels)'),
73
+ undoPrevious: zod_1.z
74
+ .boolean()
75
+ .optional()
76
+ .describe('Revert previous import jobs with the same labels before committing (default: false)'),
77
+ importDimensions: zod_1.z
78
+ .boolean()
79
+ .optional()
80
+ .describe('Auto-create any missing dimension members before committing (default: false)'),
81
+ overwriteCells: zod_1.z
82
+ .boolean()
83
+ .optional()
84
+ .describe('Overwrite existing cell values (default: false - adds to existing values)'),
85
+ };
86
+ const createFileSchema = {
87
+ organisation: zod_1.z
88
+ .string()
89
+ .optional()
90
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
91
+ tenant: zod_1.z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),
92
+ fileName: zod_1.z.string().describe('Name of the file to create or update'),
93
+ folderPath: zod_1.z
94
+ .array(zod_1.z.string())
95
+ .optional()
96
+ .describe('Folder path as array (e.g., ["Files", "Reports"]). Default: ["Files"]'),
97
+ content: zod_1.z.string().describe('File content as text string'),
98
+ };
99
+ function registerDataTools(server) {
100
+ // farseer_export_variable_data - Export variable data
101
+ server.tool('farseer_export_variable_data', `Export data from a Farseer variable as CSV or JSON.
102
+
103
+ Uses the ExportApi.exportFormula() method to export variable data.
104
+ The variable name is passed as the formula, and the result contains
105
+ all data cells for that variable across all its dimensions.
106
+
107
+ Returns the raw CSV/JSON text inline so you can analyze it directly.
108
+
109
+ Use the 'limit' parameter to restrict row count for large variables.
110
+
111
+ If no tenant is specified, uses the currently checked-out tenant.`, exportVariableDataSchema,
112
+ // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas
113
+ async (params) => {
114
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
115
+ if (!resolved) {
116
+ return (0, helpers_1.tenantRequiredResponse)();
117
+ }
118
+ const { organisation, tenant } = resolved;
119
+ const nativeClient = await (0, farseerFactory_1.getNativeFarseerClient)(organisation, tenant);
120
+ if (!nativeClient) {
121
+ return (0, helpers_1.authRequiredResponse)(tenant);
122
+ }
123
+ try {
124
+ const exportRequest = {
125
+ formula: params.variableName,
126
+ format: params.format || 'csv',
127
+ };
128
+ if (params.limit) {
129
+ exportRequest.limit = params.limit;
130
+ }
131
+ const blob = await nativeClient.export.exportFormula(exportRequest);
132
+ const text = await blob.text();
133
+ const lines = text.split('\n').filter((l) => l.trim()).length;
134
+ return (0, helpers_1.successResponse)({
135
+ tenant,
136
+ variable: params.variableName,
137
+ format: params.format || 'csv',
138
+ rowCount: Math.max(0, lines - 1),
139
+ data: text,
140
+ });
141
+ }
142
+ catch (error) {
143
+ return (0, helpers_1.errorResponse)(`Export variable data failed: ${await extractErrorMessage(error)}`, 'NETWORK_ERROR');
144
+ }
145
+ });
146
+ // farseer_load_variable_data - Load variable data with specific dimensions
147
+ server.tool('farseer_load_variable_data', `Load data from a Farseer variable into a structured CSV format.
148
+
149
+ Uses the ExportApi.exportFormula() method to export variable data as CSV.
150
+ Returns all data cells for the variable across all its dimensions.
151
+
152
+ You can optionally specify which dimensions to include for documentation,
153
+ but the export returns all dimensions by default.
154
+
155
+ Example usage:
156
+ - Load "Revenue" data
157
+ - Load "Revenue" with dimensions ["Product", "Years", "Months"]
158
+
159
+ If no tenant is specified, uses the currently checked-out tenant.`, loadVariableDataSchema,
160
+ // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas
161
+ async (params) => {
162
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
163
+ if (!resolved) {
164
+ return (0, helpers_1.tenantRequiredResponse)();
165
+ }
166
+ const { organisation, tenant } = resolved;
167
+ const nativeClient = await (0, farseerFactory_1.getNativeFarseerClient)(organisation, tenant);
168
+ if (!nativeClient) {
169
+ return (0, helpers_1.authRequiredResponse)(tenant);
170
+ }
171
+ try {
172
+ const blob = await nativeClient.export.exportFormula({
173
+ formula: params.variableName,
174
+ format: 'csv',
175
+ });
176
+ const text = await blob.text();
177
+ const lines = text.split('\n').filter((l) => l.trim()).length;
178
+ const rowCount = Math.max(0, lines - 1);
179
+ return (0, helpers_1.successResponse)({
180
+ tenant,
181
+ variable: params.variableName,
182
+ dimensions: params.dimensions || 'all',
183
+ rowCount,
184
+ data: text,
185
+ });
186
+ }
187
+ catch (error) {
188
+ return (0, helpers_1.errorResponse)(`Load variable data failed: ${await extractErrorMessage(error)}`, 'NETWORK_ERROR');
189
+ }
190
+ });
191
+ // farseer_create_import_job - Create and execute import job
192
+ server.tool('farseer_create_import_job', `Create and execute a complete data import job on a Farseer instance.
193
+
194
+ This tool handles the full import workflow in a single call:
195
+ 1. Builds import metadata from column definitions
196
+ 2. Creates the import job
197
+ 3. Adds all data rows
198
+ 4. Optionally creates missing dimension members (importDimensions)
199
+ 5. Optionally reverts previous imports with same labels (undoPrevious)
200
+ 6. Commits the import
201
+
202
+ Column types:
203
+ - DIMENSION_TABLE: Maps to a dimension table (e.g., Product, Years, Months)
204
+ - VARIABLE: Maps to a variable that will receive data values
205
+ - Can include dimensionsNames to fix specific dimension members for this column
206
+ - DATE: Date column with format string
207
+ - DESCRIPTION: Cell description/comment
208
+
209
+ The 'labels' parameter is important for the undoPrevious feature:
210
+ when undoPrevious is true, all previously committed imports with the
211
+ same labels will be reverted before this import is committed.
212
+ This is useful for idempotent re-imports.
213
+
214
+ The 'overwriteCells' parameter controls whether existing values are
215
+ overwritten (true) or accumulated (false, default).
216
+
217
+ Example columns for importing revenue data:
218
+ [
219
+ { "type": "DIMENSION_TABLE", "dimensionTableName": "Product" },
220
+ { "type": "DIMENSION_TABLE", "dimensionTableName": "Years" },
221
+ { "type": "DIMENSION_TABLE", "dimensionTableName": "Months" },
222
+ { "type": "VARIABLE", "variableName": "Revenue",
223
+ "dimensionsNames": [
224
+ { "tableName": "Versions", "memberName": "Actual" }
225
+ ]
226
+ }
227
+ ]
228
+
229
+ If no tenant is specified, uses the currently checked-out tenant.`, createImportJobSchema,
230
+ // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas
231
+ async (params) => {
232
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
233
+ if (!resolved) {
234
+ return (0, helpers_1.tenantRequiredResponse)();
235
+ }
236
+ const { organisation, tenant } = resolved;
237
+ const nativeClient = await (0, farseerFactory_1.getNativeFarseerClient)(organisation, tenant);
238
+ if (!nativeClient) {
239
+ return (0, helpers_1.authRequiredResponse)(tenant);
240
+ }
241
+ try {
242
+ await nativeClient.initTagMap();
243
+ const { title, columns, rows, labels, undoPrevious = false, importDimensions = false, overwriteCells = false, } = params;
244
+ // Build metadata columns
245
+ const metadataColumns = columns.map((col) => {
246
+ switch (col.type) {
247
+ case 'DIMENSION_TABLE':
248
+ return {
249
+ type: 'DIMENSION_TABLE',
250
+ dimensionTableName: col.dimensionTableName,
251
+ columnName: col.columnName,
252
+ };
253
+ case 'VARIABLE':
254
+ return {
255
+ type: 'VARIABLE',
256
+ variableName: col.variableName,
257
+ columnName: col.columnName || col.variableName,
258
+ dimensionsNames: col.dimensionsNames,
259
+ };
260
+ case 'DATE':
261
+ return {
262
+ type: 'DATE',
263
+ dateFormat: col.dateFormat,
264
+ columnName: col.columnName,
265
+ };
266
+ case 'DESCRIPTION':
267
+ return {
268
+ type: 'DESCRIPTION',
269
+ columnName: col.columnName,
270
+ };
271
+ default:
272
+ return {
273
+ type: 'NONE',
274
+ columnName: col.columnName,
275
+ };
276
+ }
277
+ });
278
+ // Build metadata
279
+ const metadata = await nativeClient.buildImportJobMetadata(metadataColumns);
280
+ if (overwriteCells) {
281
+ metadata.overwriteCells = true;
282
+ }
283
+ // Create import job
284
+ const importActions = await nativeClient.createImportJob({
285
+ title,
286
+ metadata,
287
+ labels,
288
+ });
289
+ // Add rows
290
+ await importActions.addRows(rows);
291
+ await importActions.flushRows();
292
+ // Import dimensions if needed
293
+ if (importDimensions) {
294
+ await importActions.importDimensions();
295
+ }
296
+ // Undo previous if needed
297
+ if (undoPrevious) {
298
+ await importActions.undoPrevious();
299
+ }
300
+ // Commit
301
+ const report = await importActions.commit();
302
+ return (0, helpers_1.successResponse)({
303
+ tenant,
304
+ title,
305
+ rowCount: rows.length,
306
+ labels: labels || [],
307
+ undoPrevious,
308
+ importDimensions,
309
+ overwriteCells,
310
+ commitReport: report,
311
+ });
312
+ }
313
+ catch (error) {
314
+ return (0, helpers_1.errorResponse)(`Import job failed: ${await extractErrorMessage(error)}`, 'NETWORK_ERROR');
315
+ }
316
+ });
317
+ // farseer_create_file - Create or update file on instance
318
+ server.tool('farseer_create_file', `Create or update a file on a Farseer instance.
319
+
320
+ This creates a file in the specified folder on the Farseer file system.
321
+ If a file with the same name already exists in that folder, it will be updated.
322
+
323
+ The folderPath is an array of folder names, starting from the root.
324
+ Default is ["Files"] which is the standard files folder.
325
+
326
+ Common use cases:
327
+ - Creating CSV report files
328
+ - Uploading configuration files
329
+ - Saving processed data outputs
330
+
331
+ If no tenant is specified, uses the currently checked-out tenant.`, createFileSchema, async (params) => {
332
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
333
+ if (!resolved) {
334
+ return (0, helpers_1.tenantRequiredResponse)();
335
+ }
336
+ const { organisation, tenant } = resolved;
337
+ const nativeClient = await (0, farseerFactory_1.getNativeFarseerClient)(organisation, tenant);
338
+ if (!nativeClient) {
339
+ return (0, helpers_1.authRequiredResponse)(tenant);
340
+ }
341
+ try {
342
+ const folderPath = params.folderPath || ['Files'];
343
+ const folder = await nativeClient.getItemByPath(folderPath);
344
+ const buffer = Buffer.from(params.content, 'utf-8');
345
+ await nativeClient.createOrUpdateFarseerFile({ name: params.fileName, folderId: folder.id }, buffer);
346
+ return (0, helpers_1.successResponse)({
347
+ tenant,
348
+ fileName: params.fileName,
349
+ folderPath,
350
+ size: buffer.length,
351
+ message: `File "${params.fileName}" created/updated in ${folderPath.join('/')}`,
352
+ });
353
+ }
354
+ catch (error) {
355
+ return (0, helpers_1.errorResponse)(`Create file failed: ${await extractErrorMessage(error)}`, 'NETWORK_ERROR');
356
+ }
357
+ });
358
+ }
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ /**
3
+ * Model Inspection Tools
4
+ *
5
+ * Tools for exploring Farseer data models (dimensions, variables, formulas).
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.registerModelTools = registerModelTools;
9
+ const zod_1 = require("zod");
10
+ const farseerFactory_1 = require("../../services/farseerFactory");
11
+ const helpers_1 = require("../utils/helpers");
12
+ // Define schemas outside of tool registration to avoid deep type instantiation
13
+ const exportModelSchema = {
14
+ tenant: zod_1.z.string().optional().describe('Tenant ID (e.g. "salvus-prodaja"). Uses checked-out tenant if omitted.'),
15
+ organisation: zod_1.z
16
+ .string()
17
+ .optional()
18
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
19
+ };
20
+ const listTablesSchema = {
21
+ tenant: zod_1.z.string().optional().describe('Tenant ID (e.g. "salvus-prodaja"). Uses checked-out tenant if omitted.'),
22
+ organisation: zod_1.z
23
+ .string()
24
+ .optional()
25
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
26
+ };
27
+ const listVariablesSchema = {
28
+ tenant: zod_1.z.string().optional().describe('Tenant ID (e.g. "salvus-prodaja"). Uses checked-out tenant if omitted.'),
29
+ organisation: zod_1.z
30
+ .string()
31
+ .optional()
32
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
33
+ };
34
+ const getTableSchema = {
35
+ organisation: zod_1.z
36
+ .string()
37
+ .optional()
38
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
39
+ tenant: zod_1.z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),
40
+ tableName: zod_1.z.string().describe('Name of the dimension table'),
41
+ };
42
+ const getVariableSchema = {
43
+ organisation: zod_1.z
44
+ .string()
45
+ .optional()
46
+ .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),
47
+ tenant: zod_1.z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),
48
+ variableName: zod_1.z.string().describe('Name of the variable'),
49
+ };
50
+ function registerModelTools(server) {
51
+ // farseer_export_model - Export complete model
52
+ server.tool('farseer_export_model', `Export the complete data model structure from a Farseer tenant.
53
+
54
+ Returns:
55
+ - All dimension tables with member counts and foreign key relationships
56
+ - All variables with their dimensions, formulas, and roll-up types
57
+
58
+ This is essential for understanding a tenant's data structure before writing import scripts.
59
+
60
+ The model export can be large for complex tenants. Use farseer_list_tables or
61
+ farseer_list_variables for a summary view.
62
+
63
+ If no tenant is specified, uses the currently checked-out tenant.`, exportModelSchema, async (params) => {
64
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
65
+ if (!resolved) {
66
+ return (0, helpers_1.tenantRequiredResponse)();
67
+ }
68
+ const { organisation, tenant } = resolved;
69
+ const clientResult = await (0, farseerFactory_1.getFarseerClientWithFallback)(organisation, tenant);
70
+ if (!clientResult) {
71
+ return (0, helpers_1.authRequiredResponse)(tenant);
72
+ }
73
+ try {
74
+ const model = await clientResult.client.exportModel();
75
+ // Process tables
76
+ const tables = model.tables.map((t) => ({
77
+ name: t.name,
78
+ memberCount: t.rows?.length || 0,
79
+ columns: t.columns.map((c) => ({
80
+ type: c.type,
81
+ name: c.name,
82
+ foreignKeyTable: c.foreignKeyTableName,
83
+ })),
84
+ foreignKeys: t.columns.filter((c) => c.type === 'FOREIGN_KEY').map((c) => c.foreignKeyTableName),
85
+ folderPath: t.folderPath,
86
+ }));
87
+ // Process variables
88
+ const variables = model.variables.map((v) => ({
89
+ name: v.name,
90
+ dimensions: v.tables || [],
91
+ formula: v.formula || undefined,
92
+ rollupType: v.rollupType,
93
+ numberFormat: v.numberFormat,
94
+ readonly: v.readonly,
95
+ calculateOnDemand: v.calculateOnDemand,
96
+ folderPath: v.folderPath,
97
+ }));
98
+ return (0, helpers_1.successResponse)({
99
+ tenant,
100
+ summary: {
101
+ tableCount: tables.length,
102
+ variableCount: variables.length,
103
+ },
104
+ tables,
105
+ variables,
106
+ });
107
+ }
108
+ catch (error) {
109
+ return (0, helpers_1.errorResponse)(`Export model failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 'NETWORK_ERROR');
110
+ }
111
+ });
112
+ // farseer_list_tables - List dimension tables
113
+ server.tool('farseer_list_tables', `List all dimension tables in a Farseer tenant model.
114
+
115
+ Dimension tables define the structure of data:
116
+ - Product, Region, Customer (business dimensions)
117
+ - Months, Years (time dimensions - built-in)
118
+ - Versions (scenario dimension - built-in)
119
+
120
+ Returns table names, member counts, and foreign key relationships.
121
+
122
+ If no tenant is specified, uses the currently checked-out tenant.`, listTablesSchema, async (params) => {
123
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
124
+ if (!resolved) {
125
+ return (0, helpers_1.tenantRequiredResponse)();
126
+ }
127
+ const { organisation, tenant } = resolved;
128
+ const clientResult = await (0, farseerFactory_1.getFarseerClientWithFallback)(organisation, tenant);
129
+ if (!clientResult) {
130
+ return (0, helpers_1.authRequiredResponse)(tenant);
131
+ }
132
+ try {
133
+ const model = await clientResult.client.exportModel();
134
+ const tables = model.tables.map((t) => ({
135
+ name: t.name,
136
+ memberCount: t.rows?.length || 0,
137
+ foreignKeys: t.columns.filter((c) => c.type === 'FOREIGN_KEY').map((c) => c.foreignKeyTableName),
138
+ }));
139
+ // Sort by name
140
+ tables.sort((a, b) => a.name.localeCompare(b.name));
141
+ return (0, helpers_1.successResponse)({
142
+ tenant,
143
+ totalTables: tables.length,
144
+ tables,
145
+ });
146
+ }
147
+ catch (error) {
148
+ return (0, helpers_1.errorResponse)(`List tables failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 'NETWORK_ERROR');
149
+ }
150
+ });
151
+ // farseer_list_variables - List variables
152
+ server.tool('farseer_list_variables', `List all variables defined in a Farseer tenant model.
153
+
154
+ Variables store data and calculations - they are the core of the data model.
155
+
156
+ Each variable has:
157
+ - Dimensions it spans (Product, Region, Month, etc.)
158
+ - Optional formula for calculated values
159
+ - Roll-up type (how values aggregate up hierarchies)
160
+
161
+ If no tenant is specified, uses the currently checked-out tenant.`, listVariablesSchema, async (params) => {
162
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
163
+ if (!resolved) {
164
+ return (0, helpers_1.tenantRequiredResponse)();
165
+ }
166
+ const { organisation, tenant } = resolved;
167
+ const clientResult = await (0, farseerFactory_1.getFarseerClientWithFallback)(organisation, tenant);
168
+ if (!clientResult) {
169
+ return (0, helpers_1.authRequiredResponse)(tenant);
170
+ }
171
+ try {
172
+ const model = await clientResult.client.exportModel();
173
+ const variables = model.variables.map((v) => ({
174
+ name: v.name,
175
+ dimensions: v.tables || [],
176
+ hasFormula: !!v.formula,
177
+ rollupType: v.rollupType,
178
+ readonly: v.readonly,
179
+ }));
180
+ // Sort by name
181
+ variables.sort((a, b) => a.name.localeCompare(b.name));
182
+ return (0, helpers_1.successResponse)({
183
+ tenant,
184
+ totalVariables: variables.length,
185
+ variables,
186
+ });
187
+ }
188
+ catch (error) {
189
+ return (0, helpers_1.errorResponse)(`List variables failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 'NETWORK_ERROR');
190
+ }
191
+ });
192
+ // farseer_get_table - Get dimension table details
193
+ server.tool('farseer_get_table', `Get detailed information about a specific dimension table.
194
+
195
+ Returns:
196
+ - Table columns with their types
197
+ - Foreign key relationships to other tables
198
+ - Sample members (first 20)
199
+ - Total member count
200
+
201
+ This helps understand the structure needed for import scripts.
202
+
203
+ If no tenant is specified, uses the currently checked-out tenant.`, getTableSchema, async (params) => {
204
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
205
+ if (!resolved) {
206
+ return (0, helpers_1.tenantRequiredResponse)();
207
+ }
208
+ const { organisation, tenant } = resolved;
209
+ const clientResult = await (0, farseerFactory_1.getFarseerClientWithFallback)(organisation, tenant);
210
+ if (!clientResult) {
211
+ return (0, helpers_1.authRequiredResponse)(tenant);
212
+ }
213
+ try {
214
+ const model = await clientResult.client.exportModel();
215
+ const table = model.tables.find((t) => t.name.toLowerCase() === params.tableName.toLowerCase());
216
+ if (!table) {
217
+ return (0, helpers_1.errorResponse)(`Table "${params.tableName}" not found`, 'NOT_FOUND');
218
+ }
219
+ // Get sample members (first column is usually the primary key / name)
220
+ const primaryKeyColumn = table.columns.find((c) => c.type === 'PRIMARY_KEY');
221
+ let sampleMembers = [];
222
+ if (table.rows && table.rows.length > 0) {
223
+ const pkIndex = primaryKeyColumn ? table.columns.indexOf(primaryKeyColumn) : 0;
224
+ sampleMembers = table.rows.slice(0, 20).map((row) => String(row[pkIndex]));
225
+ }
226
+ return (0, helpers_1.successResponse)({
227
+ tenant,
228
+ table: {
229
+ name: table.name,
230
+ columns: table.columns.map((c) => ({
231
+ type: c.type,
232
+ name: c.name,
233
+ foreignKeyTable: c.foreignKeyTableName,
234
+ })),
235
+ memberCount: table.rows?.length || 0,
236
+ sampleMembers,
237
+ folderPath: table.folderPath,
238
+ },
239
+ });
240
+ }
241
+ catch (error) {
242
+ return (0, helpers_1.errorResponse)(`Get table failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 'NETWORK_ERROR');
243
+ }
244
+ });
245
+ // farseer_get_variable - Get variable details
246
+ server.tool('farseer_get_variable', `Get detailed information about a specific variable.
247
+
248
+ Returns:
249
+ - Dimensions the variable spans
250
+ - Formula (if calculated)
251
+ - Roll-up type (SUM, AVERAGE, etc.)
252
+ - Data type and format
253
+ - Whether it's readonly or calculated on demand
254
+
255
+ This is essential for understanding what dimensions and values are needed for imports.
256
+
257
+ If no tenant is specified, uses the currently checked-out tenant.`, getVariableSchema, async (params) => {
258
+ const resolved = (0, helpers_1.resolveOrgAndTenant)(params);
259
+ if (!resolved) {
260
+ return (0, helpers_1.tenantRequiredResponse)();
261
+ }
262
+ const { organisation, tenant } = resolved;
263
+ const clientResult = await (0, farseerFactory_1.getFarseerClientWithFallback)(organisation, tenant);
264
+ if (!clientResult) {
265
+ return (0, helpers_1.authRequiredResponse)(tenant);
266
+ }
267
+ try {
268
+ const model = await clientResult.client.exportModel();
269
+ const variable = model.variables.find((v) => v.name.toLowerCase() === params.variableName.toLowerCase());
270
+ if (!variable) {
271
+ return (0, helpers_1.errorResponse)(`Variable "${params.variableName}" not found`, 'NOT_FOUND');
272
+ }
273
+ return (0, helpers_1.successResponse)({
274
+ tenant,
275
+ variable: {
276
+ name: variable.name,
277
+ description: variable.description,
278
+ formula: variable.formula,
279
+ dimensions: variable.tables || [],
280
+ rollupType: variable.rollupType,
281
+ dataType: variable.dataType,
282
+ numberFormat: variable.numberFormat,
283
+ readonly: variable.readonly,
284
+ calculateOnDemand: variable.calculateOnDemand,
285
+ folderPath: variable.folderPath,
286
+ },
287
+ });
288
+ }
289
+ catch (error) {
290
+ return (0, helpers_1.errorResponse)(`Get variable failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 'NETWORK_ERROR');
291
+ }
292
+ });
293
+ }