farseer-cli 1.13.0 → 1.14.1
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.
- package/README.md +23 -8
- package/dist/commands/pipeline.js +158 -0
- package/dist/commands/pipeline.js.map +7 -0
- package/dist/commands/variables.js +17 -8
- package/dist/commands/variables.js.map +2 -2
- package/dist/index.js +40 -46
- package/dist/index.js.map +2 -2
- package/dist/mcp/prompts/workflows.js +13 -68
- package/dist/mcp/prompts/workflows.js.map +2 -2
- package/dist/mcp/resources/documentation.js +14 -0
- package/dist/mcp/resources/documentation.js.map +2 -2
- package/dist/mcp/server.js +14 -2
- package/dist/mcp/server.js.map +2 -2
- package/dist/mcp/skills.js +59 -0
- package/dist/mcp/skills.js.map +7 -0
- package/dist/mcp/tools/appTools.js +4 -0
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +2 -0
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +6 -41
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/pipelineContract.js +317 -0
- package/dist/mcp/tools/pipelineContract.js.map +7 -0
- package/dist/mcp/tools/pipelineTools.js +111 -0
- package/dist/mcp/tools/pipelineTools.js.map +7 -0
- package/dist/mcp/tools/runTools.js +2 -0
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +4 -0
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/pipeline/compatibility.js +53 -0
- package/dist/pipeline/compatibility.js.map +7 -0
- package/dist/pipeline/connect.js +139 -0
- package/dist/pipeline/connect.js.map +7 -0
- package/dist/pipeline/create.js +158 -0
- package/dist/pipeline/create.js.map +7 -0
- package/dist/pipeline/errors.js +45 -0
- package/dist/pipeline/errors.js.map +7 -0
- package/dist/pipeline/generated-reference.json +115 -0
- package/dist/pipeline/guide.js +33 -0
- package/dist/pipeline/guide.js.map +7 -0
- package/dist/pipeline/init.js +204 -0
- package/dist/pipeline/init.js.map +7 -0
- package/dist/pipeline/operations.js +103 -0
- package/dist/pipeline/operations.js.map +7 -0
- package/dist/pipeline/query.js +103 -0
- package/dist/pipeline/query.js.map +7 -0
- package/dist/pipeline/queryWorker.js +119 -0
- package/dist/pipeline/queryWorker.js.map +7 -0
- package/dist/pipeline/readiness.js +55 -0
- package/dist/pipeline/readiness.js.map +7 -0
- package/dist/pipeline/reference.js +72 -0
- package/dist/pipeline/reference.js.map +7 -0
- package/dist/pipeline/requests.js +122 -0
- package/dist/pipeline/requests.js.map +7 -0
- package/dist/pipeline/runArguments.js +68 -0
- package/dist/pipeline/runArguments.js.map +7 -0
- package/dist/pipeline/runtime.js +105 -0
- package/dist/pipeline/runtime.js.map +7 -0
- package/dist/pipeline/service.js +967 -0
- package/dist/pipeline/service.js.map +7 -0
- package/dist/services/agentApprovalFetch.js +86 -0
- package/dist/services/agentApprovalFetch.js.map +7 -0
- package/dist/services/configService.js +29 -0
- package/dist/services/configService.js.map +2 -2
- package/dist/services/credentials.js +2 -0
- package/dist/services/credentials.js.map +2 -2
- package/dist/services/farseerService.js +10 -3
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/preflight.js +4 -0
- package/dist/services/preflight.js.map +2 -2
- package/dist/services/syncService.js +6 -0
- package/dist/services/syncService.js.map +2 -2
- package/dist/skills/pipeline.js +71 -0
- package/dist/skills/pipeline.js.map +7 -0
- package/dist/utils/helpers.js +2 -1
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/variableValues.js +78 -0
- package/dist/utils/variableValues.js.map +7 -0
- package/docs/pipeline-client-guide.md +67 -0
- package/docs/pipeline-reference.md +2064 -0
- package/package.json +5 -1
- package/skills/pipeline-authoring/SKILL.md +95 -0
- package/skills/pipeline-authoring/practices.md +325 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/appTools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * App Management Tools\n *\n * Tools for managing Farseer apps (Remote Jobs).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { requireSession } from '../utils/session';\nimport {\n APP_COMPUTE_CHOICES,\n AppArgument,\n AppDeleteRefusedError,\n AppPredefinedAction,\n AppUpdateChanges,\n CLEAR_SETTING,\n applyRunSettings,\n applySourceFolderChange,\n formatCompute,\n redactActionValues,\n restoreRedactedValues,\n} from '../../services/apps';\nimport { successResponse, errorResponse, resolveAppItemForMcp, resolveAppForMcp } from '../utils/helpers';\nimport { matchByName } from '../../utils/nameResolver';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst listAppsSchema = {\n details: z.boolean().optional().describe('Include full details for each app'),\n};\n\nconst getAppSchema = {\n appName: z.string().optional().describe('Name of the app (can include spaces). Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n};\n\nconst createAppSchema = {\n appName: z.string().describe('Name for the new app'),\n};\n\nexport const argumentSchema = z\n .object({\n name: z.string(),\n dataType: z.enum(['string', 'boolean']).optional().describe('Data type. Defaults to \"string\" if omitted.'),\n fixed: z\n .boolean()\n .optional()\n .describe('Lock the value at run time so users cannot override it (admin sets, user reads only).'),\n options: z\n .array(z.string())\n .optional()\n .describe('Closed allowed-value set. Only meaningful for string dataType.'),\n defaultValue: z.string().optional(),\n secret: z.boolean().optional().describe('Mask the value in inputs and logs.'),\n })\n // Cross-axis checks mirror the backend's `validateExpectedArguments` so an\n // LLM caller gets pre-request feedback. Backend stays authoritative \u2014 these\n // catch the same shapes earlier, they don't replace the validator.\n .refine(\n (a) => a.dataType !== 'boolean' || a.defaultValue === undefined || ['true', 'false'].includes(a.defaultValue),\n {\n message: 'Boolean argument defaultValue must be \"true\" or \"false\"',\n path: ['defaultValue'],\n },\n )\n .refine((a) => !a.options || a.defaultValue === undefined || a.options.includes(a.defaultValue), {\n message: 'defaultValue must be one of the options',\n path: ['defaultValue'],\n });\n\nexport const predefinedActionSchema = z.object({\n name: z.string(),\n runArguments: z.record(z.string()).describe('Argument name to the value this action runs with.'),\n});\n\nconst configureAppSchema = {\n appName: z.string().optional().describe('Name of the app to configure. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n entrypoint: z\n .string()\n .optional()\n .describe('Main script filename \u2014 must be a file in the app\\'s source folder (e.g., \"index.ts\")'),\n sourceFolder: z\n .string()\n .optional()\n .describe('Source folder the app\\'s scripts come from (path under Files/, e.g. \"Scripts/MyApp\")'),\n description: z.string().optional().describe('App description'),\n arguments: z.array(argumentSchema).optional().describe('App arguments with default values'),\n newName: z.string().optional().describe('Rename the app'),\n schedule: z\n .string()\n .optional()\n .describe(`Cron expression to run the app on, e.g. \"0 6 * * *\". Pass \"${CLEAR_SETTING}\" to clear it.`),\n runner: z\n .string()\n .optional()\n .describe(`Name of the jobrunner that runs the app. Pass \"${CLEAR_SETTING}\" to let any runner take it.`),\n runnerImage: z\n .string()\n .optional()\n .describe(\n `Container image the app runs in, as \"<repository>:<tag>\" (e.g. \"runner-typescript:latest\") or a full registry reference. Pass \"${CLEAR_SETTING}\" for the tenant default.`,\n ),\n compute: z\n .enum(APP_COMPUTE_CHOICES as unknown as [string, ...string[]])\n .optional()\n .describe(\n 'Where a run executes: \"local\" is a container on the jobrunner\\'s own machine, \"batch\" a machine created for that run. The size suffix picks how much machine; bare \"batch\" takes the deployment\\'s default size.',\n ),\n predefinedActions: z\n .array(predefinedActionSchema)\n .optional()\n .describe('Named argument presets offered as buttons in the UI. Replaces the existing list wholesale.'),\n};\n\nconst deleteAppSchema = {\n appName: z.string().optional().describe('Name of the app to delete. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n};\n\nexport function registerAppTools(server: McpServer): void {\n // Cast to avoid TS2589 deep type instantiation with MCP SDK + Zod generics\n const s: any = server;\n\n // farseer_list_apps - List all apps\n s.tool(\n 'farseer_list_apps',\n `List all apps (Remote Jobs) configured on a Farseer tenant.\n\nApps are executable script configurations that include:\n- Entry point script\n- List of included scripts\n- Expected arguments with default values\n\nUse details=true to include full information for each app.`,\n listAppsSchema,\n async (params: { details?: boolean }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const appList = await client.listApps();\n\n if (!params.details) {\n return successResponse({\n tenant,\n totalApps: appList.length,\n apps: appList.map((a) => ({\n name: a.name,\n reference: a.reference,\n })),\n });\n }\n\n // Get full details for each app\n const appsWithDetails = [];\n for (const item of appList) {\n const app = await client.getApp(item.reference);\n if (app) {\n const appScripts = app.scriptFiles ?? [];\n const mainScript = appScripts.find((s) => s.id === app.mainScriptFileId);\n appsWithDetails.push({\n name: app.name,\n id: app.id,\n description: app.description || '',\n entrypoint: mainScript?.name || null,\n scripts: appScripts.map((s) => s.name),\n arguments: app.expectedArguments.map((a) => ({\n name: a.name,\n dataType: a.dataType,\n ...(a.fixed !== undefined ? { fixed: a.fixed } : {}),\n ...(a.options !== undefined ? { options: a.options } : {}),\n ...(a.defaultValue !== undefined ? { defaultValue: a.defaultValue } : {}),\n ...(a.secret !== undefined ? { secret: a.secret } : {}),\n })),\n });\n }\n }\n\n return successResponse({\n tenant,\n totalApps: appsWithDetails.length,\n apps: appsWithDetails,\n });\n } catch (error) {\n return errorResponse(`List apps failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_get_app - Get app details\n s.tool(\n 'farseer_get_app',\n `Get detailed information about a specific Farseer app.\n\nReturns:\n- App name and description\n- Entry point script (main script that runs)\n- List of all included scripts\n- Expected arguments with their default values\n- Schedule, runner, runner image and compute selection\n- Predefined actions (named argument presets)`,\n getAppSchema,\n async (params: { appName?: string; appId?: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const resolution = await resolveAppForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const app = resolution.app;\n\n const getAppScripts = app.scriptFiles ?? [];\n const mainScript = getAppScripts.find((s) => s.id === app.mainScriptFileId);\n\n return successResponse({\n tenant,\n app: {\n id: app.id,\n name: app.name,\n description: app.description || '',\n entrypoint: mainScript?.name || null,\n scripts: getAppScripts.map((s) => ({\n id: s.id,\n name: s.name,\n isEntrypoint: s.id === app.mainScriptFileId,\n })),\n arguments: app.expectedArguments.map((a) => ({\n name: a.name,\n dataType: a.dataType,\n ...(a.fixed !== undefined ? { fixed: a.fixed } : {}),\n ...(a.options !== undefined ? { options: a.options } : {}),\n ...(a.defaultValue !== undefined ? { defaultValue: a.defaultValue } : {}),\n ...(a.secret !== undefined ? { secret: a.secret } : {}),\n })),\n status: app.status,\n lastHeartbeat: app.lastHeartbeat,\n schedule: app.schedule ?? null,\n runner: app.runnerName ?? null,\n runnerImage: app.runnerImage ?? null,\n compute: formatCompute(app.compute),\n predefinedActions: redactActionValues(app.predefinedActions ?? [], app.expectedArguments),\n },\n });\n } catch (error) {\n return errorResponse(`Get app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_app - Create new app\n s.tool(\n 'farseer_create_app',\n `Create a new Farseer app.\n\nA Farseer App is a named configuration that points to a TypeScript script and defines its arguments.\nThe script uses farseer-client to interact with the Farseer API (import data, export reports, etc.).\n\nWorkflow to create a new app:\n1. Write the script at farseer-apps/<tenant>/files/Scripts/<name>.ts\n2. Push the script to remote with farseer_push (scripts must exist on remote first)\n3. Create the app with this tool (farseer_create_app)\n4. Configure it with farseer_configure_app (set entrypoint, scripts, arguments)\n5. Run it with farseer_run_app (CLI injects auth credentials automatically)\n\nScripts should use \\`new FarseerClient()\\` with no arguments - credentials are injected via environment variables by the CLI at runtime.`,\n createAppSchema,\n async (params: { appName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n // Any name match means the name is taken \u2014 a collision still counts.\n const existing = matchByName(await client.listApps(), params.appName);\n if (existing.length > 0) {\n return errorResponse(`App \"${params.appName}\" already exists`, 'VALIDATION_ERROR');\n }\n\n const app = await client.createApp(params.appName);\n\n return successResponse({\n tenant,\n app: {\n id: app.id,\n name: app.name,\n },\n message: `App \"${params.appName}\" created. Use farseer_configure_app to set entrypoint, scripts, and arguments.`,\n });\n } catch (error) {\n return errorResponse(`Create app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_configure_app - Configure app settings\n s.tool(\n 'farseer_configure_app',\n `Configure an existing Farseer app.\n\nYou can set:\n- sourceFolder: Folder under Files/ the app's scripts come from (e.g. \"Scripts/MyApp\")\n- entrypoint: Main script to execute \u2014 must be a file in the source folder (e.g., \"index.ts\")\n- description: App description\n- arguments: List of expected arguments. Each has a name, optional dataType\n ('string' | 'boolean' \u2014 defaults to 'string'), optional fixed (locks the\n value at run time), optional options (closed allowed-value set, string\n dataType only), optional defaultValue, and optional secret.\n- newName: Rename the app\n- schedule: Cron expression the app runs on (e.g. \"0 6 * * *\")\n- runner: Which jobrunner runs the app\n- runnerImage: Container image, as \"<repository>:<tag>\" or a full registry reference\n- compute: Where a run executes \u2014 'local', 'batch', or 'batch:<size>' with size s, m, l or xl\n- predefinedActions: Named argument presets offered as buttons in the UI. The\n list you pass replaces the app's whole list. farseer_get_app shows a secret\n argument's value as \"<secret>\"; send \"<secret>\" back to keep the stored value\n of the action with exactly that name. Where two actions share a name, give\n the real value.\n\nImportant:\n- The app's scripts are derived from its source folder; the entrypoint must be\n one of those files. To use a script from another folder, set sourceFolder first.\n- Changing sourceFolder to a folder that doesn't contain the current entrypoint\n requires passing entrypoint in the same call.\n- Settings you don't pass are preserved (this only changes what you specify).\n- Pass \"${CLEAR_SETTING}\" to schedule, runner or runnerImage to clear it.\n- Arguments are passed to the script as a JSON-encoded FARSEER_ARGS env var\n- Boolean dataType requires defaultValue \u2208 { \"true\", \"false\" }; defaultValue\n must be one of options when options is set`,\n configureAppSchema,\n async (params: {\n appName?: string;\n appId?: string;\n entrypoint?: string;\n sourceFolder?: string;\n description?: string;\n arguments?: Array<{\n name: string;\n dataType?: 'string' | 'boolean';\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }>;\n newName?: string;\n schedule?: string;\n runner?: string;\n runnerImage?: string;\n compute?: string;\n predefinedActions?: AppPredefinedAction[];\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const resolution = await resolveAppForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const app = resolution.app;\n\n // The set of changes. updateApp merges these onto the app's\n // current state, so anything left out here is preserved.\n const changes: AppUpdateChanges = {};\n\n if (params.newName) {\n changes.name = params.newName;\n }\n\n if (params.description !== undefined) {\n changes.description = params.description;\n }\n\n if (params.arguments) {\n // PUT semantics on the backend: this `expectedArguments`\n // array replaces the existing one wholesale. So if the\n // caller supplies a name but omits axes (dataType, fixed,\n // options, secret), we look up the existing arg by name\n // and carry those fields over. Without this merge, a\n // configure_app call that only re-sets defaultValue would\n // silently clear the secret flag or demote a dropdown\n // back to a plain string variable.\n //\n // Lookup is case-insensitive for convenience (caller\n // shouldn't have to remember exact casing to update an\n // existing arg), but on the write we keep the backend's\n // stored casing: validateExpectedArguments on the server\n // is case-sensitive (seen.has(arg.name)), so writing\n // back caller-supplied case would silently rename the\n // arg (e.g. jobName \u2192 JOBNAME) and break the next push.\n const existingByName = new Map(app.expectedArguments.map((e) => [e.name.toLowerCase(), e]));\n changes.expectedArguments = params.arguments.map((a) => {\n const existing = existingByName.get(a.name.toLowerCase());\n const arg: AppArgument = {\n name: existing?.name ?? a.name,\n dataType: a.dataType ?? existing?.dataType ?? 'string',\n };\n const fixed = a.fixed ?? existing?.fixed;\n if (fixed !== undefined) arg.fixed = fixed;\n const options = a.options ?? existing?.options;\n if (options !== undefined) arg.options = options;\n const defaultValue = a.defaultValue ?? existing?.defaultValue;\n if (defaultValue !== undefined) arg.defaultValue = defaultValue;\n const secret = a.secret ?? existing?.secret;\n if (secret !== undefined) arg.secret = secret;\n return arg;\n });\n }\n\n // Source folder + entrypoint. An app's scripts derive from its\n // source folder, and the entrypoint must be one of those files.\n // The decision lives in applySourceFolderChange (shared with the\n // CLI `app configure` command); the 'mcp' caller gets a plain,\n // param-worded error string.\n const sourceFolderError = await applySourceFolderChange(\n client,\n app,\n changes,\n { sourceFolder: params.sourceFolder, entrypoint: params.entrypoint },\n 'mcp',\n );\n if (sourceFolderError) {\n return errorResponse(sourceFolderError, 'VALIDATION_ERROR');\n }\n\n if (params.predefinedActions) {\n const restored = restoreRedactedValues(params.predefinedActions, app.predefinedActions ?? []);\n if ('error' in restored) {\n return errorResponse(restored.error, 'VALIDATION_ERROR');\n }\n changes.predefinedActions = restored.actions;\n }\n\n // Schedule, runner, image and compute. Shared with the CLI\n // `app configure` command so both surfaces take the same vocabulary.\n const runSettings = await applyRunSettings(client, app, changes, {\n schedule: params.schedule,\n runner: params.runner,\n runnerImage: params.runnerImage,\n compute: params.compute,\n });\n if ('error' in runSettings) {\n return errorResponse(runSettings.error, 'VALIDATION_ERROR');\n }\n\n const reference = app.id.toString();\n const updated = await client.updateApp(reference, changes, app);\n\n return successResponse({\n tenant,\n appName: params.newName || app.name,\n updated: Object.keys(changes),\n compute: formatCompute(updated.compute),\n warnings: runSettings.warnings,\n message: `App \"${app.name}\" configured successfully`,\n });\n } catch (error) {\n return errorResponse(`Configure app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_delete_app - Delete app\n s.tool(\n 'farseer_delete_app',\n `Delete an app from a Farseer tenant.\n\nWARNING: This is irreversible - the app will be permanently removed from the remote instance.\n\nThis does NOT delete the script files, only the app configuration.`,\n deleteAppSchema,\n async (params: { appName?: string; appId?: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const resolution = await resolveAppItemForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const appItem = resolution.item;\n\n await client.deleteApp(appItem.reference);\n\n // The folder API 200s even when nothing was deleted; confirm.\n const remaining = await client.listApps();\n if (remaining.some((a) => a.reference === appItem.reference)) {\n return errorResponse(\n `Delete reported success but \"${appItem.name}\" is still present`,\n 'NETWORK_ERROR',\n );\n }\n\n return successResponse({\n tenant,\n deletedApp: appItem.name,\n message: `App \"${appItem.name}\" has been deleted`,\n });\n } catch (error) {\n // A guard refusal is not retryable \u2014 nothing was deleted and a\n // retry cannot change that. Don't let it read as a transport blip.\n return errorResponse(\n `Delete app failed: ${await formatClientError(error)}`,\n error instanceof AppDeleteRefusedError ? 'VALIDATION_ERROR' : 'NETWORK_ERROR',\n );\n }\n },\n );\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,qBAA+B;AAC/B,kBAYO;AACP,qBAAuF;AACvF,0BAA4B;AAC5B,4BAAkC;AAGlC,MAAM,iBAAiB;AAAA,EACnB,SAAS,aAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,mCAAmC;AAChF;AAEA,MAAM,eAAe;AAAA,EACjB,SAAS,aAAE,OAAO,EAAE,SAAS,EAAE,SAAS,4DAA4D;AAAA,EACpG,OAAO,aAAE,OAAO,EAAE,SAAS,EAAE,SAAS,kEAA6D;AACvG;AAEA,MAAM,kBAAkB;AAAA,EACpB,SAAS,aAAE,OAAO,EAAE,SAAS,sBAAsB;AACvD;AAEO,MAAM,iBAAiB,aACzB,OAAO;AAAA,EACJ,MAAM,aAAE,OAAO;AAAA,EACf,UAAU,aAAE,KAAK,CAAC,UAAU,SAAS,CAAC,EAAE,SAAS,EAAE,SAAS,6CAA6C;AAAA,EACzG,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SAAS,OAAO;AACZ,mBAAO,8BAAc,mBAAmB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MAC7F;AAAA,IACJ;AAAA,EACJ;AAGA,IAAE;AAAA,IACE;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * App Management Tools\n *\n * Tools for managing Farseer apps (Remote Jobs).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { requireSession } from '../utils/session';\nimport {\n APP_COMPUTE_CHOICES,\n AppArgument,\n AppDeleteRefusedError,\n AppPredefinedAction,\n AppUpdateChanges,\n CLEAR_SETTING,\n applyRunSettings,\n applySourceFolderChange,\n formatCompute,\n redactActionValues,\n restoreRedactedValues,\n} from '../../services/apps';\nimport { successResponse, errorResponse, resolveAppItemForMcp, resolveAppForMcp } from '../utils/helpers';\nimport { matchByName } from '../../utils/nameResolver';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst listAppsSchema = {\n details: z.boolean().optional().describe('Include full details for each app'),\n};\n\nconst getAppSchema = {\n appName: z.string().optional().describe('Name of the app (can include spaces). Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n};\n\nconst createAppSchema = {\n appName: z.string().describe('Name for the new app'),\n};\n\nexport const argumentSchema = z\n .object({\n name: z.string(),\n dataType: z.enum(['string', 'boolean']).optional().describe('Data type. Defaults to \"string\" if omitted.'),\n fixed: z\n .boolean()\n .optional()\n .describe('Lock the value at run time so users cannot override it (admin sets, user reads only).'),\n options: z\n .array(z.string())\n .optional()\n .describe('Closed allowed-value set. Only meaningful for string dataType.'),\n defaultValue: z.string().optional(),\n secret: z.boolean().optional().describe('Mask the value in inputs and logs.'),\n })\n // Cross-axis checks mirror the backend's `validateExpectedArguments` so an\n // LLM caller gets pre-request feedback. Backend stays authoritative \u2014 these\n // catch the same shapes earlier, they don't replace the validator.\n .refine(\n (a) => a.dataType !== 'boolean' || a.defaultValue === undefined || ['true', 'false'].includes(a.defaultValue),\n {\n message: 'Boolean argument defaultValue must be \"true\" or \"false\"',\n path: ['defaultValue'],\n },\n )\n .refine((a) => !a.options || a.defaultValue === undefined || a.options.includes(a.defaultValue), {\n message: 'defaultValue must be one of the options',\n path: ['defaultValue'],\n });\n\nexport const predefinedActionSchema = z.object({\n name: z.string(),\n runArguments: z.record(z.string()).describe('Argument name to the value this action runs with.'),\n});\n\nconst configureAppSchema = {\n appName: z.string().optional().describe('Name of the app to configure. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n entrypoint: z\n .string()\n .optional()\n .describe('Main script filename \u2014 must be a file in the app\\'s source folder (e.g., \"index.ts\")'),\n sourceFolder: z\n .string()\n .optional()\n .describe('Source folder the app\\'s scripts come from (path under Files/, e.g. \"Scripts/MyApp\")'),\n description: z.string().optional().describe('App description'),\n arguments: z.array(argumentSchema).optional().describe('App arguments with default values'),\n newName: z.string().optional().describe('Rename the app'),\n schedule: z\n .string()\n .optional()\n .describe(`Cron expression to run the app on, e.g. \"0 6 * * *\". Pass \"${CLEAR_SETTING}\" to clear it.`),\n runner: z\n .string()\n .optional()\n .describe(`Name of the jobrunner that runs the app. Pass \"${CLEAR_SETTING}\" to let any runner take it.`),\n runnerImage: z\n .string()\n .optional()\n .describe(\n `Container image the app runs in, as \"<repository>:<tag>\" (e.g. \"runner-typescript:latest\") or a full registry reference. Pass \"${CLEAR_SETTING}\" for the tenant default.`,\n ),\n compute: z\n .enum(APP_COMPUTE_CHOICES as unknown as [string, ...string[]])\n .optional()\n .describe(\n 'Where a run executes: \"local\" is a container on the jobrunner\\'s own machine, \"batch\" a machine created for that run. The size suffix picks how much machine; bare \"batch\" takes the deployment\\'s default size.',\n ),\n predefinedActions: z\n .array(predefinedActionSchema)\n .optional()\n .describe('Named argument presets offered as buttons in the UI. Replaces the existing list wholesale.'),\n};\n\nconst deleteAppSchema = {\n appName: z.string().optional().describe('Name of the app to delete. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n};\n\nexport function registerAppTools(server: McpServer): void {\n // Cast to avoid TS2589 deep type instantiation with MCP SDK + Zod generics\n const s: any = server;\n\n // farseer_list_apps - List all apps\n s.tool(\n 'farseer_list_apps',\n `List all apps (Remote Jobs) configured on a Farseer tenant.\n\nApps are executable script configurations that include:\n- Entry point script\n- List of included scripts\n- Expected arguments with default values\n\nUse details=true to include full information for each app.`,\n listAppsSchema,\n async (params: { details?: boolean }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const appList = await client.listApps();\n\n if (!params.details) {\n return successResponse({\n tenant,\n totalApps: appList.length,\n apps: appList.map((a) => ({\n name: a.name,\n reference: a.reference,\n })),\n });\n }\n\n // Get full details for each app\n const appsWithDetails = [];\n for (const item of appList) {\n const app = await client.getApp(item.reference);\n if (app) {\n const appScripts = app.scriptFiles ?? [];\n const mainScript = appScripts.find((s) => s.id === app.mainScriptFileId);\n appsWithDetails.push({\n name: app.name,\n id: app.id,\n description: app.description || '',\n entrypoint: mainScript?.name || null,\n scripts: appScripts.map((s) => s.name),\n arguments: app.expectedArguments.map((a) => ({\n name: a.name,\n dataType: a.dataType,\n ...(a.fixed !== undefined ? { fixed: a.fixed } : {}),\n ...(a.options !== undefined ? { options: a.options } : {}),\n ...(a.defaultValue !== undefined ? { defaultValue: a.defaultValue } : {}),\n ...(a.secret !== undefined ? { secret: a.secret } : {}),\n })),\n });\n }\n }\n\n return successResponse({\n tenant,\n totalApps: appsWithDetails.length,\n apps: appsWithDetails,\n });\n } catch (error) {\n return errorResponse(`List apps failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_get_app - Get app details\n s.tool(\n 'farseer_get_app',\n `Get detailed information about a specific Farseer app.\n\nReturns:\n- App name and description\n- Entry point script (main script that runs)\n- List of all included scripts\n- Expected arguments with their default values\n- Schedule, runner, runner image and compute selection\n- Predefined actions (named argument presets)`,\n getAppSchema,\n async (params: { appName?: string; appId?: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const resolution = await resolveAppForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const app = resolution.app;\n\n const getAppScripts = app.scriptFiles ?? [];\n const mainScript = getAppScripts.find((s) => s.id === app.mainScriptFileId);\n\n return successResponse({\n tenant,\n app: {\n id: app.id,\n name: app.name,\n description: app.description || '',\n entrypoint: mainScript?.name || null,\n scripts: getAppScripts.map((s) => ({\n id: s.id,\n name: s.name,\n isEntrypoint: s.id === app.mainScriptFileId,\n })),\n arguments: app.expectedArguments.map((a) => ({\n name: a.name,\n dataType: a.dataType,\n ...(a.fixed !== undefined ? { fixed: a.fixed } : {}),\n ...(a.options !== undefined ? { options: a.options } : {}),\n ...(a.defaultValue !== undefined ? { defaultValue: a.defaultValue } : {}),\n ...(a.secret !== undefined ? { secret: a.secret } : {}),\n })),\n status: app.status,\n lastHeartbeat: app.lastHeartbeat,\n schedule: app.schedule ?? null,\n runner: app.runnerName ?? null,\n runnerImage: app.runnerImage ?? null,\n compute: formatCompute(app.compute),\n predefinedActions: redactActionValues(app.predefinedActions ?? [], app.expectedArguments),\n },\n });\n } catch (error) {\n return errorResponse(`Get app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_app - Create new app\n s.tool(\n 'farseer_create_app',\n `Create a new Farseer app.\n\nAll new repeatable data pipelines must use Simple Pipelines through farseer_pipeline operation=guide topic=method, even when TypeScript is requested. Inspect existing apps first; do not create a replacement or duplicate to fix an existing TypeScript app. This creation workflow is for non-pipeline apps. Maintain existing TypeScript pipelines with the app tools; migration requires an explicit migration request.\n\nA Farseer App is a named configuration that points to a TypeScript script and defines its arguments.\nThe script uses farseer-client to interact with the Farseer API (import data, export reports, etc.).\n\nWorkflow to create a new app:\n1. Write the script at farseer-apps/<tenant>/files/Scripts/<name>.ts\n2. Push the script to remote with farseer_push (scripts must exist on remote first)\n3. Create the app with this tool (farseer_create_app)\n4. Configure it with farseer_configure_app (set entrypoint, scripts, arguments)\n5. Run it with farseer_run_app (CLI injects auth credentials automatically)\n\nScripts should use \\`new FarseerClient()\\` with no arguments - credentials are injected via environment variables by the CLI at runtime.`,\n createAppSchema,\n async (params: { appName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n // Any name match means the name is taken \u2014 a collision still counts.\n const existing = matchByName(await client.listApps(), params.appName);\n if (existing.length > 0) {\n return errorResponse(`App \"${params.appName}\" already exists`, 'VALIDATION_ERROR');\n }\n\n const app = await client.createApp(params.appName);\n\n return successResponse({\n tenant,\n app: {\n id: app.id,\n name: app.name,\n },\n message: `App \"${params.appName}\" created. Use farseer_configure_app to set entrypoint, scripts, and arguments.`,\n });\n } catch (error) {\n return errorResponse(`Create app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_configure_app - Configure app settings\n s.tool(\n 'farseer_configure_app',\n `Configure an existing Farseer app.\n\nPreserve existing TypeScript apps during maintenance. Do not change their source folder, entrypoint, runner image or schedule to satisfy Simple Pipelines setup. Migration requires an explicit migration request; use the existing app tools for targeted fixes.\n\nYou can set:\n- sourceFolder: Folder under Files/ the app's scripts come from (e.g. \"Scripts/MyApp\")\n- entrypoint: Main script to execute \u2014 must be a file in the source folder (e.g., \"index.ts\")\n- description: App description\n- arguments: List of expected arguments. Each has a name, optional dataType\n ('string' | 'boolean' \u2014 defaults to 'string'), optional fixed (locks the\n value at run time), optional options (closed allowed-value set, string\n dataType only), optional defaultValue, and optional secret.\n- newName: Rename the app\n- schedule: Cron expression the app runs on (e.g. \"0 6 * * *\")\n- runner: Which jobrunner runs the app\n- runnerImage: Container image, as \"<repository>:<tag>\" or a full registry reference\n- compute: Where a run executes \u2014 'local', 'batch', or 'batch:<size>' with size s, m, l or xl\n- predefinedActions: Named argument presets offered as buttons in the UI. The\n list you pass replaces the app's whole list. farseer_get_app shows a secret\n argument's value as \"<secret>\"; send \"<secret>\" back to keep the stored value\n of the action with exactly that name. Where two actions share a name, give\n the real value.\n\nImportant:\n- The app's scripts are derived from its source folder; the entrypoint must be\n one of those files. To use a script from another folder, set sourceFolder first.\n- Changing sourceFolder to a folder that doesn't contain the current entrypoint\n requires passing entrypoint in the same call.\n- Settings you don't pass are preserved (this only changes what you specify).\n- Pass \"${CLEAR_SETTING}\" to schedule, runner or runnerImage to clear it.\n- Arguments are passed to the script as a JSON-encoded FARSEER_ARGS env var\n- Boolean dataType requires defaultValue \u2208 { \"true\", \"false\" }; defaultValue\n must be one of options when options is set`,\n configureAppSchema,\n async (params: {\n appName?: string;\n appId?: string;\n entrypoint?: string;\n sourceFolder?: string;\n description?: string;\n arguments?: Array<{\n name: string;\n dataType?: 'string' | 'boolean';\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }>;\n newName?: string;\n schedule?: string;\n runner?: string;\n runnerImage?: string;\n compute?: string;\n predefinedActions?: AppPredefinedAction[];\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const resolution = await resolveAppForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const app = resolution.app;\n\n // The set of changes. updateApp merges these onto the app's\n // current state, so anything left out here is preserved.\n const changes: AppUpdateChanges = {};\n\n if (params.newName) {\n changes.name = params.newName;\n }\n\n if (params.description !== undefined) {\n changes.description = params.description;\n }\n\n if (params.arguments) {\n // PUT semantics on the backend: this `expectedArguments`\n // array replaces the existing one wholesale. So if the\n // caller supplies a name but omits axes (dataType, fixed,\n // options, secret), we look up the existing arg by name\n // and carry those fields over. Without this merge, a\n // configure_app call that only re-sets defaultValue would\n // silently clear the secret flag or demote a dropdown\n // back to a plain string variable.\n //\n // Lookup is case-insensitive for convenience (caller\n // shouldn't have to remember exact casing to update an\n // existing arg), but on the write we keep the backend's\n // stored casing: validateExpectedArguments on the server\n // is case-sensitive (seen.has(arg.name)), so writing\n // back caller-supplied case would silently rename the\n // arg (e.g. jobName \u2192 JOBNAME) and break the next push.\n const existingByName = new Map(app.expectedArguments.map((e) => [e.name.toLowerCase(), e]));\n changes.expectedArguments = params.arguments.map((a) => {\n const existing = existingByName.get(a.name.toLowerCase());\n const arg: AppArgument = {\n name: existing?.name ?? a.name,\n dataType: a.dataType ?? existing?.dataType ?? 'string',\n };\n const fixed = a.fixed ?? existing?.fixed;\n if (fixed !== undefined) arg.fixed = fixed;\n const options = a.options ?? existing?.options;\n if (options !== undefined) arg.options = options;\n const defaultValue = a.defaultValue ?? existing?.defaultValue;\n if (defaultValue !== undefined) arg.defaultValue = defaultValue;\n const secret = a.secret ?? existing?.secret;\n if (secret !== undefined) arg.secret = secret;\n return arg;\n });\n }\n\n // Source folder + entrypoint. An app's scripts derive from its\n // source folder, and the entrypoint must be one of those files.\n // The decision lives in applySourceFolderChange (shared with the\n // CLI `app configure` command); the 'mcp' caller gets a plain,\n // param-worded error string.\n const sourceFolderError = await applySourceFolderChange(\n client,\n app,\n changes,\n { sourceFolder: params.sourceFolder, entrypoint: params.entrypoint },\n 'mcp',\n );\n if (sourceFolderError) {\n return errorResponse(sourceFolderError, 'VALIDATION_ERROR');\n }\n\n if (params.predefinedActions) {\n const restored = restoreRedactedValues(params.predefinedActions, app.predefinedActions ?? []);\n if ('error' in restored) {\n return errorResponse(restored.error, 'VALIDATION_ERROR');\n }\n changes.predefinedActions = restored.actions;\n }\n\n // Schedule, runner, image and compute. Shared with the CLI\n // `app configure` command so both surfaces take the same vocabulary.\n const runSettings = await applyRunSettings(client, app, changes, {\n schedule: params.schedule,\n runner: params.runner,\n runnerImage: params.runnerImage,\n compute: params.compute,\n });\n if ('error' in runSettings) {\n return errorResponse(runSettings.error, 'VALIDATION_ERROR');\n }\n\n const reference = app.id.toString();\n const updated = await client.updateApp(reference, changes, app);\n\n return successResponse({\n tenant,\n appName: params.newName || app.name,\n updated: Object.keys(changes),\n compute: formatCompute(updated.compute),\n warnings: runSettings.warnings,\n message: `App \"${app.name}\" configured successfully`,\n });\n } catch (error) {\n return errorResponse(`Configure app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_delete_app - Delete app\n s.tool(\n 'farseer_delete_app',\n `Delete an app from a Farseer tenant.\n\nWARNING: This is irreversible - the app will be permanently removed from the remote instance.\n\nThis does NOT delete the script files, only the app configuration.`,\n deleteAppSchema,\n async (params: { appName?: string; appId?: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const resolution = await resolveAppItemForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const appItem = resolution.item;\n\n await client.deleteApp(appItem.reference);\n\n // The folder API 200s even when nothing was deleted; confirm.\n const remaining = await client.listApps();\n if (remaining.some((a) => a.reference === appItem.reference)) {\n return errorResponse(\n `Delete reported success but \"${appItem.name}\" is still present`,\n 'NETWORK_ERROR',\n );\n }\n\n return successResponse({\n tenant,\n deletedApp: appItem.name,\n message: `App \"${appItem.name}\" has been deleted`,\n });\n } catch (error) {\n // A guard refusal is not retryable \u2014 nothing was deleted and a\n // retry cannot change that. Don't let it read as a transport blip.\n return errorResponse(\n `Delete app failed: ${await formatClientError(error)}`,\n error instanceof AppDeleteRefusedError ? 'VALIDATION_ERROR' : 'NETWORK_ERROR',\n );\n }\n },\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,qBAA+B;AAC/B,kBAYO;AACP,q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"]
|
|
7
7
|
}
|
|
@@ -187,6 +187,8 @@ Example usage:
|
|
|
187
187
|
"farseer_create_import_job",
|
|
188
188
|
`Create and execute a complete data import job on a Farseer instance.
|
|
189
189
|
|
|
190
|
+
For repeatable data extraction, transformation and loading, start with farseer_pipeline operation=guide topic=method. Use this tool for a direct import the user requested. If pipeline setup is missing, explain what needs preparing before choosing a different workflow.
|
|
191
|
+
|
|
190
192
|
This tool handles the full import workflow in a single call:
|
|
191
193
|
1. Builds import metadata from column definitions
|
|
192
194
|
2. Creates the import job
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/dataTools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Data Operation Tools\n *\n * MCP tools for data export, import jobs, and file management on Farseer instances.\n * These use the native farseer-client for full API access.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as farseer from 'farseer-client';\nimport { requireSession } from '../utils/session';\nimport { successResponse, errorResponse } from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst exportVariableDataSchema = {\n variableName: z.string().describe('Name of the variable to export'),\n filters: z\n .array(z.array(z.string()).length(2))\n .optional()\n .describe(\n 'Dimension filters as [tableName, memberName] pairs (e.g., [[\"Months\",\"M1\"],[\"Brand\",\"0000032\"]]). Filters the export to specific dimension members.',\n ),\n format: z.enum(['csv', 'json']).optional().describe('Output format (default: csv)'),\n limit: z.number().optional().describe('Maximum number of rows to return'),\n};\n\nconst loadVariableDataSchema = {\n variableName: z.string().describe('Name of the variable to load'),\n dimensions: z.array(z.string()).optional().describe('Dimension table names to include as columns in the export'),\n};\n\nconst createImportJobSchema = {\n title: z.string().describe('Import job title (shown in import history)'),\n columns: z\n .array(\n z.object({\n type: z.enum(['DIMENSION_TABLE', 'VARIABLE', 'DATE', 'DESCRIPTION']).describe('Column type'),\n dimensionTableName: z.string().optional().describe('For DIMENSION_TABLE: name of the dimension table'),\n variableName: z.string().optional().describe('For VARIABLE: name of the variable'),\n columnName: z.string().optional().describe('Column header name'),\n dateFormat: z.string().optional().describe('For DATE: date format string'),\n dimensionsNames: z\n .array(\n z.object({\n tableName: z.string(),\n memberName: z.string(),\n }),\n )\n .optional()\n .describe('For VARIABLE: fixed dimension members (filters) for this variable column'),\n }),\n )\n .describe('Column definitions matching the data structure'),\n rows: z\n .array(z.array(z.union([z.string(), z.number(), z.null()])))\n .describe('Data rows - each row is an array of values matching column order'),\n labels: z\n .array(z.string())\n .optional()\n .describe('Labels for grouping import jobs (used by undoPrevious to revert jobs with same labels)'),\n undoPrevious: z\n .boolean()\n .optional()\n .describe('Revert previous import jobs with the same labels before committing (default: false)'),\n importDimensions: z\n .boolean()\n .optional()\n .describe('Auto-create any missing dimension members before committing (default: false)'),\n overwriteCells: z\n .boolean()\n .optional()\n .describe('Overwrite existing cell values (default: false - adds to existing values)'),\n};\n\nconst createFileSchema = {\n fileName: z.string().describe('Name of the file to create or update'),\n folderPath: z\n .array(z.string())\n .optional()\n .describe('Folder path as array (e.g., [\"Files\", \"Reports\"]). Default: [\"Files\"]'),\n content: z.string().describe('File content as text string'),\n};\n\nexport function registerDataTools(server: McpServer): void {\n // farseer_export_variable_data - Export variable data\n server.tool(\n 'farseer_export_variable_data',\n `Export data from a Farseer variable as CSV.\n\nBuilds an export configuration from the variable's dimensions and uses\nthe evaluator export endpoint. Works on all server versions.\n\nFor small results (under 500 rows), returns data inline.\nFor large results (500+ rows), automatically exports to a temp file and returns the path \u2014\nuse the Read tool to inspect the file contents.\n\nUse the 'limit' parameter to restrict row count for large variables.`,\n exportVariableDataSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: {\n variableName: string;\n filters?: Array<Array<string>>;\n format?: 'csv' | 'json';\n limit?: number;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n const text = await exportVariableAsCsv(nativeClient, params.variableName, params.limit, params.filters);\n\n const lines = text.split('\\n').filter((l) => l.trim());\n const rowCount = Math.max(0, lines.length - 1);\n\n const CSV_THRESHOLD = 500;\n\n // Large result \u2014 export to file\n if (rowCount >= CSV_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const safeName = params.variableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const filePath = path.join(tmpDir, `farseer_${tenant}_${safeName}.csv`);\n fs.writeFileSync(filePath, text, 'utf-8');\n\n const previewLines = lines.slice(0, 6).join('\\n');\n\n return successResponse({\n tenant,\n variable: params.variableName,\n format: 'csv',\n rowCount,\n exportedToFile: filePath,\n message: `Variable has ${rowCount} rows \u2014 exported to file. Use Read tool to inspect.`,\n preview: previewLines,\n });\n }\n\n return successResponse({\n tenant,\n variable: params.variableName,\n format: 'csv',\n rowCount,\n data: text,\n });\n } catch (error) {\n return errorResponse(`Export variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_load_variable_data - Load variable data with specific dimensions\n server.tool(\n 'farseer_load_variable_data',\n `Load data from a Farseer variable into a structured CSV format.\n\nExports all data cells for the variable. You can optionally filter to\nspecific dimensions only.\n\nFor small results (under 500 rows), returns data inline.\nFor large results (500+ rows), automatically exports to a temp CSV file and returns the path.\n\nExample usage:\n- Load \"Revenue\" data (all dimensions)\n- Load \"Revenue\" with dimensions [\"Product\", \"Years\", \"Months\"]`,\n loadVariableDataSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { variableName: string; dimensions?: string[] }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n const text = await exportVariableAsCsv(nativeClient, params.variableName);\n\n const lines = text.split('\\n').filter((l) => l.trim());\n const rowCount = Math.max(0, lines.length - 1);\n\n const CSV_THRESHOLD = 500;\n\n // Large result \u2014 export to file\n if (rowCount >= CSV_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const safeName = params.variableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const filePath = path.join(tmpDir, `farseer_${tenant}_${safeName}_data.csv`);\n fs.writeFileSync(filePath, text, 'utf-8');\n\n const previewLines = lines.slice(0, 6).join('\\n');\n\n return successResponse({\n tenant,\n variable: params.variableName,\n dimensions: params.dimensions || 'all',\n rowCount,\n exportedToFile: filePath,\n message: `Variable has ${rowCount} rows \u2014 exported to CSV. Use Read tool to inspect.`,\n preview: previewLines,\n });\n }\n\n return successResponse({\n tenant,\n variable: params.variableName,\n dimensions: params.dimensions || 'all',\n rowCount,\n data: text,\n });\n } catch (error) {\n return errorResponse(`Load variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_import_job - Create and execute import job\n server.tool(\n 'farseer_create_import_job',\n `Create and execute a complete data import job on a Farseer instance.\n\nThis tool handles the full import workflow in a single call:\n1. Builds import metadata from column definitions\n2. Creates the import job\n3. Adds all data rows\n4. Optionally creates missing dimension members (importDimensions)\n5. Optionally reverts previous imports with same labels (undoPrevious)\n6. Commits the import\n\nColumn types:\n- DIMENSION_TABLE: Maps to a dimension table (e.g., Product, Years, Months)\n- VARIABLE: Maps to a variable that will receive data values\n - Can include dimensionsNames to fix specific dimension members for this column\n- DATE: Date column with format string\n- DESCRIPTION: Cell description/comment\n\nThe 'labels' parameter is important for the undoPrevious feature:\nwhen undoPrevious is true, all previously committed imports with the\nsame labels will be reverted before this import is committed.\nThis is useful for idempotent re-imports.\n\nThe 'overwriteCells' parameter controls whether existing values are\noverwritten (true) or accumulated (false, default).\n\nExample columns for importing revenue data:\n[\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Product\" },\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Years\" },\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Months\" },\n { \"type\": \"VARIABLE\", \"variableName\": \"Revenue\",\n \"dimensionsNames\": [\n { \"tableName\": \"Versions\", \"memberName\": \"Actual\" }\n ]\n }\n]`,\n createImportJobSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: {\n title: string;\n columns: Array<{\n type: 'DIMENSION_TABLE' | 'VARIABLE' | 'DATE' | 'DESCRIPTION';\n dimensionTableName?: string;\n variableName?: string;\n columnName?: string;\n dateFormat?: string;\n dimensionsNames?: Array<{ tableName: string; memberName: string }>;\n }>;\n rows: Array<Array<string | number | null>>;\n labels?: string[];\n undoPrevious?: boolean;\n importDimensions?: boolean;\n overwriteCells?: boolean;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n const {\n title,\n columns,\n rows,\n labels,\n undoPrevious = false,\n importDimensions = false,\n overwriteCells = false,\n } = params;\n\n // Build metadata columns\n const metadataColumns = columns.map((col) => {\n switch (col.type) {\n case 'DIMENSION_TABLE':\n return {\n type: 'DIMENSION_TABLE' as const,\n dimensionTableName: col.dimensionTableName!,\n columnName: col.columnName,\n };\n case 'VARIABLE':\n return {\n type: 'VARIABLE' as const,\n variableName: col.variableName!,\n columnName: col.columnName || col.variableName!,\n dimensionsNames: col.dimensionsNames,\n };\n case 'DATE':\n return {\n type: 'DATE' as const,\n dateFormat: col.dateFormat!,\n columnName: col.columnName,\n };\n case 'DESCRIPTION':\n return {\n type: 'DESCRIPTION' as const,\n columnName: col.columnName,\n };\n default:\n return {\n type: 'NONE' as const,\n columnName: col.columnName,\n };\n }\n });\n\n // Build metadata\n const metadata = await nativeClient.buildImportJobMetadata(metadataColumns as any);\n\n if (overwriteCells) {\n (metadata as any).overwriteCells = true;\n }\n\n // Create import job\n const importActions = await nativeClient.createImportJob({\n title,\n metadata,\n labels,\n });\n\n // Add rows\n await importActions.addRows(rows as any);\n await importActions.flushRows();\n\n // Import dimensions if needed\n if (importDimensions) {\n await importActions.importDimensions();\n }\n\n // Undo previous if needed\n if (undoPrevious) {\n await importActions.undoPrevious();\n }\n\n // Commit\n const report = await importActions.commit();\n\n return successResponse({\n tenant,\n title,\n rowCount: rows.length,\n labels: labels || [],\n undoPrevious,\n importDimensions,\n overwriteCells,\n commitReport: report,\n });\n } catch (error) {\n return errorResponse(`Import job failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_file - Create or update file on instance\n server.tool(\n 'farseer_create_file',\n `Create or update a file on a Farseer instance.\n\nThis creates a file in the specified folder on the Farseer file system.\nIf a file with the same name already exists in that folder, it will be updated.\n\nThe folderPath is an array of folder names, starting from the root.\nDefault is [\"Files\"] which is the standard files folder.\n\nCommon use cases:\n- Creating CSV report files\n- Uploading configuration files\n- Saving processed data outputs`,\n createFileSchema,\n async (params: { fileName: string; folderPath?: string[]; content: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client, native: nativeClient } = gate.session;\n\n try {\n const folderPath = params.folderPath || ['Files'];\n // Not nativeClient.getItemByPath: for a single-segment path that\n // name-searches the whole tenant and refuses on more than one\n // loose match, so a second folder called \"Files\" breaks it.\n const folder = await client.getFolderByPath(folderPath);\n if (!folder) {\n return errorResponse(`Folder \"${folderPath.join('/')}\" not found`, 'NOT_FOUND');\n }\n const buffer = Buffer.from(params.content, 'utf-8');\n\n await nativeClient.createOrUpdateFarseerFile(\n { name: params.fileName, folderId: folder.id } as any,\n buffer,\n );\n\n return successResponse({\n tenant,\n fileName: params.fileName,\n folderPath,\n size: buffer.length,\n message: `File \"${params.fileName}\" created/updated in ${folderPath.join('/')}`,\n });\n } catch (error) {\n return errorResponse(`Create file failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n\n/**\n * Export variable data as CSV using evaluatorExport (works on all server versions).\n * Falls back to exportFormula if evaluatorExport fails.\n */\n/**\n * Export variable data as CSV using exportFormula.\n * Wraps the variable name in quotes as required by the API.\n * Supports dimension filters: [[\"Months\",\"M1\"],[\"Brand\",\"0000032\"]]\n * becomes sum(\"VarName\", \"Months\">\"M1\", \"Brand\">\"0000032\")\n */\nasync function exportVariableAsCsv(\n client: farseer.FarseerClient,\n variableName: string,\n limit?: number,\n filters?: Array<Array<string>>,\n): Promise<string> {\n let formula: string;\n if (filters && filters.length > 0) {\n const filterParts = filters.map(([table, member]) => `\"${table}\">\"${member}\"`).join(', ');\n formula = `sum(\"${variableName}\", ${filterParts})`;\n } else {\n formula = `\"${variableName}\"`;\n }\n\n const blob = await client.export.exportFormula({\n formula,\n format: farseer.ExportFormat.Csv,\n limit,\n });\n return await blob.text();\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,iBAAkB;AAClB,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,cAAyB;AACzB,qBAA+B;AAC/B,qBAA+C;AAC/C,4BAAkC;AAGlC,MAAM,2BAA2B;AAAA,EAC7B,cAAc,aAAE,OAAO,EAAE,SAAS,gCAAgC;AAAA,EAClE,SAAS,aACJ,MAAM,aAAE,MAAM,aAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,EACnC,SAAS,EACT;AAAA,IACG;AAAA,EACJ;AAAA,EACJ,QAAQ,aAAE,KAAK,CAAC,OAAO,MAAM,CAAC,EAAE,SAAS,EAAE,SAAS,8BAA8B;AAAA,EAClF,OAAO,aAAE,OAAO,EAAE,SAAS,EAAE,SAAS,kCAAkC;AAC5E;AAEA,MAAM,yBAAyB;AAAA,EAC3B,cAAc,aAAE,OAAO,EAAE,SAAS,8BAA8B;AAAA,EAChE,YAAY,aAAE,MAAM,aAAE,OAAO,CAAC,EAAE,SAAS,EAAE,SAAS,2DAA2D;AACnH;AAEA,MAAM,wBAAwB;AAAA,EAC1B,OAAO,aAAE,OAAO,EAAE,SAAS,4CAA4C;AAAA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SAAO;AAAA,IACH;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * Data Operation Tools\n *\n * MCP tools for data export, import jobs, and file management on Farseer instances.\n * These use the native farseer-client for full API access.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as farseer from 'farseer-client';\nimport { requireSession } from '../utils/session';\nimport { successResponse, errorResponse } from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst exportVariableDataSchema = {\n variableName: z.string().describe('Name of the variable to export'),\n filters: z\n .array(z.array(z.string()).length(2))\n .optional()\n .describe(\n 'Dimension filters as [tableName, memberName] pairs (e.g., [[\"Months\",\"M1\"],[\"Brand\",\"0000032\"]]). Filters the export to specific dimension members.',\n ),\n format: z.enum(['csv', 'json']).optional().describe('Output format (default: csv)'),\n limit: z.number().optional().describe('Maximum number of rows to return'),\n};\n\nconst loadVariableDataSchema = {\n variableName: z.string().describe('Name of the variable to load'),\n dimensions: z.array(z.string()).optional().describe('Dimension table names to include as columns in the export'),\n};\n\nconst createImportJobSchema = {\n title: z.string().describe('Import job title (shown in import history)'),\n columns: z\n .array(\n z.object({\n type: z.enum(['DIMENSION_TABLE', 'VARIABLE', 'DATE', 'DESCRIPTION']).describe('Column type'),\n dimensionTableName: z.string().optional().describe('For DIMENSION_TABLE: name of the dimension table'),\n variableName: z.string().optional().describe('For VARIABLE: name of the variable'),\n columnName: z.string().optional().describe('Column header name'),\n dateFormat: z.string().optional().describe('For DATE: date format string'),\n dimensionsNames: z\n .array(\n z.object({\n tableName: z.string(),\n memberName: z.string(),\n }),\n )\n .optional()\n .describe('For VARIABLE: fixed dimension members (filters) for this variable column'),\n }),\n )\n .describe('Column definitions matching the data structure'),\n rows: z\n .array(z.array(z.union([z.string(), z.number(), z.null()])))\n .describe('Data rows - each row is an array of values matching column order'),\n labels: z\n .array(z.string())\n .optional()\n .describe('Labels for grouping import jobs (used by undoPrevious to revert jobs with same labels)'),\n undoPrevious: z\n .boolean()\n .optional()\n .describe('Revert previous import jobs with the same labels before committing (default: false)'),\n importDimensions: z\n .boolean()\n .optional()\n .describe('Auto-create any missing dimension members before committing (default: false)'),\n overwriteCells: z\n .boolean()\n .optional()\n .describe('Overwrite existing cell values (default: false - adds to existing values)'),\n};\n\nconst createFileSchema = {\n fileName: z.string().describe('Name of the file to create or update'),\n folderPath: z\n .array(z.string())\n .optional()\n .describe('Folder path as array (e.g., [\"Files\", \"Reports\"]). Default: [\"Files\"]'),\n content: z.string().describe('File content as text string'),\n};\n\nexport function registerDataTools(server: McpServer): void {\n // farseer_export_variable_data - Export variable data\n server.tool(\n 'farseer_export_variable_data',\n `Export data from a Farseer variable as CSV.\n\nBuilds an export configuration from the variable's dimensions and uses\nthe evaluator export endpoint. Works on all server versions.\n\nFor small results (under 500 rows), returns data inline.\nFor large results (500+ rows), automatically exports to a temp file and returns the path \u2014\nuse the Read tool to inspect the file contents.\n\nUse the 'limit' parameter to restrict row count for large variables.`,\n exportVariableDataSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: {\n variableName: string;\n filters?: Array<Array<string>>;\n format?: 'csv' | 'json';\n limit?: number;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n const text = await exportVariableAsCsv(nativeClient, params.variableName, params.limit, params.filters);\n\n const lines = text.split('\\n').filter((l) => l.trim());\n const rowCount = Math.max(0, lines.length - 1);\n\n const CSV_THRESHOLD = 500;\n\n // Large result \u2014 export to file\n if (rowCount >= CSV_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const safeName = params.variableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const filePath = path.join(tmpDir, `farseer_${tenant}_${safeName}.csv`);\n fs.writeFileSync(filePath, text, 'utf-8');\n\n const previewLines = lines.slice(0, 6).join('\\n');\n\n return successResponse({\n tenant,\n variable: params.variableName,\n format: 'csv',\n rowCount,\n exportedToFile: filePath,\n message: `Variable has ${rowCount} rows \u2014 exported to file. Use Read tool to inspect.`,\n preview: previewLines,\n });\n }\n\n return successResponse({\n tenant,\n variable: params.variableName,\n format: 'csv',\n rowCount,\n data: text,\n });\n } catch (error) {\n return errorResponse(`Export variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_load_variable_data - Load variable data with specific dimensions\n server.tool(\n 'farseer_load_variable_data',\n `Load data from a Farseer variable into a structured CSV format.\n\nExports all data cells for the variable. You can optionally filter to\nspecific dimensions only.\n\nFor small results (under 500 rows), returns data inline.\nFor large results (500+ rows), automatically exports to a temp CSV file and returns the path.\n\nExample usage:\n- Load \"Revenue\" data (all dimensions)\n- Load \"Revenue\" with dimensions [\"Product\", \"Years\", \"Months\"]`,\n loadVariableDataSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { variableName: string; dimensions?: string[] }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n const text = await exportVariableAsCsv(nativeClient, params.variableName);\n\n const lines = text.split('\\n').filter((l) => l.trim());\n const rowCount = Math.max(0, lines.length - 1);\n\n const CSV_THRESHOLD = 500;\n\n // Large result \u2014 export to file\n if (rowCount >= CSV_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const safeName = params.variableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const filePath = path.join(tmpDir, `farseer_${tenant}_${safeName}_data.csv`);\n fs.writeFileSync(filePath, text, 'utf-8');\n\n const previewLines = lines.slice(0, 6).join('\\n');\n\n return successResponse({\n tenant,\n variable: params.variableName,\n dimensions: params.dimensions || 'all',\n rowCount,\n exportedToFile: filePath,\n message: `Variable has ${rowCount} rows \u2014 exported to CSV. Use Read tool to inspect.`,\n preview: previewLines,\n });\n }\n\n return successResponse({\n tenant,\n variable: params.variableName,\n dimensions: params.dimensions || 'all',\n rowCount,\n data: text,\n });\n } catch (error) {\n return errorResponse(`Load variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_import_job - Create and execute import job\n server.tool(\n 'farseer_create_import_job',\n `Create and execute a complete data import job on a Farseer instance.\n\nFor repeatable data extraction, transformation and loading, start with farseer_pipeline operation=guide topic=method. Use this tool for a direct import the user requested. If pipeline setup is missing, explain what needs preparing before choosing a different workflow.\n\nThis tool handles the full import workflow in a single call:\n1. Builds import metadata from column definitions\n2. Creates the import job\n3. Adds all data rows\n4. Optionally creates missing dimension members (importDimensions)\n5. Optionally reverts previous imports with same labels (undoPrevious)\n6. Commits the import\n\nColumn types:\n- DIMENSION_TABLE: Maps to a dimension table (e.g., Product, Years, Months)\n- VARIABLE: Maps to a variable that will receive data values\n - Can include dimensionsNames to fix specific dimension members for this column\n- DATE: Date column with format string\n- DESCRIPTION: Cell description/comment\n\nThe 'labels' parameter is important for the undoPrevious feature:\nwhen undoPrevious is true, all previously committed imports with the\nsame labels will be reverted before this import is committed.\nThis is useful for idempotent re-imports.\n\nThe 'overwriteCells' parameter controls whether existing values are\noverwritten (true) or accumulated (false, default).\n\nExample columns for importing revenue data:\n[\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Product\" },\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Years\" },\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Months\" },\n { \"type\": \"VARIABLE\", \"variableName\": \"Revenue\",\n \"dimensionsNames\": [\n { \"tableName\": \"Versions\", \"memberName\": \"Actual\" }\n ]\n }\n]`,\n createImportJobSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: {\n title: string;\n columns: Array<{\n type: 'DIMENSION_TABLE' | 'VARIABLE' | 'DATE' | 'DESCRIPTION';\n dimensionTableName?: string;\n variableName?: string;\n columnName?: string;\n dateFormat?: string;\n dimensionsNames?: Array<{ tableName: string; memberName: string }>;\n }>;\n rows: Array<Array<string | number | null>>;\n labels?: string[];\n undoPrevious?: boolean;\n importDimensions?: boolean;\n overwriteCells?: boolean;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n const {\n title,\n columns,\n rows,\n labels,\n undoPrevious = false,\n importDimensions = false,\n overwriteCells = false,\n } = params;\n\n // Build metadata columns\n const metadataColumns = columns.map((col) => {\n switch (col.type) {\n case 'DIMENSION_TABLE':\n return {\n type: 'DIMENSION_TABLE' as const,\n dimensionTableName: col.dimensionTableName!,\n columnName: col.columnName,\n };\n case 'VARIABLE':\n return {\n type: 'VARIABLE' as const,\n variableName: col.variableName!,\n columnName: col.columnName || col.variableName!,\n dimensionsNames: col.dimensionsNames,\n };\n case 'DATE':\n return {\n type: 'DATE' as const,\n dateFormat: col.dateFormat!,\n columnName: col.columnName,\n };\n case 'DESCRIPTION':\n return {\n type: 'DESCRIPTION' as const,\n columnName: col.columnName,\n };\n default:\n return {\n type: 'NONE' as const,\n columnName: col.columnName,\n };\n }\n });\n\n // Build metadata\n const metadata = await nativeClient.buildImportJobMetadata(metadataColumns as any);\n\n if (overwriteCells) {\n (metadata as any).overwriteCells = true;\n }\n\n // Create import job\n const importActions = await nativeClient.createImportJob({\n title,\n metadata,\n labels,\n });\n\n // Add rows\n await importActions.addRows(rows as any);\n await importActions.flushRows();\n\n // Import dimensions if needed\n if (importDimensions) {\n await importActions.importDimensions();\n }\n\n // Undo previous if needed\n if (undoPrevious) {\n await importActions.undoPrevious();\n }\n\n // Commit\n const report = await importActions.commit();\n\n return successResponse({\n tenant,\n title,\n rowCount: rows.length,\n labels: labels || [],\n undoPrevious,\n importDimensions,\n overwriteCells,\n commitReport: report,\n });\n } catch (error) {\n return errorResponse(`Import job failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_file - Create or update file on instance\n server.tool(\n 'farseer_create_file',\n `Create or update a file on a Farseer instance.\n\nThis creates a file in the specified folder on the Farseer file system.\nIf a file with the same name already exists in that folder, it will be updated.\n\nThe folderPath is an array of folder names, starting from the root.\nDefault is [\"Files\"] which is the standard files folder.\n\nCommon use cases:\n- Creating CSV report files\n- Uploading configuration files\n- Saving processed data outputs`,\n createFileSchema,\n async (params: { fileName: string; folderPath?: string[]; content: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client, native: nativeClient } = gate.session;\n\n try {\n const folderPath = params.folderPath || ['Files'];\n // Not nativeClient.getItemByPath: for a single-segment path that\n // name-searches the whole tenant and refuses on more than one\n // loose match, so a second folder called \"Files\" breaks it.\n const folder = await client.getFolderByPath(folderPath);\n if (!folder) {\n return errorResponse(`Folder \"${folderPath.join('/')}\" not found`, 'NOT_FOUND');\n }\n const buffer = Buffer.from(params.content, 'utf-8');\n\n await nativeClient.createOrUpdateFarseerFile(\n { name: params.fileName, folderId: folder.id } as any,\n buffer,\n );\n\n return successResponse({\n tenant,\n fileName: params.fileName,\n folderPath,\n size: buffer.length,\n message: `File \"${params.fileName}\" created/updated in ${folderPath.join('/')}`,\n });\n } catch (error) {\n return errorResponse(`Create file failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n\n/**\n * Export variable data as CSV using evaluatorExport (works on all server versions).\n * Falls back to exportFormula if evaluatorExport fails.\n */\n/**\n * Export variable data as CSV using exportFormula.\n * Wraps the variable name in quotes as required by the API.\n * Supports dimension filters: [[\"Months\",\"M1\"],[\"Brand\",\"0000032\"]]\n * becomes sum(\"VarName\", \"Months\">\"M1\", \"Brand\">\"0000032\")\n */\nasync function exportVariableAsCsv(\n client: farseer.FarseerClient,\n variableName: string,\n limit?: number,\n filters?: Array<Array<string>>,\n): Promise<string> {\n let formula: string;\n if (filters && filters.length > 0) {\n const filterParts = filters.map(([table, member]) => `\"${table}\">\"${member}\"`).join(', ');\n formula = `sum(\"${variableName}\", ${filterParts})`;\n } else {\n formula = `\"${variableName}\"`;\n }\n\n const blob = await client.export.exportFormula({\n formula,\n format: farseer.ExportFormat.Csv,\n limit,\n });\n return await blob.text();\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,iBAAkB;AAClB,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,cAAyB;AACzB,qBAA+B;AAC/B,qBAA+C;AAC/C,4BAAkC;AAGlC,MAAM,2BAA2B;AAAA,EAC7B,cAAc,aAAE,OAAO,EAAE,SAAS,gCAAgC;AAAA,EAClE,SAAS,aACJ,MAAM,aAAE,MAAM,aAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,EACnC,SAAS,EACT;AAAA,IACG;AAAA,EACJ;AAAA,EACJ,QAAQ,aAAE,KAAK,CAAC,OAAO,MAAM,CAAC,EAAE,SAAS,EAAE,SAAS,8BAA8B;AAAA,EAClF,OAAO,aAAE,OAAO,EAAE,SAAS,EAAE,SAAS,kCAAkC;AAC5E;AAEA,MAAM,yBAAyB;AAAA,EAC3B,cAAc,aAAE,OAAO,EAAE,SAAS,8BAA8B;AAAA,EAChE,YAAY,aAAE,MAAM,aAAE,OAAO,CAAC,EAAE,SAAS,EAAE,SAAS,2DAA2D;AACnH;AAEA,MAAM,wBAAwB;AAAA,EAC1B,OAAO,aAAE,OAAO,EAAE,SAAS,4CAA4C;AAAA,EACvE,SAAS,aACJ;AAAA,IACG,aAAE,OAAO;AAAA,MACL,MAAM,aAAE,KAAK,CAAC,mBAAmB,YAAY,QAA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UACnB;AAAA,UACA,UAAU,OAAO;AAAA,UACjB;AAAA,UACA,MAAM,OAAO;AAAA,UACb,SAAS,SAAS,OAAO,QAAQ,wBAAwB,WAAW,KAAK,GAAG,CAAC;AAAA,QACjF,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,8BAAc,uBAAuB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MACjG;AAAA,IACJ;AAAA,EACJ;AACJ;AAYA,eAAe,oBACX,QACA,cACA,OACA,SACe;AACf,MAAI;AACJ,MAAI,WAAW,QAAQ,SAAS,GAAG;AAC/B,UAAM,cAAc,QAAQ,IAAI,CAAC,CAAC,OAAO,MAAM,MAAM,IAAI,KAAK,MAAM,MAAM,GAAG,EAAE,KAAK,IAAI;AACxF,cAAU,QAAQ,YAAY,MAAM,WAAW;AAAA,EACnD,OAAO;AACH,cAAU,IAAI,YAAY;AAAA,EAC9B;AAEA,QAAM,OAAO,MAAM,OAAO,OAAO,cAAc;AAAA,IAC3C;AAAA,IACA,QAAQ,QAAQ,aAAa;AAAA,IAC7B;AAAA,EACJ,CAAC;AACD,SAAO,MAAM,KAAK,KAAK;AAC3B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -41,29 +41,7 @@ var import_errorFormatter = require("../../utils/errorFormatter");
|
|
|
41
41
|
var import_folderMatch = require("../../utils/folderMatch");
|
|
42
42
|
var farseer = __toESM(require("farseer-client"));
|
|
43
43
|
var import_farseer_client = require("farseer-client");
|
|
44
|
-
|
|
45
|
-
sum: "SUM",
|
|
46
|
-
average: "AVERAGE",
|
|
47
|
-
avg: "AVERAGE",
|
|
48
|
-
min: "MIN",
|
|
49
|
-
max: "MAX",
|
|
50
|
-
none: "NONE",
|
|
51
|
-
formula: "FORMULA",
|
|
52
|
-
closingstate: "CLOSING STATE",
|
|
53
|
-
"closing state": "CLOSING STATE",
|
|
54
|
-
"closing-state": "CLOSING STATE",
|
|
55
|
-
beginningstate: "BEGINNING STATE",
|
|
56
|
-
"beginning state": "BEGINNING STATE",
|
|
57
|
-
"beginning-state": "BEGINNING STATE"
|
|
58
|
-
};
|
|
59
|
-
function normalizeRollupType(value) {
|
|
60
|
-
const normalized = ROLLUP_TYPE_MAP[value.toLowerCase()];
|
|
61
|
-
if (!normalized) {
|
|
62
|
-
const validTypes = [...new Set(Object.values(ROLLUP_TYPE_MAP))].join(", ");
|
|
63
|
-
throw new Error(`Invalid rollupType "${value}". Valid types: ${validTypes}`);
|
|
64
|
-
}
|
|
65
|
-
return normalized;
|
|
66
|
-
}
|
|
44
|
+
var import_variableValues = require("../../utils/variableValues");
|
|
67
45
|
const evaluateFormulaSchema = {
|
|
68
46
|
formula: import_zod.z.string().describe("Formula expression to evaluate (e.g., variable name or calculation)"),
|
|
69
47
|
filters: import_zod.z.array(import_zod.z.array(import_zod.z.string()).length(2)).optional().describe('Dimension filters as [tableName, memberName] pairs (e.g., [["Years","2024"],["Months","Jan"]])')
|
|
@@ -85,7 +63,7 @@ const createVariableSchema = {
|
|
|
85
63
|
dimensions: import_zod.z.array(import_zod.z.string()).optional().describe("Dimension table names this variable spans"),
|
|
86
64
|
formula: import_zod.z.string().optional().describe("Formula expression"),
|
|
87
65
|
rollupType: import_zod.z.string().optional().describe("Rollup type (Sum, Average, Min, Max, None, Formula, Closing State, Beginning State)"),
|
|
88
|
-
dataType: import_zod.z.string().optional().describe("Data type (Decimal, Integer
|
|
66
|
+
dataType: import_zod.z.string().optional().describe("Data type (Decimal, Integer)"),
|
|
89
67
|
description: import_zod.z.string().optional().describe("Variable description"),
|
|
90
68
|
readonly: import_zod.z.boolean().optional().describe("Whether the variable is read-only"),
|
|
91
69
|
measure: import_zod.z.boolean().optional().describe("Set to true for dimensionless formula variables (measure mode)"),
|
|
@@ -688,8 +666,8 @@ Example:
|
|
|
688
666
|
tableGids.push(table.id);
|
|
689
667
|
}
|
|
690
668
|
}
|
|
691
|
-
const rollupType = normalizeRollupType(params.rollupType || "SUM");
|
|
692
|
-
const dataType = (params.dataType || "DECIMAL")
|
|
669
|
+
const rollupType = (0, import_variableValues.normalizeRollupType)(params.rollupType || "SUM");
|
|
670
|
+
const dataType = (0, import_variableValues.normalizeDataType)(params.dataType || "DECIMAL");
|
|
693
671
|
const createEntity = {
|
|
694
672
|
type: import_farseer_client.EntityType.Variable,
|
|
695
673
|
meta: {
|
|
@@ -769,20 +747,7 @@ Updatable fields:
|
|
|
769
747
|
name: params.newName || variable.name,
|
|
770
748
|
description: params.description !== void 0 ? params.description : current.meta?.description ?? null
|
|
771
749
|
},
|
|
772
|
-
variable:
|
|
773
|
-
notes: currentVar.notes ?? null,
|
|
774
|
-
tableGids: currentVar.tableGids || [],
|
|
775
|
-
memberGids: currentVar.memberGids || [],
|
|
776
|
-
rollupType: currentVar.rollupType || "SUM",
|
|
777
|
-
dataType: currentVar.dataType || "DECIMAL",
|
|
778
|
-
topDownMapping: currentVar.topDownMapping ?? null,
|
|
779
|
-
measure: currentVar.measure || false,
|
|
780
|
-
readonly: currentVar.readonly || false,
|
|
781
|
-
calculateOnDemand: currentVar.calculateOnDemand || false,
|
|
782
|
-
zConstraint: currentVar.zConstraint || false,
|
|
783
|
-
optimizeCalculation: currentVar.optimizeCalculation ?? true
|
|
784
|
-
// referencedBy is readOnly - do NOT send in update requests
|
|
785
|
-
}
|
|
750
|
+
variable: (0, import_variableValues.writableVariable)(currentVar)
|
|
786
751
|
};
|
|
787
752
|
if (params.dimensions) {
|
|
788
753
|
const tableGids = [];
|
|
@@ -793,7 +758,7 @@ Updatable fields:
|
|
|
793
758
|
updateEntity.variable.tableGids = tableGids;
|
|
794
759
|
}
|
|
795
760
|
if (params.rollupType) {
|
|
796
|
-
updateEntity.variable.rollupType = normalizeRollupType(params.rollupType);
|
|
761
|
+
updateEntity.variable.rollupType = (0, import_variableValues.normalizeRollupType)(params.rollupType);
|
|
797
762
|
}
|
|
798
763
|
if (params.readonly !== void 0) {
|
|
799
764
|
updateEntity.variable.readonly = params.readonly;
|