farseer-cli 1.11.2 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -10
- package/dist/commands/app.js +54 -4
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/login.js +60 -26
- package/dist/commands/login.js.map +2 -2
- package/dist/commands/logout.js +37 -12
- package/dist/commands/logout.js.map +3 -3
- package/dist/commands/run.js +10 -27
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/whoami.js +10 -14
- package/dist/commands/whoami.js.map +2 -2
- package/dist/mcp/prompts/workflows.js +2 -0
- package/dist/mcp/prompts/workflows.js.map +2 -2
- package/dist/mcp/tools/appTools.js +54 -4
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +5 -2
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +5 -18
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +16 -6
- package/dist/mcp/utils/helpers.js.map +3 -3
- package/dist/mcp/utils/session.js +14 -9
- package/dist/mcp/utils/session.js.map +2 -2
- package/dist/services/appSyncService.js +33 -1
- package/dist/services/appSyncService.js.map +2 -2
- package/dist/services/apps.js +199 -9
- package/dist/services/apps.js.map +3 -3
- package/dist/services/authErrors.js +2 -2
- package/dist/services/authErrors.js.map +2 -2
- package/dist/services/configService.js +45 -9
- package/dist/services/configService.js.map +2 -2
- package/dist/services/credentials.js +10 -7
- package/dist/services/credentials.js.map +2 -2
- package/dist/services/farseerService.js +95 -36
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/preflight.js +3 -2
- package/dist/services/preflight.js.map +2 -2
- package/dist/services/realms.js +67 -0
- package/dist/services/realms.js.map +7 -0
- package/docs/cli-guide.md +16 -0
- package/package.json +1 -1
|
@@ -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 { AppArgument, AppDeleteRefusedError, AppUpdateChanges, applySourceFolderChange } 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\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};\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 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 },\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\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- 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 }) => {\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 const reference = app.id.toString();\n await client.updateApp(reference, changes, app);\n\n return successResponse({\n tenant,\n appName: params.newName || app.name,\n updated: Object.keys(changes),\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;AAOA,iBAAkB;AAClB,qBAA+B;AAC/B,
|
|
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;A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AA,IACE;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA;AAAA,IACA,OAAO,WAAiD;AACpD,YAAM,OAAO,UAAM,+BAAe;AAClC,UAAI,CAAC,KAAK,GAAI,QAAO,KAAK;AAC1B,YAAM,EAAE,QAAQ,OAAO,IAAI,KAAK;AAEhC,UAAI;AACA,cAAM,aAAa,UAAM,qCAAqB,QAAQ;AAAA,UAClD,SAAS,OAAO;AAAA,UAChB,IAAI,OAAO;AAAA,QACf,CAAC;AACD,YAAI,WAAW,YAAY;AACvB,iBAAO,WAAW;AAAA,QACtB;AACA,cAAM,UAAU,WAAW;AAE3B,cAAM,OAAO,UAAU,QAAQ,SAAS;AAGxC,cAAM,YAAY,MAAM,OAAO,SAAS;AACxC,YAAI,UAAU,KAAK,CAAC,MAAM,EAAE,cAAc,QAAQ,SAAS,GAAG;AAC1D,qBAAO;AAAA,YACH,gCAAgC,QAAQ,IAAI;AAAA,YAC5C;AAAA,UACJ;AAAA,QACJ;AAEA,mBAAO,gCAAgB;AAAA,UACnB;AAAA,UACA,YAAY,QAAQ;AAAA,UACpB,SAAS,QAAQ,QAAQ,IAAI;AAAA,QACjC,CAAC;AAAA,MACL,SAAS,OAAO;AAGZ,mBAAO;AAAA,UACH,sBAAsB,UAAM,yCAAkB,KAAK,CAAC;AAAA,UACpD,iBAAiB,oCAAwB,qBAAqB;AAAA,QAClE;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": ["s"]
|
|
7
7
|
}
|
|
@@ -37,11 +37,12 @@ function registerAuthTools(server) {
|
|
|
37
37
|
`Check Farseer authentication status and the tenant this session is bound to.
|
|
38
38
|
|
|
39
39
|
Returns:
|
|
40
|
-
- Whether a JWT (browser login) is valid and when it expires
|
|
40
|
+
- Whether a JWT (browser login) is valid for this tenant's Keycloak realm, and when it expires
|
|
41
|
+
- Every browser login, one per realm
|
|
41
42
|
- The tenant this session operates on, and whether it is locked
|
|
42
43
|
- Tenants with API keys configured
|
|
43
44
|
|
|
44
|
-
If not authenticated, run "farseer login" in a terminal.`,
|
|
45
|
+
If not authenticated, run "farseer login --org <organisation>" in a terminal.`,
|
|
45
46
|
{},
|
|
46
47
|
async () => {
|
|
47
48
|
const status = (0, import_helpers.getAuthStatus)();
|
|
@@ -51,6 +52,8 @@ If not authenticated, run "farseer login" in a terminal.`,
|
|
|
51
52
|
return (0, import_helpers.successResponse)({
|
|
52
53
|
jwtValid: status.jwtValid,
|
|
53
54
|
jwtExpiresAt: status.jwtExpiresAt,
|
|
55
|
+
jwtRealm: status.jwtRealm,
|
|
56
|
+
logins: status.logins,
|
|
54
57
|
tenant: pin,
|
|
55
58
|
tenantLocked: !!pin,
|
|
56
59
|
configuredTenants: status.configuredTenants,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/authTools.ts"],
|
|
4
|
-
"sourcesContent": ["/** Authentication and tenant binding. See tenantPin.ts for the binding rules. */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { getTenantOrg } from '../../services/configService';\nimport { openTenantSession } from '../../services/preflight';\nimport {\n getAuthStatus,\n successResponse,\n errorResponse,\n describeSessionFailure,\n describeSessionWarning,\n} from '../utils/helpers';\nimport { getSessionWarning, rememberSession } from '../utils/session';\nimport { selectTenant, getTenantPin, isLaunchPinned } from '../utils/tenantPin';\n\n// Defined outside registration to avoid deep zod type instantiation.\nconst selectTenantSchema = {\n tenant: z.string().describe('Tenant to bind this session to (e.g. \"salvus-prodaja\"), from the user\\'s request.'),\n organisation: z\n .string()\n .optional()\n .describe('Organisation subdomain. Defaults to the saved mapping for the tenant, else the tenant name.'),\n};\n\nexport function registerAuthTools(server: McpServer): void {\n // farseer_whoami - Auth status + the tenant this session is bound to\n server.tool(\n 'farseer_whoami',\n `Check Farseer authentication status and the tenant this session is bound to.\n\nReturns:\n- Whether a JWT (browser login) is valid and when it expires\n- The tenant this session operates on, and whether it is locked\n- Tenants with API keys configured\n\nIf not authenticated, run \"farseer login
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAkB;AAClB,2BAA6B;AAC7B,uBAAkC;AAClC,qBAMO;AACP,qBAAmD;AACnD,uBAA2D;AAG3D,MAAM,qBAAqB;AAAA,EACvB,QAAQ,aAAE,OAAO,EAAE,SAAS,kFAAmF;AAAA,EAC/G,cAAc,aACT,OAAO,EACP,SAAS,EACT,SAAS,6FAA6F;AAC/G;AAEO,SAAS,kBAAkB,QAAyB;AAEvD,SAAO;AAAA,IACH;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["/** Authentication and tenant binding. See tenantPin.ts for the binding rules. */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { getTenantOrg } from '../../services/configService';\nimport { openTenantSession } from '../../services/preflight';\nimport {\n getAuthStatus,\n successResponse,\n errorResponse,\n describeSessionFailure,\n describeSessionWarning,\n} from '../utils/helpers';\nimport { getSessionWarning, rememberSession } from '../utils/session';\nimport { selectTenant, getTenantPin, isLaunchPinned } from '../utils/tenantPin';\n\n// Defined outside registration to avoid deep zod type instantiation.\nconst selectTenantSchema = {\n tenant: z.string().describe('Tenant to bind this session to (e.g. \"salvus-prodaja\"), from the user\\'s request.'),\n organisation: z\n .string()\n .optional()\n .describe('Organisation subdomain. Defaults to the saved mapping for the tenant, else the tenant name.'),\n};\n\nexport function registerAuthTools(server: McpServer): void {\n // farseer_whoami - Auth status + the tenant this session is bound to\n server.tool(\n 'farseer_whoami',\n `Check Farseer authentication status and the tenant this session is bound to.\n\nReturns:\n- Whether a JWT (browser login) is valid for this tenant's Keycloak realm, and when it expires\n- Every browser login, one per realm\n- The tenant this session operates on, and whether it is locked\n- Tenants with API keys configured\n\nIf not authenticated, run \"farseer login --org <organisation>\" in a terminal.`,\n {},\n async () => {\n const status = getAuthStatus();\n const pin = status.tenant;\n const message = !pin\n ? 'No tenant selected yet. Tell me which tenant/client to work on and I will call farseer_select_tenant to connect (once per session).'\n : status.launchPinned\n ? `This session is locked to tenant \"${pin.tenant}\" (org: ${pin.organisation}), fixed at launch.`\n : `This session is working on tenant \"${pin.tenant}\" (org: ${pin.organisation}), selected and locked for the session.`;\n const warning = getSessionWarning();\n return successResponse({\n jwtValid: status.jwtValid,\n jwtExpiresAt: status.jwtExpiresAt,\n jwtRealm: status.jwtRealm,\n logins: status.logins,\n tenant: pin,\n tenantLocked: !!pin,\n configuredTenants: status.configuredTenants,\n warning: warning && describeSessionWarning(warning),\n message: warning ? `${message} ${describeSessionWarning(warning)}` : message,\n });\n },\n );\n\n // farseer_select_tenant - Bind this session to a tenant, once\n server.tool(\n 'farseer_select_tenant',\n `Bind this MCP session to a Farseer tenant. Call this once when the user says which tenant/client to work on.\n\nRules:\n- Works only if the server was launched without --tenant. If it was launched with --tenant, it is already locked and this returns an error.\n- Can be called only ONCE. After the first selection the tenant is locked for the session and cannot be changed. To work on a different tenant, start a new session.\n- The tenant must be reachable (you must be logged in). If it can't be connected \u2014 wrong name or not logged in \u2014 selection fails WITHOUT locking, so you can correct it and call again.\n\nUse this before any other farseer tool when no tenant is set yet (farseer_whoami tells you).`,\n selectTenantSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { tenant: string; organisation?: string }) => {\n const { tenant, organisation } = params;\n\n // A locked session can't change tenant. Reject before any network\n // call, and don't verify a tenant we won't bind to.\n if (isLaunchPinned()) {\n return errorResponse(\n `This server is pinned to tenant \"${getTenantPin()!.tenant}\" via --tenant; the tenant cannot be changed from here.`,\n 'VALIDATION_ERROR',\n );\n }\n const bound = getTenantPin();\n if (bound) {\n return errorResponse(\n `This session is already working on tenant \"${bound.tenant}\" and the tenant cannot be changed. Start a new session to use a different tenant.`,\n 'VALIDATION_ERROR',\n );\n }\n\n const org = organisation || getTenantOrg(tenant) || tenant;\n\n // Before locking: selection is one-shot, so this is the last moment a\n // wrong organisation is still correctable. Costs no extra round trip.\n const outcome = await openTenantSession(org, tenant);\n if (!outcome.ok) {\n return describeSessionFailure(outcome.failure, 'Correct it and call farseer_select_tenant again.');\n }\n\n const result = selectTenant({ organisation: org, tenant });\n if (!result.ok) {\n // Lost a race to a concurrent selection between the check above\n // and here \u2014 treat as already-bound.\n return errorResponse(\n `This session is already working on tenant \"${result.current.tenant}\" and the tenant cannot be changed. Start a new session to use a different tenant.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // The pair is proven and can no longer change, so the first tool call\n // has nothing left to ask.\n rememberSession(result.checkout, outcome.auth, outcome.warning);\n\n const selected = `Selected tenant \"${result.checkout.tenant}\" (org: ${result.checkout.organisation}). This session is now locked to it for its lifetime.`;\n return successResponse({\n tenant: result.checkout,\n warning: outcome.warning && describeSessionWarning(outcome.warning),\n message: outcome.warning ? `${selected} ${describeSessionWarning(outcome.warning)}` : selected,\n });\n },\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAkB;AAClB,2BAA6B;AAC7B,uBAAkC;AAClC,qBAMO;AACP,qBAAmD;AACnD,uBAA2D;AAG3D,MAAM,qBAAqB;AAAA,EACvB,QAAQ,aAAE,OAAO,EAAE,SAAS,kFAAmF;AAAA,EAC/G,cAAc,aACT,OAAO,EACP,SAAS,EACT,SAAS,6FAA6F;AAC/G;AAEO,SAAS,kBAAkB,QAAyB;AAEvD,SAAO;AAAA,IACH;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASA,CAAC;AAAA,IACD,YAAY;AACR,YAAM,aAAS,8BAAc;AAC7B,YAAM,MAAM,OAAO;AACnB,YAAM,UAAU,CAAC,MACX,wIACA,OAAO,eACL,qCAAqC,IAAI,MAAM,W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;AAE9D,YAAM,WAAW,oBAAoB,OAAO,SAAS,MAAM,WAAW,OAAO,SAAS,YAAY;AAClG,iBAAO,gCAAgB;AAAA,QACnB,QAAQ,OAAO;AAAA,QACf,SAAS,QAAQ,eAAW,uCAAuB,QAAQ,OAAO;AAAA,QAClE,SAAS,QAAQ,UAAU,GAAG,QAAQ,QAAI,uCAAuB,QAAQ,OAAO,CAAC,KAAK;AAAA,MAC1F,CAAC;AAAA,IACL;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -38,6 +38,7 @@ var path = __toESM(require("path"));
|
|
|
38
38
|
var import_session = require("../utils/session");
|
|
39
39
|
var import_configService = require("../../services/configService");
|
|
40
40
|
var import_farseerService = require("../../services/farseerService");
|
|
41
|
+
var import_realms = require("../../services/realms");
|
|
41
42
|
var import_helpers = require("../../utils/helpers");
|
|
42
43
|
var import_packageManager = require("../../utils/packageManager");
|
|
43
44
|
var import_helpers2 = require("../utils/helpers");
|
|
@@ -67,27 +68,13 @@ async function getRunCredentials(organisation, tenant) {
|
|
|
67
68
|
basePath: credential.basePath
|
|
68
69
|
};
|
|
69
70
|
}
|
|
70
|
-
const
|
|
71
|
-
if (!
|
|
71
|
+
const accessToken = await (0, import_farseerService.getFreshAccessToken)(await (0, import_realms.realmForOrganisation)(organisation));
|
|
72
|
+
if (!accessToken) {
|
|
72
73
|
return null;
|
|
73
74
|
}
|
|
74
|
-
if (!(0, import_configService.isUserAuthValid)()) {
|
|
75
|
-
const refreshed = await (0, import_farseerService.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
|
|
76
|
-
if (!refreshed) {
|
|
77
|
-
return null;
|
|
78
|
-
}
|
|
79
|
-
(0, import_configService.setUserAuth)({
|
|
80
|
-
accessToken: refreshed.accessToken,
|
|
81
|
-
refreshToken: refreshed.refreshToken,
|
|
82
|
-
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
83
|
-
realm: auth.realm
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
const updatedAuth = (0, import_configService.getUserAuth)();
|
|
87
|
-
if (!updatedAuth) return null;
|
|
88
75
|
return {
|
|
89
76
|
tenantId: tenant,
|
|
90
|
-
accessToken
|
|
77
|
+
accessToken,
|
|
91
78
|
basePath: (0, import_configService.generateBasePath)(organisation)
|
|
92
79
|
};
|
|
93
80
|
}
|
|
@@ -148,7 +135,7 @@ Arguments not overridden use their default values from app config.`,
|
|
|
148
135
|
}
|
|
149
136
|
const credentials = await getRunCredentials(organisation, tenant);
|
|
150
137
|
if (!credentials) {
|
|
151
|
-
return (0, import_helpers2.authRequiredResponse)(tenant);
|
|
138
|
+
return (0, import_helpers2.authRequiredResponse)(tenant, organisation);
|
|
152
139
|
}
|
|
153
140
|
const tenantDir = (0, import_helpers.getTenantDir)(tenant);
|
|
154
141
|
const srcDir = (0, import_helpers.getTenantSrcDir)(tenant);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/runTools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * App Execution Tools\n *\n * Tools for running Farseer apps locally.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { requireSession } from '../utils/session';\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n setUserAuth,\n generateBasePath,\n} from '../../services/configService';\nimport { refreshAccessToken } from '../../services/farseerService';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir } from '../../utils/helpers';\nimport { ensurePackageJson, parsePackageSpec } from '../../utils/packageManager';\nimport {\n getSessionTenant,\n successResponse,\n errorResponse,\n authRequiredResponse,\n tenantRequiredResponse,\n resolveAppForMcp,\n} from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n/**\n * Find a script file recursively in a directory.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) return null;\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n if (item.isFile() && item.name === scriptName) return itemRelPath;\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n return null;\n };\n return search(baseDir);\n}\n\ninterface RunCredentials {\n tenantId: string;\n apiKey?: string;\n accessToken?: string;\n basePath: string;\n}\n\nasync function getRunCredentials(organisation: string, tenant: string): Promise<RunCredentials | null> {\n // First try API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // Try user auth (browser login)\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n\n // Check if token needs refresh\n if (!isUserAuthValid()) {\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n }\n\n const updatedAuth = getUserAuth();\n if (!updatedAuth) return null;\n\n return {\n tenantId: tenant,\n accessToken: updatedAuth.accessToken,\n basePath: generateBasePath(organisation),\n };\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst runAppSchema = {\n appName: z.string().optional().describe('Name of the app to run. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n argumentOverrides: z\n .record(z.string(), z.string())\n .optional()\n .describe('Override argument values (Name: Value pairs)'),\n};\n\nexport function registerRunTools(server: McpServer): void {\n // farseer_run_app - Run an app locally\n server.tool(\n 'farseer_run_app',\n `Run a Farseer app locally.\n\nThis executes the app's entrypoint script using npx tsx with credentials automatically injected.\nThe script's FarseerClient() constructor picks up the injected env vars - no hardcoded credentials needed.\n\nHow it works:\n1. Looks up app configuration to find the entrypoint script\n2. Injects credentials as environment variables:\n - TENANT_ID: The tenant identifier\n - FARSEER_URL: Base API URL (e.g., https://myorg.farseer.io/api/v3)\n - FARSEER_API_KEY or FARSEER_TOKEN: Authentication credentials from login\n3. Passes app arguments via command line in the order defined by app config\n4. Executes the script using npx tsx in the tenant directory\n\nRequirements:\n- Scripts must be pulled locally first (farseer_pull)\n- Dependencies must be installed (run \"farseer install <tenant>\" in terminal)\n- All CLI commands must be run from the repository root (the directory containing farseer-apps/)\n\nArguments can be overridden using the argumentOverrides parameter.\nArguments not overridden use their default values from app config.`,\n runAppSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { appName?: string; appId?: string; argumentOverrides?: Record<string, string> }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client } = gate.session;\n\n try {\n // Get app details\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 runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n return errorResponse(\n `App \"${app.name}\" has no scripts configured. Configure it with farseer_configure_app.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Find entrypoint script\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n return errorResponse(`Entrypoint script not found for app \"${app.name}\"`, 'NOT_FOUND');\n }\n\n // Get run credentials\n const credentials = await getRunCredentials(organisation, tenant);\n if (!credentials) {\n return authRequiredResponse(tenant);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Normalize script name - strip Scripts/ prefix if present\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Find script: try Scripts/ first, then search recursively in files/\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try full relative path under files/ first (e.g. Scripts/MyApp/index.ts \u2192 files/Scripts/MyApp/index.ts)\n const fullRelPath = path.resolve(filesDir, mainScript.name);\n if (fs.existsSync(fullRelPath)) {\n scriptPath = fullRelPath;\n relativeScriptPath = `files/${mainScript.name}`;\n } else {\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n }\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n return errorResponse(\n `Script not found locally: ${scriptName}. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n return errorResponse(\n `Dependencies not installed. Run \"farseer install ${tenant}\" in terminal first.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Build arguments\n const appArgs: Record<string, string> = {};\n\n // Start with defaults. defaultValue is optional on the API\n // type; treat missing as '' so we always hand a string to\n // the runner.\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue ?? '';\n }\n\n // Apply overrides\n if (params.argumentOverrides) {\n for (const [name, value] of Object.entries(params.argumentOverrides)) {\n appArgs[name] = value;\n }\n }\n\n // Build environment\n const envVars: Record<string, string> = {\n ...(process.env as Record<string, string>),\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_TOKEN = credentials.accessToken;\n }\n\n // Build command line arguments (in order)\n const cmdArgs: string[] = [];\n for (const arg of app.expectedArguments) {\n cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue ?? '');\n }\n\n // Run the script\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npx', ['tsx', relativeScriptPath, ...cmdArgs], {\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n resolve(\n successResponse({\n tenant,\n app: app.name,\n script: mainScript.name,\n arguments: appArgs,\n exitCode: code ?? 0,\n stdout: stdout.slice(0, 10000), // Limit output size\n stderr: stderr.slice(0, 5000),\n truncated: stdout.length > 10000 || stderr.length > 5000,\n }),\n );\n });\n\n child.on('error', (err) => {\n resolve(\n errorResponse(\n `Failed to run script: ${err.message}. Make sure tsx is installed: npm install -g tsx`,\n 'UNKNOWN',\n ),\n );\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('Script execution timed out after 5 minutes', 'UNKNOWN'));\n },\n 5 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Run app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_install - Install dependencies for a tenant\n server.tool(\n 'farseer_install',\n `Install npm dependencies for a Farseer tenant.\n\nEnsures the tenant directory has a package.json with farseer-client, then runs npm install.\nIf package.json doesn't exist, it is auto-created with farseer-client as a dependency.\n\nYou can also add extra npm packages (e.g., axios, lodash) that a script needs.\nThese are added to package.json and installed in one step.\n\nTypical workflow:\n1. farseer_pull \u2192 farseer_install \u2192 farseer_run_app\n\nAll commands must run from the repository root (the directory containing farseer-apps/).`,\n {\n packages: z\n .array(z.string())\n .optional()\n .describe('Additional npm packages to install (e.g., [\"axios\", \"lodash@4\"])'),\n },\n async (params: { packages?: string[] }) => {\n // Not behind requireSession: this never reaches the tenant, so there\n // is nothing to validate. `farseer install` is excluded for the same reason.\n const resolved = getSessionTenant();\n if (!resolved) return tenantRequiredResponse();\n const { tenant } = resolved;\n\n const tenantDir = getTenantDir(tenant);\n\n if (!fs.existsSync(tenantDir)) {\n return errorResponse(\n `Tenant folder not found: farseer-apps/${tenant}/. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n try {\n // Auto-create or update package.json using shared utility\n const addedPackages = [...ensurePackageJson(tenantDir, tenant)];\n\n // Add extra packages if requested\n if (params.packages && params.packages.length > 0) {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n pkg.dependencies = pkg.dependencies || {};\n\n for (const pkgSpec of params.packages) {\n const { name, version } = parsePackageSpec(pkgSpec);\n if (!pkg.dependencies[name]) {\n pkg.dependencies[name] = version;\n addedPackages.push(pkgSpec);\n }\n }\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n }\n\n // Run npm install\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npm', ['install'], {\n cwd: tenantDir,\n shell: true,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n resolve(\n successResponse({\n tenant,\n tenantDir: `farseer-apps/${tenant}/`,\n addedPackages,\n exitCode: 0,\n message: `Dependencies installed successfully${addedPackages.length ? ` (${addedPackages.join(', ')})` : ''}`,\n }),\n );\n } else {\n resolve(\n errorResponse(\n `npm install failed (exit code ${code}):\\n${stderr.slice(0, 3000)}`,\n 'UNKNOWN',\n ),\n );\n }\n });\n\n child.on('error', (err) => {\n resolve(errorResponse(`Failed to run npm install: ${err.message}`, 'UNKNOWN'));\n });\n\n // Timeout after 2 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('npm install timed out after 2 minutes', 'UNKNOWN'));\n },\n 2 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Install failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,2BAAsB;AACtB,SAAoB;AACpB,WAAsB;AACtB,qBAA+B;AAC/B,
|
|
4
|
+
"sourcesContent": ["/**\n * App Execution Tools\n *\n * Tools for running Farseer apps locally.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { requireSession } from '../utils/session';\nimport { getCredential, generateBasePath } from '../../services/configService';\nimport { getFreshAccessToken } from '../../services/farseerService';\nimport { realmForOrganisation } from '../../services/realms';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir } from '../../utils/helpers';\nimport { ensurePackageJson, parsePackageSpec } from '../../utils/packageManager';\nimport {\n getSessionTenant,\n successResponse,\n errorResponse,\n authRequiredResponse,\n tenantRequiredResponse,\n resolveAppForMcp,\n} from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n/**\n * Find a script file recursively in a directory.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) return null;\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n if (item.isFile() && item.name === scriptName) return itemRelPath;\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n return null;\n };\n return search(baseDir);\n}\n\ninterface RunCredentials {\n tenantId: string;\n apiKey?: string;\n accessToken?: string;\n basePath: string;\n}\n\nasync function getRunCredentials(organisation: string, tenant: string): Promise<RunCredentials | null> {\n // First try API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // Try user auth (browser login) for the organisation's realm\n const accessToken = await getFreshAccessToken(await realmForOrganisation(organisation));\n if (!accessToken) {\n return null;\n }\n\n return {\n tenantId: tenant,\n accessToken,\n basePath: generateBasePath(organisation),\n };\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst runAppSchema = {\n appName: z.string().optional().describe('Name of the app to run. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n argumentOverrides: z\n .record(z.string(), z.string())\n .optional()\n .describe('Override argument values (Name: Value pairs)'),\n};\n\nexport function registerRunTools(server: McpServer): void {\n // farseer_run_app - Run an app locally\n server.tool(\n 'farseer_run_app',\n `Run a Farseer app locally.\n\nThis executes the app's entrypoint script using npx tsx with credentials automatically injected.\nThe script's FarseerClient() constructor picks up the injected env vars - no hardcoded credentials needed.\n\nHow it works:\n1. Looks up app configuration to find the entrypoint script\n2. Injects credentials as environment variables:\n - TENANT_ID: The tenant identifier\n - FARSEER_URL: Base API URL (e.g., https://myorg.farseer.io/api/v3)\n - FARSEER_API_KEY or FARSEER_TOKEN: Authentication credentials from login\n3. Passes app arguments via command line in the order defined by app config\n4. Executes the script using npx tsx in the tenant directory\n\nRequirements:\n- Scripts must be pulled locally first (farseer_pull)\n- Dependencies must be installed (run \"farseer install <tenant>\" in terminal)\n- All CLI commands must be run from the repository root (the directory containing farseer-apps/)\n\nArguments can be overridden using the argumentOverrides parameter.\nArguments not overridden use their default values from app config.`,\n runAppSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { appName?: string; appId?: string; argumentOverrides?: Record<string, string> }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client } = gate.session;\n\n try {\n // Get app details\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 runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n return errorResponse(\n `App \"${app.name}\" has no scripts configured. Configure it with farseer_configure_app.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Find entrypoint script\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n return errorResponse(`Entrypoint script not found for app \"${app.name}\"`, 'NOT_FOUND');\n }\n\n // Get run credentials\n const credentials = await getRunCredentials(organisation, tenant);\n if (!credentials) {\n return authRequiredResponse(tenant, organisation);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Normalize script name - strip Scripts/ prefix if present\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Find script: try Scripts/ first, then search recursively in files/\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try full relative path under files/ first (e.g. Scripts/MyApp/index.ts \u2192 files/Scripts/MyApp/index.ts)\n const fullRelPath = path.resolve(filesDir, mainScript.name);\n if (fs.existsSync(fullRelPath)) {\n scriptPath = fullRelPath;\n relativeScriptPath = `files/${mainScript.name}`;\n } else {\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n }\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n return errorResponse(\n `Script not found locally: ${scriptName}. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n return errorResponse(\n `Dependencies not installed. Run \"farseer install ${tenant}\" in terminal first.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Build arguments\n const appArgs: Record<string, string> = {};\n\n // Start with defaults. defaultValue is optional on the API\n // type; treat missing as '' so we always hand a string to\n // the runner.\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue ?? '';\n }\n\n // Apply overrides\n if (params.argumentOverrides) {\n for (const [name, value] of Object.entries(params.argumentOverrides)) {\n appArgs[name] = value;\n }\n }\n\n // Build environment\n const envVars: Record<string, string> = {\n ...(process.env as Record<string, string>),\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_TOKEN = credentials.accessToken;\n }\n\n // Build command line arguments (in order)\n const cmdArgs: string[] = [];\n for (const arg of app.expectedArguments) {\n cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue ?? '');\n }\n\n // Run the script\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npx', ['tsx', relativeScriptPath, ...cmdArgs], {\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n resolve(\n successResponse({\n tenant,\n app: app.name,\n script: mainScript.name,\n arguments: appArgs,\n exitCode: code ?? 0,\n stdout: stdout.slice(0, 10000), // Limit output size\n stderr: stderr.slice(0, 5000),\n truncated: stdout.length > 10000 || stderr.length > 5000,\n }),\n );\n });\n\n child.on('error', (err) => {\n resolve(\n errorResponse(\n `Failed to run script: ${err.message}. Make sure tsx is installed: npm install -g tsx`,\n 'UNKNOWN',\n ),\n );\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('Script execution timed out after 5 minutes', 'UNKNOWN'));\n },\n 5 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Run app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_install - Install dependencies for a tenant\n server.tool(\n 'farseer_install',\n `Install npm dependencies for a Farseer tenant.\n\nEnsures the tenant directory has a package.json with farseer-client, then runs npm install.\nIf package.json doesn't exist, it is auto-created with farseer-client as a dependency.\n\nYou can also add extra npm packages (e.g., axios, lodash) that a script needs.\nThese are added to package.json and installed in one step.\n\nTypical workflow:\n1. farseer_pull \u2192 farseer_install \u2192 farseer_run_app\n\nAll commands must run from the repository root (the directory containing farseer-apps/).`,\n {\n packages: z\n .array(z.string())\n .optional()\n .describe('Additional npm packages to install (e.g., [\"axios\", \"lodash@4\"])'),\n },\n async (params: { packages?: string[] }) => {\n // Not behind requireSession: this never reaches the tenant, so there\n // is nothing to validate. `farseer install` is excluded for the same reason.\n const resolved = getSessionTenant();\n if (!resolved) return tenantRequiredResponse();\n const { tenant } = resolved;\n\n const tenantDir = getTenantDir(tenant);\n\n if (!fs.existsSync(tenantDir)) {\n return errorResponse(\n `Tenant folder not found: farseer-apps/${tenant}/. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n try {\n // Auto-create or update package.json using shared utility\n const addedPackages = [...ensurePackageJson(tenantDir, tenant)];\n\n // Add extra packages if requested\n if (params.packages && params.packages.length > 0) {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n pkg.dependencies = pkg.dependencies || {};\n\n for (const pkgSpec of params.packages) {\n const { name, version } = parsePackageSpec(pkgSpec);\n if (!pkg.dependencies[name]) {\n pkg.dependencies[name] = version;\n addedPackages.push(pkgSpec);\n }\n }\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n }\n\n // Run npm install\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npm', ['install'], {\n cwd: tenantDir,\n shell: true,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n resolve(\n successResponse({\n tenant,\n tenantDir: `farseer-apps/${tenant}/`,\n addedPackages,\n exitCode: 0,\n message: `Dependencies installed successfully${addedPackages.length ? ` (${addedPackages.join(', ')})` : ''}`,\n }),\n );\n } else {\n resolve(\n errorResponse(\n `npm install failed (exit code ${code}):\\n${stderr.slice(0, 3000)}`,\n 'UNKNOWN',\n ),\n );\n }\n });\n\n child.on('error', (err) => {\n resolve(errorResponse(`Failed to run npm install: ${err.message}`, 'UNKNOWN'));\n });\n\n // Timeout after 2 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('npm install timed out after 2 minutes', 'UNKNOWN'));\n },\n 2 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Install failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,2BAAsB;AACtB,SAAoB;AACpB,WAAsB;AACtB,qBAA+B;AAC/B,2BAAgD;AAChD,4BAAoC;AACpC,oBAAqC;AACrC,qBAAiE;AACjE,4BAAoD;AACpD,IAAAA,kBAOO;AACP,4BAAkC;AAKlC,SAAS,sBAAsB,SAAiB,YAAmC;AAC/E,MAAI,CAAC,GAAG,WAAW,OAAO,EAAG,QAAO;AACpC,QAAM,SAAS,CAAC,KAAa,eAAuB,OAAsB;AACtE,UAAM,QAAQ,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC;AACzD,eAAW,QAAQ,OAAO;AACtB,YAAM,cAAc,eAAe,GAAG,YAAY,IAAI,KAAK,IAAI,KAAK,KAAK;AACzE,UAAI,KAAK,OAAO,KAAK,KAAK,SAAS,WAAY,QAAO;AACtD,UAAI,KAAK,YAAY,GAAG;AACpB,cAAM,QAAQ,OAAO,KAAK,KAAK,KAAK,KAAK,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AA,gBAC/G,CAAC;AAAA,cACL;AAAA,YACJ,OAAO;AACH;AAAA,oBACI;AAAA,kBACI,iCAAiC,IAAI;AAAA,EAAO,OAAO,MAAM,GAAG,GAAI,CAAC;AAAA,kBACjE;AAAA,gBACJ;AAAA,cACJ;AAAA,YACJ;AAAA,UACJ,CAAC;AAED,gBAAM,GAAG,SAAS,CAAC,QAAQ;AACvB,wBAAQ,+BAAc,8BAA8B,IAAI,OAAO,IAAI,SAAS,CAAC;AAAA,UACjF,CAAC;AAGD;AAAA,YACI,MAAM;AACF,oBAAM,KAAK;AACX,0BAAQ,+BAAc,yCAAyC,SAAS,CAAC;AAAA,YAC7E;AAAA,YACA,IAAI,KAAK;AAAA,UACb;AAAA,QACJ,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,+BAAc,mBAAmB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MAC7F;AAAA,IACJ;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": ["import_helpers"]
|
|
7
7
|
}
|
|
@@ -42,6 +42,7 @@ __export(helpers_exports, {
|
|
|
42
42
|
});
|
|
43
43
|
module.exports = __toCommonJS(helpers_exports);
|
|
44
44
|
var import_configService = require("../../services/configService");
|
|
45
|
+
var import_realms = require("../../services/realms");
|
|
45
46
|
var import_tenantPin = require("./tenantPin");
|
|
46
47
|
var import_fileLogger = require("../../utils/fileLogger");
|
|
47
48
|
var import_nameResolver = require("../../utils/nameResolver");
|
|
@@ -123,8 +124,9 @@ async function resolveAppForMcp(client, selector) {
|
|
|
123
124
|
}
|
|
124
125
|
return { app };
|
|
125
126
|
}
|
|
126
|
-
function authRequiredResponse(tenant) {
|
|
127
|
-
const
|
|
127
|
+
function authRequiredResponse(tenant, organisation) {
|
|
128
|
+
const login = `farseer login${organisation ? ` --org ${organisation}` : ""}`;
|
|
129
|
+
const message = tenant ? `Authentication required for tenant "${tenant}". Run "${login}" to authenticate.` : `Authentication required. Run "${login}" to authenticate.`;
|
|
128
130
|
return errorResponse(message, "AUTH_REQUIRED");
|
|
129
131
|
}
|
|
130
132
|
function tenantRequiredResponse() {
|
|
@@ -143,12 +145,20 @@ function tenantRequiredResponse() {
|
|
|
143
145
|
);
|
|
144
146
|
}
|
|
145
147
|
function getAuthStatus() {
|
|
146
|
-
const auth = (0, import_configService.getUserAuth)();
|
|
147
148
|
const pin = (0, import_tenantPin.getTenantPin)();
|
|
148
149
|
const credentials = (0, import_configService.listCredentials)();
|
|
150
|
+
const logins = Object.entries((0, import_configService.listUserAuths)()).map(([realm2, login2]) => ({
|
|
151
|
+
realm: realm2,
|
|
152
|
+
valid: (0, import_configService.isUserAuthValid)(login2),
|
|
153
|
+
expiresAt: login2.expiresAt
|
|
154
|
+
}));
|
|
155
|
+
const realm = pin ? (0, import_realms.knownRealmForOrganisation)(pin.organisation) : void 0;
|
|
156
|
+
const login = realm ? logins.find((l) => l.realm === realm) : logins.find((l) => l.valid) ?? logins[0];
|
|
149
157
|
return {
|
|
150
|
-
jwtValid:
|
|
151
|
-
jwtExpiresAt:
|
|
158
|
+
jwtValid: !!login?.valid,
|
|
159
|
+
jwtExpiresAt: login?.expiresAt,
|
|
160
|
+
jwtRealm: login?.realm ?? realm,
|
|
161
|
+
logins,
|
|
152
162
|
tenant: pin,
|
|
153
163
|
launchPinned: (0, import_tenantPin.isLaunchPinned)(),
|
|
154
164
|
configuredTenants: Object.keys(credentials)
|
|
@@ -157,7 +167,7 @@ function getAuthStatus() {
|
|
|
157
167
|
function describeSessionFailure(failure, remedy) {
|
|
158
168
|
switch (failure.reason) {
|
|
159
169
|
case "no-credentials":
|
|
160
|
-
return authRequiredResponse(failure.tenant);
|
|
170
|
+
return authRequiredResponse(failure.tenant, failure.organisation);
|
|
161
171
|
case "org-unknown":
|
|
162
172
|
return errorResponse(`No Farseer organisation at "${failure.organisation}". ${remedy}`, "VALIDATION_ERROR");
|
|
163
173
|
case "pair-refuted": {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/utils/helpers.ts"],
|
|
4
|
-
"sourcesContent": ["/** Response shapes and wording shared by the MCP tools. */\n\nimport { getUserAuth, isUserAuthValid, listCredentials } from '../../services/configService';\nimport type { SessionFailure, SessionWarning } from '../../services/preflight';\nimport { getTenantPin, isLaunchPinned } from './tenantPin';\nimport { fileLogger } from '../../utils/fileLogger';\nimport type { FarseerService } from '../../services/farseerService';\nimport type { AppListItem, RemoteApp } from '../../services/apps';\nimport { selectByNameOrId, formatAmbiguous } from '../../utils/nameResolver';\nimport { resolveSheet, resolveDashboard, describeAmbiguity, type NamedEntity } from '../../utils/entityResolver';\nimport * as farseer from 'farseer-client';\n\n/**\n * The tenant this server is bound to, or null if nothing is bound yet. The env\n * is read once at launch (see launchPin.ts), so re-exporting FARSEER_TENANT\n * mid-session cannot retarget a running server.\n */\nexport function getSessionTenant(): { organisation: string; tenant: string } | null {\n return getTenantPin() ?? null;\n}\n\nexport function successResponse(data: Record<string, unknown>): { content: Array<{ type: 'text'; text: string }> } {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ success: true, ...data }, null, 2),\n },\n ],\n };\n}\n\nexport type McpErrorResponse = { content: Array<{ type: 'text'; text: string }>; isError: true };\n\nexport function errorResponse(\n message: string,\n errorCode?: 'AUTH_REQUIRED' | 'NOT_FOUND' | 'NETWORK_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN',\n): McpErrorResponse {\n // Log MCP tool errors to file for diagnostics\n fileLogger.error('mcp-tool', message, { errorCode: errorCode || 'UNKNOWN' });\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: false,\n error: message,\n errorCode: errorCode || 'UNKNOWN',\n },\n null,\n 2,\n ),\n },\n ],\n isError: true,\n };\n}\n\n/**\n * Resolve an app to its folder list item, or to an error response ready to\n * return. An explicit `appId` wins; a name that matches more than one app is a\n * validation error listing the candidates, never a guess.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ item: AppListItem } | { error: ReturnType<typeof errorResponse> }> {\n const selection = selectByNameOrId(\n await client.listApps(),\n { name: selector.appName, id: selector.id },\n (a) => a.reference,\n );\n if (selection.kind === 'found') {\n return { item: selection.entity };\n }\n if (selection.kind === 'ambiguous') {\n // Names are not unique \u2014 refuse to guess which colliding app was meant.\n return {\n error: errorResponse(\n formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference),\n 'VALIDATION_ERROR',\n ),\n };\n }\n if (selection.kind === 'conflict') {\n return {\n error: errorResponse(\n `App ${selection.entity.reference} is \"${selection.entity.name}\", not \"${selection.name}\". The id and the name point at different apps, so nothing was done \u2014 pass one of them.`,\n 'VALIDATION_ERROR',\n ),\n };\n }\n return {\n error: errorResponse(\n selector.id ? `App not found: id ${selector.id}` : `App \"${selector.appName}\" not found`,\n 'NOT_FOUND',\n ),\n };\n}\n\n/**\n * Resolve an app for an MCP tool to its full details. Wraps\n * `resolveAppItemForMcp` + `getApp` so the tools that need the whole\n * `RemoteApp` (get, configure, run) don't repeat the fetch.\n */\nexport async function resolveAppForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ app: RemoteApp } | { error: ReturnType<typeof errorResponse> }> {\n const resolution = await resolveAppItemForMcp(client, selector);\n if ('error' in resolution) {\n return resolution;\n }\n const app = await client.getApp(resolution.item.reference);\n if (!app) {\n return { error: errorResponse('Failed to load app details', 'NETWORK_ERROR') };\n }\n return { app };\n}\n\nexport function authRequiredResponse(tenant?: string): McpErrorResponse {\n const message = tenant\n ? `Authentication required for tenant \"${tenant}\". Run \"farseer login\" to authenticate.`\n : 'Authentication required. Run \"farseer login\" to authenticate.';\n\n return errorResponse(message, 'AUTH_REQUIRED');\n}\n\n/** No usable tenant for this call. States only how to fix the current situation. */\nexport function tenantRequiredResponse(): McpErrorResponse {\n const pin = getTenantPin();\n if (pin) {\n return errorResponse(\n `This session works only on tenant \"${pin.tenant}\". The tenant is locked for the session \u2014 to work on a different tenant, start a new session.`,\n 'VALIDATION_ERROR',\n );\n }\n // Agent-facing: the in-session fix is farseer_select_tenant, not a CLI\n // command or config edit. Configured API-key tenants are offered as a hint\n // when present (a browser-login user may reach others not listed).\n const configured = Object.keys(listCredentials());\n const hint = configured.length > 0 ? ` Configured tenants include: ${configured.join(', ')}.` : '';\n return errorResponse(\n `No tenant is selected for this session yet. Call farseer_select_tenant with the tenant to work on (the client the user named). It can be selected once, then locks for the session.${hint}`,\n 'VALIDATION_ERROR',\n );\n}\n\nexport function getAuthStatus(): {\n jwtValid: boolean;\n jwtExpiresAt?: string;\n tenant?: { organisation: string; tenant: string };\n launchPinned: boolean;\n configuredTenants: string[];\n} {\n const auth = getUserAuth();\n const pin = getTenantPin();\n const credentials = listCredentials();\n\n return {\n jwtValid: isUserAuthValid(),\n jwtExpiresAt: auth?.expiresAt,\n tenant: pin,\n launchPinned: isLaunchPinned(),\n configuredTenants: Object.keys(credentials),\n };\n}\n\n/**\n * The diagnosis is the guard's; `remedy` is the caller's, because the same\n * refusal is fixable in-session before the tenant locks and not after.\n */\nexport function describeSessionFailure(failure: SessionFailure, remedy: string): McpErrorResponse {\n switch (failure.reason) {\n case 'no-credentials':\n return authRequiredResponse(failure.tenant);\n\n case 'org-unknown':\n return errorResponse(`No Farseer organisation at \"${failure.organisation}\". ${remedy}`, 'VALIDATION_ERROR');\n\n case 'pair-refuted': {\n const known =\n failure.orgTenants.length > 0\n ? ` Tenants you can access under \"${failure.organisation}\": ${failure.orgTenants.join(', ')}.`\n : '';\n return errorResponse(\n `Tenant \"${failure.tenant}\" is not available under organisation \"${failure.organisation}\".${known} ${remedy}`,\n 'VALIDATION_ERROR',\n );\n }\n }\n}\n\n/** The CLI's warning without the \"you typed it\" framing \u2014 an agent did not type it. */\nexport function describeSessionWarning(warning: SessionWarning): string {\n return (\n `Organisation \"${warning.organisation}\" is not being used: the stored API key for \"${warning.tenant}\" ` +\n `carries its own host (${warning.host}). The tenant is the bound one; the organisation has no effect.`\n );\n}\n\n/**\n * A sheet or dashboard for an MCP tool, or an error response ready to return.\n * A name matching more than one is a validation error listing the candidates by\n * folder \u2014 several of these tools write, so guessing corrupts the other one.\n */\nexport async function resolveEntityForMcp(\n client: farseer.FarseerClient,\n kind: 'sheet' | 'dashboard',\n nameOrId: string,\n): Promise<{ entity: NamedEntity } | { error: McpErrorResponse }> {\n const sheet = kind === 'sheet';\n const selection = sheet ? await resolveSheet(client, nameOrId) : await resolveDashboard(client, nameOrId);\n\n if (selection.kind === 'found') {\n return { entity: selection.entity };\n }\n if (selection.kind === 'ambiguous') {\n const itemType = sheet ? farseer.FolderItemType.Sheet : farseer.FolderItemType.Dashboard;\n const message = await describeAmbiguity(client, `${kind}s`, nameOrId, selection.matches, itemType);\n return { error: errorResponse(message, 'VALIDATION_ERROR') };\n }\n return { error: errorResponse(`${sheet ? 'Sheet' : 'Dashboard'} \"${nameOrId}\" not found`, 'NOT_FOUND') };\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,
|
|
6
|
-
"names": []
|
|
4
|
+
"sourcesContent": ["/** Response shapes and wording shared by the MCP tools. */\n\nimport { isUserAuthValid, listCredentials, listUserAuths } from '../../services/configService';\nimport { knownRealmForOrganisation } from '../../services/realms';\nimport type { SessionFailure, SessionWarning } from '../../services/preflight';\nimport { getTenantPin, isLaunchPinned } from './tenantPin';\nimport { fileLogger } from '../../utils/fileLogger';\nimport type { FarseerService } from '../../services/farseerService';\nimport type { AppListItem, RemoteApp } from '../../services/apps';\nimport { selectByNameOrId, formatAmbiguous } from '../../utils/nameResolver';\nimport { resolveSheet, resolveDashboard, describeAmbiguity, type NamedEntity } from '../../utils/entityResolver';\nimport * as farseer from 'farseer-client';\n\n/**\n * The tenant this server is bound to, or null if nothing is bound yet. The env\n * is read once at launch (see launchPin.ts), so re-exporting FARSEER_TENANT\n * mid-session cannot retarget a running server.\n */\nexport function getSessionTenant(): { organisation: string; tenant: string } | null {\n return getTenantPin() ?? null;\n}\n\nexport function successResponse(data: Record<string, unknown>): { content: Array<{ type: 'text'; text: string }> } {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ success: true, ...data }, null, 2),\n },\n ],\n };\n}\n\nexport type McpErrorResponse = { content: Array<{ type: 'text'; text: string }>; isError: true };\n\nexport function errorResponse(\n message: string,\n errorCode?: 'AUTH_REQUIRED' | 'NOT_FOUND' | 'NETWORK_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN',\n): McpErrorResponse {\n // Log MCP tool errors to file for diagnostics\n fileLogger.error('mcp-tool', message, { errorCode: errorCode || 'UNKNOWN' });\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: false,\n error: message,\n errorCode: errorCode || 'UNKNOWN',\n },\n null,\n 2,\n ),\n },\n ],\n isError: true,\n };\n}\n\n/**\n * Resolve an app to its folder list item, or to an error response ready to\n * return. An explicit `appId` wins; a name that matches more than one app is a\n * validation error listing the candidates, never a guess.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ item: AppListItem } | { error: ReturnType<typeof errorResponse> }> {\n const selection = selectByNameOrId(\n await client.listApps(),\n { name: selector.appName, id: selector.id },\n (a) => a.reference,\n );\n if (selection.kind === 'found') {\n return { item: selection.entity };\n }\n if (selection.kind === 'ambiguous') {\n // Names are not unique \u2014 refuse to guess which colliding app was meant.\n return {\n error: errorResponse(\n formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference),\n 'VALIDATION_ERROR',\n ),\n };\n }\n if (selection.kind === 'conflict') {\n return {\n error: errorResponse(\n `App ${selection.entity.reference} is \"${selection.entity.name}\", not \"${selection.name}\". The id and the name point at different apps, so nothing was done \u2014 pass one of them.`,\n 'VALIDATION_ERROR',\n ),\n };\n }\n return {\n error: errorResponse(\n selector.id ? `App not found: id ${selector.id}` : `App \"${selector.appName}\" not found`,\n 'NOT_FOUND',\n ),\n };\n}\n\n/**\n * Resolve an app for an MCP tool to its full details. Wraps\n * `resolveAppItemForMcp` + `getApp` so the tools that need the whole\n * `RemoteApp` (get, configure, run) don't repeat the fetch.\n */\nexport async function resolveAppForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ app: RemoteApp } | { error: ReturnType<typeof errorResponse> }> {\n const resolution = await resolveAppItemForMcp(client, selector);\n if ('error' in resolution) {\n return resolution;\n }\n const app = await client.getApp(resolution.item.reference);\n if (!app) {\n return { error: errorResponse('Failed to load app details', 'NETWORK_ERROR') };\n }\n return { app };\n}\n\nexport function authRequiredResponse(tenant?: string, organisation?: string): McpErrorResponse {\n // A login is per realm, so name the org: `login --org` picks its realm.\n const login = `farseer login${organisation ? ` --org ${organisation}` : ''}`;\n const message = tenant\n ? `Authentication required for tenant \"${tenant}\". Run \"${login}\" to authenticate.`\n : `Authentication required. Run \"${login}\" to authenticate.`;\n\n return errorResponse(message, 'AUTH_REQUIRED');\n}\n\n/** No usable tenant for this call. States only how to fix the current situation. */\nexport function tenantRequiredResponse(): McpErrorResponse {\n const pin = getTenantPin();\n if (pin) {\n return errorResponse(\n `This session works only on tenant \"${pin.tenant}\". The tenant is locked for the session \u2014 to work on a different tenant, start a new session.`,\n 'VALIDATION_ERROR',\n );\n }\n // Agent-facing: the in-session fix is farseer_select_tenant, not a CLI\n // command or config edit. Configured API-key tenants are offered as a hint\n // when present (a browser-login user may reach others not listed).\n const configured = Object.keys(listCredentials());\n const hint = configured.length > 0 ? ` Configured tenants include: ${configured.join(', ')}.` : '';\n return errorResponse(\n `No tenant is selected for this session yet. Call farseer_select_tenant with the tenant to work on (the client the user named). It can be selected once, then locks for the session.${hint}`,\n 'VALIDATION_ERROR',\n );\n}\n\nexport function getAuthStatus(): {\n jwtValid: boolean;\n jwtExpiresAt?: string;\n jwtRealm?: string;\n logins: { realm: string; valid: boolean; expiresAt: string }[];\n tenant?: { organisation: string; tenant: string };\n launchPinned: boolean;\n configuredTenants: string[];\n} {\n const pin = getTenantPin();\n const credentials = listCredentials();\n const logins = Object.entries(listUserAuths()).map(([realm, login]) => ({\n realm,\n valid: isUserAuthValid(login),\n expiresAt: login.expiresAt,\n }));\n // Bound: the login that tenant needs. Unbound: any usable one.\n const realm = pin ? knownRealmForOrganisation(pin.organisation) : undefined;\n const login = realm ? logins.find((l) => l.realm === realm) : (logins.find((l) => l.valid) ?? logins[0]);\n\n return {\n jwtValid: !!login?.valid,\n jwtExpiresAt: login?.expiresAt,\n jwtRealm: login?.realm ?? realm,\n logins,\n tenant: pin,\n launchPinned: isLaunchPinned(),\n configuredTenants: Object.keys(credentials),\n };\n}\n\n/**\n * The diagnosis is the guard's; `remedy` is the caller's, because the same\n * refusal is fixable in-session before the tenant locks and not after.\n */\nexport function describeSessionFailure(failure: SessionFailure, remedy: string): McpErrorResponse {\n switch (failure.reason) {\n case 'no-credentials':\n return authRequiredResponse(failure.tenant, failure.organisation);\n\n case 'org-unknown':\n return errorResponse(`No Farseer organisation at \"${failure.organisation}\". ${remedy}`, 'VALIDATION_ERROR');\n\n case 'pair-refuted': {\n const known =\n failure.orgTenants.length > 0\n ? ` Tenants you can access under \"${failure.organisation}\": ${failure.orgTenants.join(', ')}.`\n : '';\n return errorResponse(\n `Tenant \"${failure.tenant}\" is not available under organisation \"${failure.organisation}\".${known} ${remedy}`,\n 'VALIDATION_ERROR',\n );\n }\n }\n}\n\n/** The CLI's warning without the \"you typed it\" framing \u2014 an agent did not type it. */\nexport function describeSessionWarning(warning: SessionWarning): string {\n return (\n `Organisation \"${warning.organisation}\" is not being used: the stored API key for \"${warning.tenant}\" ` +\n `carries its own host (${warning.host}). The tenant is the bound one; the organisation has no effect.`\n );\n}\n\n/**\n * A sheet or dashboard for an MCP tool, or an error response ready to return.\n * A name matching more than one is a validation error listing the candidates by\n * folder \u2014 several of these tools write, so guessing corrupts the other one.\n */\nexport async function resolveEntityForMcp(\n client: farseer.FarseerClient,\n kind: 'sheet' | 'dashboard',\n nameOrId: string,\n): Promise<{ entity: NamedEntity } | { error: McpErrorResponse }> {\n const sheet = kind === 'sheet';\n const selection = sheet ? await resolveSheet(client, nameOrId) : await resolveDashboard(client, nameOrId);\n\n if (selection.kind === 'found') {\n return { entity: selection.entity };\n }\n if (selection.kind === 'ambiguous') {\n const itemType = sheet ? farseer.FolderItemType.Sheet : farseer.FolderItemType.Dashboard;\n const message = await describeAmbiguity(client, `${kind}s`, nameOrId, selection.matches, itemType);\n return { error: errorResponse(message, 'VALIDATION_ERROR') };\n }\n return { error: errorResponse(`${sheet ? 'Sheet' : 'Dashboard'} \"${nameOrId}\" not found`, 'NOT_FOUND') };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,2BAAgE;AAChE,oBAA0C;AAE1C,uBAA6C;AAC7C,wBAA2B;AAG3B,0BAAkD;AAClD,4BAAoF;AACpF,cAAyB;AAOlB,SAAS,mBAAoE;AAChF,aAAO,+BAAa,KAAK;AAC7B;AAEO,SAAS,gBAAgB,MAAmF;AAC/G,SAAO;AAAA,IACH,SAAS;AAAA,MACL;AAAA,QACI,MAAM;AAAA,QACN,MAAM,KAAK,UAAU,EAAE,SAAS,MAAM,GAAG,KAAK,GAAG,MAAM,CAAC;AAAA,MAC5D;AAAA,IACJ;AAAA,EACJ;AACJ;AAIO,SAAS,cACZ,SACA,WACgB;AAEhB,+BAAW,MAAM,YAAY,SAAS,EAAE,WAAW,aAAa,UAAU,CAAC;A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
7
7
|
}
|
|
@@ -26,19 +26,24 @@ __export(session_exports, {
|
|
|
26
26
|
module.exports = __toCommonJS(session_exports);
|
|
27
27
|
var import_configService = require("../../services/configService");
|
|
28
28
|
var import_credentials = require("../../services/credentials");
|
|
29
|
+
var import_realms = require("../../services/realms");
|
|
29
30
|
var import_preflight = require("../../services/preflight");
|
|
30
31
|
var import_helpers = require("./helpers");
|
|
31
32
|
var import_tenantPin = require("./tenantPin");
|
|
32
33
|
let validated;
|
|
33
|
-
function credentialState(
|
|
34
|
-
const credential = (0, import_configService.getCredential)(tenant);
|
|
34
|
+
function credentialState(pin, passedOverLogin) {
|
|
35
|
+
const credential = (0, import_configService.getCredential)(pin.tenant);
|
|
35
36
|
const key = credential ? `${credential.basePath}|${credential.tenantId}|${credential.apiKey}` : "none";
|
|
36
|
-
const login = (0, import_configService.getUserAuth)();
|
|
37
|
+
const login = (0, import_configService.getUserAuth)((0, import_realms.knownRealmForOrganisation)(pin.organisation));
|
|
37
38
|
const who = !login ? "none" : passedOverLogin ? `unusable:${login.refreshToken}` : `session:${loginSession(login)}`;
|
|
38
39
|
return `${who}|${key}`;
|
|
39
40
|
}
|
|
40
|
-
function passedOver(auth) {
|
|
41
|
-
|
|
41
|
+
function passedOver(pin, auth) {
|
|
42
|
+
if (auth.kind !== "apiKey") {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
const login = (0, import_configService.getUserAuth)((0, import_realms.knownRealmForOrganisation)(pin.organisation));
|
|
46
|
+
return !!login && !(0, import_configService.isUserAuthValid)(login);
|
|
42
47
|
}
|
|
43
48
|
function loginSession(login) {
|
|
44
49
|
for (const token of [login.refreshToken, login.accessToken]) {
|
|
@@ -57,11 +62,11 @@ async function requireSession() {
|
|
|
57
62
|
if (!pin) {
|
|
58
63
|
return { ok: false, response: (0, import_helpers.tenantRequiredResponse)() };
|
|
59
64
|
}
|
|
60
|
-
if (validated?.pin === pin && validated.credentials === credentialState(pin
|
|
65
|
+
if (validated?.pin === pin && validated.credentials === credentialState(pin, validated.passedOverLogin)) {
|
|
61
66
|
const auth = await (0, import_credentials.refreshAuth)(validated.auth);
|
|
62
67
|
if (!auth) {
|
|
63
68
|
validated = void 0;
|
|
64
|
-
return { ok: false, response: (0, import_helpers.authRequiredResponse)(pin.tenant) };
|
|
69
|
+
return { ok: false, response: (0, import_helpers.authRequiredResponse)(pin.tenant, pin.organisation) };
|
|
65
70
|
}
|
|
66
71
|
return { ok: true, session: (0, import_preflight.sessionFrom)(pin.organisation, pin.tenant, auth) };
|
|
67
72
|
}
|
|
@@ -76,8 +81,8 @@ function rememberSession(pin, auth, warning) {
|
|
|
76
81
|
remember(pin, auth, warning);
|
|
77
82
|
}
|
|
78
83
|
function remember(pin, auth, warning) {
|
|
79
|
-
const passedOverLogin = passedOver(auth);
|
|
80
|
-
validated = { pin, auth, credentials: credentialState(pin
|
|
84
|
+
const passedOverLogin = passedOver(pin, auth);
|
|
85
|
+
validated = { pin, auth, credentials: credentialState(pin, passedOverLogin), passedOverLogin, warning };
|
|
81
86
|
}
|
|
82
87
|
function getSessionWarning() {
|
|
83
88
|
const pin = (0, import_tenantPin.getTenantPin)();
|