farseer-cli 1.12.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -18
- 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/pipeline.js +158 -0
- package/dist/commands/pipeline.js.map +7 -0
- package/dist/commands/run.js +10 -27
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/variables.js +17 -8
- package/dist/commands/variables.js.map +2 -2
- package/dist/commands/whoami.js +10 -14
- package/dist/commands/whoami.js.map +2 -2
- package/dist/index.js +40 -46
- package/dist/index.js.map +2 -2
- package/dist/mcp/prompts/workflows.js +13 -68
- package/dist/mcp/prompts/workflows.js.map +2 -2
- package/dist/mcp/resources/documentation.js +14 -0
- package/dist/mcp/resources/documentation.js.map +2 -2
- package/dist/mcp/server.js +14 -2
- package/dist/mcp/server.js.map +2 -2
- package/dist/mcp/skills.js +59 -0
- package/dist/mcp/skills.js.map +7 -0
- package/dist/mcp/tools/appTools.js +4 -0
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +5 -2
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +2 -0
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +6 -41
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/pipelineContract.js +317 -0
- package/dist/mcp/tools/pipelineContract.js.map +7 -0
- package/dist/mcp/tools/pipelineTools.js +111 -0
- package/dist/mcp/tools/pipelineTools.js.map +7 -0
- package/dist/mcp/tools/runTools.js +7 -18
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +4 -0
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/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/pipeline/compatibility.js +53 -0
- package/dist/pipeline/compatibility.js.map +7 -0
- package/dist/pipeline/connect.js +139 -0
- package/dist/pipeline/connect.js.map +7 -0
- package/dist/pipeline/create.js +158 -0
- package/dist/pipeline/create.js.map +7 -0
- package/dist/pipeline/errors.js +45 -0
- package/dist/pipeline/errors.js.map +7 -0
- package/dist/pipeline/generated-reference.json +115 -0
- package/dist/pipeline/guide.js +33 -0
- package/dist/pipeline/guide.js.map +7 -0
- package/dist/pipeline/init.js +204 -0
- package/dist/pipeline/init.js.map +7 -0
- package/dist/pipeline/operations.js +103 -0
- package/dist/pipeline/operations.js.map +7 -0
- package/dist/pipeline/query.js +103 -0
- package/dist/pipeline/query.js.map +7 -0
- package/dist/pipeline/queryWorker.js +119 -0
- package/dist/pipeline/queryWorker.js.map +7 -0
- package/dist/pipeline/readiness.js +55 -0
- package/dist/pipeline/readiness.js.map +7 -0
- package/dist/pipeline/reference.js +72 -0
- package/dist/pipeline/reference.js.map +7 -0
- package/dist/pipeline/requests.js +122 -0
- package/dist/pipeline/requests.js.map +7 -0
- package/dist/pipeline/runArguments.js +68 -0
- package/dist/pipeline/runArguments.js.map +7 -0
- package/dist/pipeline/runtime.js +105 -0
- package/dist/pipeline/runtime.js.map +7 -0
- package/dist/pipeline/service.js +967 -0
- package/dist/pipeline/service.js.map +7 -0
- package/dist/services/agentApprovalFetch.js +86 -0
- package/dist/services/agentApprovalFetch.js.map +7 -0
- package/dist/services/authErrors.js +2 -2
- package/dist/services/authErrors.js.map +2 -2
- package/dist/services/configService.js +74 -9
- package/dist/services/configService.js.map +2 -2
- package/dist/services/credentials.js +12 -7
- package/dist/services/credentials.js.map +2 -2
- package/dist/services/farseerService.js +94 -39
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/preflight.js +7 -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/dist/services/syncService.js +6 -0
- package/dist/services/syncService.js.map +2 -2
- package/dist/skills/pipeline.js +71 -0
- package/dist/skills/pipeline.js.map +7 -0
- package/dist/utils/helpers.js +2 -1
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/variableValues.js +78 -0
- package/dist/utils/variableValues.js.map +7 -0
- package/docs/pipeline-client-guide.md +67 -0
- package/docs/pipeline-reference.md +2064 -0
- package/package.json +5 -1
- package/skills/pipeline-authoring/SKILL.md +95 -0
- package/skills/pipeline-authoring/practices.md +325 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/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\nUse this tool to run an existing TypeScript app, including an existing pipeline, without requiring the user to explicitly say TypeScript. Preserve its implementation and configuration; migration requires an explicit migration request. All new repeatable pipelines must use Simple Pipelines through farseer_pipeline and its remote run operation. An existing TypeScript app is not missing Simple Pipelines setup.\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,IAAI,GAAG,WAAW;AAC3D,YAAI,MAAO,QAAO;AAAA,MACtB;AAAA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ACH;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
|
}
|
|
@@ -100,6 +100,8 @@ function registerSyncTools(server) {
|
|
|
100
100
|
"farseer_pull",
|
|
101
101
|
`Pull (download) files and app configurations from a Farseer instance to the local repository.
|
|
102
102
|
|
|
103
|
+
For a prepared data pipeline, use farseer_pipeline operation=pull to sync that pipeline's source scope. Start with operation=guide topic=method when authoring a pipeline.
|
|
104
|
+
|
|
103
105
|
What gets pulled:
|
|
104
106
|
- Files from the tenant Files/ folder (searched recursively)
|
|
105
107
|
- App configurations (saved as JSON in apps/ folder)
|
|
@@ -192,6 +194,8 @@ Sync includes (middle ground between the default scope and all):
|
|
|
192
194
|
"farseer_push",
|
|
193
195
|
`Push (upload) local file and app changes to a Farseer instance.
|
|
194
196
|
|
|
197
|
+
For a prepared data pipeline, use farseer_pipeline operation=push to sync that pipeline's source scope. Start with operation=guide topic=method when authoring a pipeline.
|
|
198
|
+
|
|
195
199
|
What gets pushed:
|
|
196
200
|
- New/modified files from farseer-apps/<tenant>/files/ (filtered by sync scope \u2014
|
|
197
201
|
default is developer files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/syncTools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * File Synchronization Tools\n *\n * Tools for syncing files between local repository and Farseer instance.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { createPatch } from 'diff';\nimport { SyncService } from '../../services/syncService';\nimport { AppSyncService } from '../../services/appSyncService';\nimport { requireSession } from '../utils/session';\nimport { successResponse, errorResponse } from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\nimport { normalizeExtensions } from '../../utils/cliOptions';\n\n/**\n * Format a category breakdown for the MCP summary string when\n * `ignoredLocal` is non-empty. Agents quote the summary verbatim back\n * to users, so the breakdown has to fit on one line and stay readable\n * without the structured array.\n *\n * Examples:\n * - \"5 with unsupported extension\"\n * - \"3 in blocklisted folders\"\n * - \"5 with unsupported extension, 3 in blocklisted folders\"\n *\n * Takes the UNCAPPED per-reason totals tracked during the walk, not\n * counts from the stored slice. The slice is capped at\n * `IGNORED_LOCAL_CAP` to bound memory, so counting it would give the\n * user a number that disagrees with the headline \u2014 e.g. headline\n * \"250 outside scope\" with breakdown \"100 with unsupported extension\"\n * when all 250 are unsupported-extension files.\n *\n * Returns an empty string when both totals are zero; the caller still\n * gates on `total > 0` and falls back to a plain pointer when this\n * comes back empty.\n */\nfunction summariseIgnoredReasons(totals: { unsupportedExtension: number; blocklistedFolder: number }): string {\n const parts: string[] = [];\n if (totals.unsupportedExtension > 0) parts.push(`${totals.unsupportedExtension} with unsupported extension`);\n if (totals.blocklistedFolder > 0) parts.push(`${totals.blocklistedFolder} in blocklisted folders`);\n return parts.join(', ');\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\n//\n// `includeExtensions` and `includeFolders` mirror the CLI's `--include-ext` /\n// `--include-folder` flags. Without them on the MCP surface, an agent could\n// only choose between the default scope and \"all\" \u2014 there was no way to\n// scope a pull/push/status to \"default plus this one folder\" the way a CLI\n// user can.\nconst includeExtensionsSchema = z\n .array(z.string())\n .optional()\n .describe(\n 'Extra file extensions to include alongside the default scope (developer files ' +\n '(.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). ' +\n 'Data files (.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 ' +\n 'opt in here (e.g. [\"csv\"]). Supply with or without leading dot (\".csv\" or \"csv\") \u2014 ' +\n \"both work; the handler normalises before matching. Mirrors the CLI's --include-ext flag.\",\n );\nconst includeFoldersSchema = z\n .array(z.string())\n .optional()\n .describe(\n 'Extra folder paths whose files (any extension) are included alongside the default scope. ' +\n 'Useful for opting into hidden or blocklisted folders. Each path is interpreted ' +\n 'relative to the tenant root, e.g. \"Data\" or \".vscode\" or \"dist\". ' +\n \"Mirrors the CLI's --include-folder flag.\",\n );\n\nconst pullSchema = {\n all: z\n .boolean()\n .optional()\n .describe(\n 'Pull every non-hidden, non-blocklisted file (default: developer files (.ts, .js, .py, ' +\n '.yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). Data files ' +\n '(.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 opt in ' +\n 'via includeExtensions (e.g. [\"csv\"]) or pass all=true to broaden everything.',\n ),\n force: z\n .boolean()\n .optional()\n .describe(\n 'DESTRUCTIVE \u2014 overwrites EVERY locally-modified file with the remote version, including ' +\n \"local edits that have no remote conflict (e.g. a file you've been editing but the remote \" +\n 'is still on the baseline version). Use only when the user has explicitly asked to ' +\n 'discard local changes. Does NOT delete local-only files (that destructive wipe stays ' +\n 'on the CLI side behind the interactive confirm prompt).',\n ),\n includeExtensions: includeExtensionsSchema,\n includeFolders: includeFoldersSchema,\n};\n\nconst pushSchema = {\n force: z\n .boolean()\n .optional()\n .describe(\n 'Skip the drift check and overwrite remote even if it diverged from baseline. ' +\n 'Does NOT delete remote-only files; pass mirror=true for that.',\n ),\n mirror: z\n .boolean()\n .optional()\n .describe(\n 'Also delete remote files that have no local counterpart \u2014 destructive \"make remote = local\" semantics. ' +\n \"Implies the upload step still respects the user's local presence, so this only fires for files \" +\n 'genuinely missing locally. Combine with force=true if the drift check would otherwise refuse the push.',\n ),\n all: z\n .boolean()\n .optional()\n .describe(\n 'Push every non-hidden, non-blocklisted file (default: developer files (.ts, .js, .py, ' +\n '.yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). Data files ' +\n '(.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 opt in ' +\n 'via includeExtensions. Hidden files / blocklisted folders still require explicit ' +\n 'opt-in via includeFolders.',\n ),\n includeExtensions: includeExtensionsSchema,\n includeFolders: includeFoldersSchema,\n};\n\nconst statusSchema = {\n all: z\n .boolean()\n .optional()\n .describe(\n 'Show status for every non-hidden, non-blocklisted file (default: developer files ' +\n '(.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). ' +\n 'Data files (.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 ' +\n 'opt in via includeExtensions (e.g. [\"csv\"]) or pass all=true to broaden everything.',\n ),\n // Deep is the default \u2014 matches the CLI's `farseer status` behaviour\n // (deep-by-default since 1.6.2). Agents should pass `shallow: true`\n // only when they have independent reason to trust the last-pull\n // baseline (e.g. checking immediately after a successful pull) and\n // want the faster path on a large tenant.\n shallow: z\n .boolean()\n .optional()\n .describe(\n 'Skip remote-content hashing. Faster on big tenants but cannot detect remote-side edits to existing ' +\n 'files made since the last pull. Default is deep \u2014 every remote file is hashed.',\n ),\n // Backwards-compat alias for callers written against the 1.6.1 MCP\n // schema, where deep=false was the fast-path opt-out. We map it to\n // shallow internally; if both are passed, shallow wins (explicit\n // opt-out beats the legacy positive). New callers should use shallow.\n deep: z\n .boolean()\n .optional()\n .describe(\n '(Deprecated) Backwards-compat alias for the pre-1.6.2 fast-path control. ' +\n 'Pass shallow=true instead. If both are supplied, shallow takes precedence.',\n ),\n includeExtensions: includeExtensionsSchema,\n includeFolders: includeFoldersSchema,\n};\n\nconst diffSchema = {\n file: z.string().optional().describe('Specific file path to diff. If omitted, shows all differences.'),\n showRemote: z.boolean().optional().describe('Show only the remote content instead of diff'),\n};\n\nconst listFilesSchema = {\n all: z\n .boolean()\n .optional()\n .describe(\n 'By default, lists files with script extensions only (.ts, .js, .mjs, .cjs), matching ' +\n \"the CLI's `farseer files list`. This is NARROWER than the default sync scope used \" +\n 'by farseer_pull/status/push. Set all=true to list every file on the remote.',\n ),\n};\n\nexport function registerSyncTools(server: McpServer): void {\n // farseer_pull - Download files from remote\n server.tool(\n 'farseer_pull',\n `Pull (download) files and app configurations from a Farseer instance to the local repository.\n\nWhat gets pulled:\n- Files from the tenant Files/ folder (searched recursively)\n- App configurations (saved as JSON in apps/ folder)\n\nFiles are saved to: farseer-apps/<tenant>/files/\nApps are saved to: farseer-apps/<tenant>/apps/\n\nDefault sync scope: developer files (.ts, .js, .py, .yml, .yaml, .md, .json) that sit\noutside hidden directories (.git/, .vscode/, .env*) and the folder blocklist\n(node_modules/, dist/, build/, vendor/, target/, tmp/, \u2026). Data files (.csv,\n.xlsx, .parquet, .pdf, images, \u2026) are backend-accepted but EXCLUDED from default\n\u2014 opt in via includeExtensions (e.g. [\"csv\"]). Hidden paths and blocklisted\nfolders require explicit opt-in.\nUse all=true to broaden the scope to every non-hidden, non-blocklisted file\n(extensions outside the backend whitelist, files with no extension, etc.).\nUse includeExtensions / includeFolders to broaden the scope without pulling everything\n(e.g. includeFolders=[\".vscode\"] adds the .vscode folder regardless of extension).\nThese mirror the CLI's --include-ext / --include-folder flags and are additive on\ntop of the default scope.\n\nConflict handling:\n- Per-file conflict resolution (keep_local / keep_remote / keep_both / merge_markers)\n is CLI-only \u2014 it requires an interactive prompt and the MCP can't answer one.\n- The MCP path returns conflicts in response.conflicts[] so the agent can re-pull\n with force=true once the user has confirmed they want to discard their edits.\n- force=true is DESTRUCTIVE: it overwrites every locally-modified file with the\n remote version (even local edits that don't conflict with remote). It does NOT\n wipe local-only files (that destructive step lives behind the CLI's confirm prompt).\n Only pass force=true when the user has explicitly accepted losing local changes.\n\nSync includes (middle ground between the default scope and all):\n- Users can configure extra extensions and folders via \"farseer config include\" CLI command\n- These are stored per-tenant in ~/.farseer/config.json under \"syncIncludes\"\n- When configured, pull/push/status automatically include those files alongside the default scope\n- Example: syncIncludes may add extra extensions or otherwise blocklisted folders like \"dist\" or \".vscode\"\n- The sync includes are respected automatically \u2014 no extra parameters needed here`,\n pullSchema,\n async (params: { all?: boolean; force?: boolean; includeExtensions?: string[]; includeFolders?: string[] }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client, authType } = gate.session;\n\n try {\n // Pull files (use tenant for folder path).\n // Normalise extensions: agents pass them with or without a\n // leading dot (\".json\" vs \"json\"), but downstream comparisons\n // are against `path.extname()` which always has a dot.\n // Without this, includeExtensions=[\"json\"] would silently\n // never match anything.\n const syncService = new SyncService(tenant, client);\n const fileResult = await syncService.pull({\n all: params.all,\n force: params.force,\n includeExtensions: params.includeExtensions\n ? normalizeExtensions(params.includeExtensions)\n : undefined,\n includeFolders: params.includeFolders,\n });\n\n // Pull apps (only with JWT auth)\n let appResult = null;\n if (authType === 'jwt') {\n const appSyncService = new AppSyncService(tenant, client);\n appResult = await appSyncService.pull();\n }\n\n const response: Record<string, any> = {\n tenant,\n organisation,\n files: {\n downloaded: fileResult.downloaded,\n deleted: fileResult.deleted,\n unchanged: fileResult.unchanged.length,\n },\n apps: appResult\n ? {\n created: appResult.created,\n updated: appResult.updated,\n deleted: appResult.deleted,\n unchanged: appResult.unchanged.length,\n }\n : { note: 'App sync requires browser login (JWT)' },\n message: `Pulled ${fileResult.downloaded.length} files${appResult ? ` and ${appResult.created.length + appResult.updated.length} apps` : ''}`,\n };\n\n if (fileResult.conflicts.length > 0) {\n response.conflicts = fileResult.conflicts.map((c) => ({\n file: c.filePath,\n type: c.type,\n description: c.description,\n }));\n response.message = `Pulled ${fileResult.downloaded.length} files but ${fileResult.conflicts.length} conflict(s) need resolution`;\n response.hint =\n 'Use force=true to overwrite local changes, or resolve conflicts via CLI: farseer pull <tenant>';\n }\n\n if (fileResult.conflictFilesWritten.length > 0) {\n response.conflictFilesWritten = fileResult.conflictFilesWritten;\n }\n\n return successResponse(response);\n } catch (error) {\n return errorResponse(`Pull failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_push - Upload files to remote\n server.tool(\n 'farseer_push',\n `Push (upload) local file and app changes to a Farseer instance.\n\nWhat gets pushed:\n- New/modified files from farseer-apps/<tenant>/files/ (filtered by sync scope \u2014\n default is developer files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories\n and the folder blocklist. Data files like .csv / .xlsx / .parquet are backend-accepted\n but excluded from default; broaden via includeExtensions / includeFolders / all on\n this tool, or via persistent sync includes set with the CLI's \"farseer config include\").\n- New/modified app configurations from farseer-apps/<tenant>/apps/.\n- Deleted files (when they were previously synced \u2014 preserves \"I rm'd this\" semantics).\n\nPre-flight (runs before any HTTP call):\n- Refuses files the backend would refuse anyway: extension not on whitelist,\n filename longer than 256 chars, empty body, unresolved git-style merge markers\n (<<<<<<< LOCAL / ======= / >>>>>>> REMOTE) left over from a merge_markers pull.\n- Returns rejected files in the response. If every candidate is rejected (and\n no deletes/updates either), the tool call returns VALIDATION_ERROR.\n\nDrift / mirror semantics:\n- force=true skips the drift check (push over remote-side adds/deletes).\n- mirror=true (separate param) also deletes remote files that have no local\n counterpart, within the current sync scope. Combine with force when both are\n needed.\n\nOut-of-scope files (e.g. a hidden .vscode/settings.json next to in-scope files)\nare INVISIBLE to push \u2014 never uploaded, never deleted. Hidden paths require\nexplicit opt-in via --include-folder (extension includes never widen scope to\nhidden files \u2014 that would let a generic .json broadening leak credentials).\n\nSilent-skip signal: \\`files.ignoredLocal\\` is an array of\n\\`{ path, reason }\\` entries listing non-hidden user files that exist on\ndisk but were outside the active sync scope and therefore NOT pushed.\n\\`reason\\` is one of:\n - \\`unsupportedExtension\\`: file extension isn't in default scope (e.g.\n .csv, .md). Tell the user to broaden with \\`--include-ext <ext>\\`.\n - \\`blocklistedFolder\\`: file is in a tooling-output folder (node_modules/,\n dist/, build/). These are almost never user content \u2014 warn the user\n that opting in is unusual instead of suggesting the flag outright.\n\\`files.ignoredLocalTotal\\` carries the uncapped count when the list was\ntruncated. Hidden files (.env, .git/, .vscode/) never appear here \u2014 the\nresponse does not advertise widening scope to include them. Use this list to\ndetect \"push succeeded but my local .csv / .md / .py files weren't sent\"\nbefore reporting success to the user.\n\nSync includes: if user configured via \"farseer config include\", drift and scope\nchecks respect those settings automatically.`,\n pushSchema,\n async (params: {\n force?: boolean;\n mirror?: boolean;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client, authType } = gate.session;\n\n try {\n const syncService = new SyncService(tenant, client);\n\n // Normalise extensions once: agents may pass them dotless\n // (\"json\" vs \".json\"), but downstream comparisons are\n // against `path.extname()` which always has a dot. Build\n // the scope once and reuse it so the drift check and push\n // run in identical scope.\n const scopeOptions = {\n all: params.all,\n includeExtensions: params.includeExtensions\n ? normalizeExtensions(params.includeExtensions)\n : undefined,\n includeFolders: params.includeFolders,\n };\n\n // Non-force push must not silently overwrite remote-side\n // drift. The previous `checkRemoteChanges` gate was a\n // list-only diff against the recorded baseline \u2014 it could\n // see remote-side adds/deletes but not content edits to\n // existing files. That's the same Matej-class blind spot\n // the CLI gate closed in 1.6.2: run a DEEP status so\n // remote content drift surfaces, then block if any\n // remote-side bucket has paths in scope.\n if (!params.force) {\n const status = await syncService.getStatus({\n ...scopeOptions,\n deep: true,\n });\n const conflicting = [\n ...status.modifiedRemotely,\n ...status.addedRemotely,\n ...status.deletedRemotely,\n ];\n if (conflicting.length > 0) {\n // Mirror the CLI's behaviour at push.ts:211-216 \u2014\n // echo the active scope flags back into the\n // suggested pull command so a default-scope pull\n // doesn't run, report \"Already up to date\", and\n // leave the agent stuck in the same drift loop.\n const scopeFlags: string[] = [];\n if (params.all) scopeFlags.push('--all');\n for (const ext of params.includeExtensions ?? []) scopeFlags.push(`--include-ext ${ext}`);\n for (const folder of params.includeFolders ?? [])\n scopeFlags.push(`--include-folder \"${folder}\"`);\n const pullCmd = ['farseer pull', tenant, ...scopeFlags].join(' ');\n return errorResponse(\n `Remote has changes for ${conflicting.length} file(s) since last pull:\\n` +\n conflicting.map((p) => ` - ${p}`).join('\\n') +\n `\\n\\nRun \\`${pullCmd}\\` first, or use force=true to overwrite remote.`,\n 'VALIDATION_ERROR',\n );\n }\n }\n\n // Push files. Pass `mirror` separately from `force` so an\n // agent must opt in explicitly to remote-side deletes \u2014 the\n // CLI gates this behind a confirm prompt, the MCP can't, so\n // we make it a separate parameter the caller has to set.\n const fileResult = await syncService.push({\n ...scopeOptions,\n force: params.force,\n mirror: params.mirror,\n });\n\n // Check for conflicts\n if (fileResult.conflicts.length > 0) {\n return errorResponse(\n `Push blocked by ${fileResult.conflicts.length} conflict(s):\\n${fileResult.conflicts.map((c) => ` - ${c.filePath}: ${c.description}`).join('\\n')}\\n\\nPull first or use force=true.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Pre-flight rejected files. A push that produced zero side\n // effects (no upload, no update, no delete) because every\n // candidate was rejected is a failure from the agent's\n // perspective \u2014 surface it as VALIDATION_ERROR so the tool\n // call doesn't quietly look like a success.\n //\n // Note `appliedAny` includes deletes: a mirror push that\n // removed remote-only files BUT had every upload candidate\n // rejected has still mutated remote state, so the response\n // must show the deletes (treated as a partial success), not\n // an error that hides them.\n if (fileResult.rejected && fileResult.rejected.length > 0) {\n const summary = fileResult.rejected.map((r) => ` - ${r.filePath}: ${r.detail}`).join('\\n');\n const appliedAny =\n fileResult.uploaded.length + fileResult.updated.length + fileResult.deleted.length > 0;\n if (!appliedAny) {\n return errorResponse(\n `Push rejected \u2014 backend would refuse every candidate file:\\n${summary}`,\n 'VALIDATION_ERROR',\n );\n }\n // Partial success: at least some side effects applied.\n // Fall through to successResponse below so the caller\n // sees the full files.{uploaded,updated,deleted,rejected}\n // breakdown and can decide how strict to be.\n }\n\n // Per-file mid-push failures (5xx, transient errors). These\n // reach the agent as a separate signal from `rejected`\n // (pre-flight). We always surface them \u2014 if the entire push\n // failed mid-flight with no side effects, return error so\n // the agent retries; otherwise let the partial success\n // through so the agent can see what stuck.\n if (fileResult.failed && fileResult.failed.length > 0) {\n const failureSummary = fileResult.failed\n .map((f) => ` - ${f.filePath} (${f.operation}): ${f.reason}`)\n .join('\\n');\n const appliedAny =\n fileResult.uploaded.length + fileResult.updated.length + fileResult.deleted.length > 0;\n if (!appliedAny) {\n return errorResponse(\n `Push failed mid-flight \u2014 every attempted file errored:\\n${failureSummary}`,\n 'NETWORK_ERROR',\n );\n }\n }\n\n // Push apps (only with JWT auth)\n let appResult = null;\n if (authType === 'jwt') {\n const appSyncService = new AppSyncService(tenant, client);\n appResult = await appSyncService.push();\n }\n\n const ignoredLocalEntries = fileResult.ignoredLocal ?? [];\n const ignoredLocalCount = fileResult.ignoredLocalTotal ?? 0;\n const ignoredLocalTotalByReason = fileResult.ignoredLocalTotalByReason ?? {\n unsupportedExtension: 0,\n blocklistedFolder: 0,\n };\n // Drive the breakdown from the UNCAPPED per-reason totals so\n // the numbers in the suffix agree with the headline even\n // when the path slice was truncated.\n const ignoredBreakdown = summariseIgnoredReasons(ignoredLocalTotalByReason);\n const ignoredSuffix =\n ignoredLocalCount > 0\n ? ignoredBreakdown\n ? ` (${ignoredLocalCount} local file(s) outside scope: ${ignoredBreakdown} \u2014 see files.ignoredLocal)`\n : ` (${ignoredLocalCount} local file(s) outside scope \u2014 see files.ignoredLocal)`\n : '';\n return successResponse({\n tenant,\n organisation,\n files: {\n uploaded: fileResult.uploaded,\n updated: fileResult.updated,\n deleted: fileResult.deleted,\n unchanged: fileResult.unchanged.length,\n rejected: fileResult.rejected ?? [],\n failed: fileResult.failed ?? [],\n // Surface scope-skipped files so an agent calling\n // push gets the same silent-skip signal CLI users\n // see in the warning line. Without this, agents\n // reported \"push complete\" while local .csv / .md /\n // .py work-in-progress sat unsent on disk.\n // Entries are { path, reason } so the agent can\n // present category-specific advice \u2014 extension\n // broadening vs blocklisted-folder warning.\n ignoredLocal: ignoredLocalEntries,\n ignoredLocalTotal: ignoredLocalCount,\n ignoredLocalTotalByReason,\n },\n apps: appResult\n ? {\n created: appResult.created,\n updated: appResult.updated,\n unchanged: appResult.unchanged.length,\n }\n : { note: 'App sync requires browser login (JWT)' },\n summary: `Pushed ${fileResult.uploaded.length + fileResult.updated.length} files${appResult ? ` and ${appResult.created.length + appResult.updated.length} apps` : ''}${fileResult.rejected && fileResult.rejected.length > 0 ? ` (${fileResult.rejected.length} skipped \u2014 see files.rejected)` : ''}${fileResult.failed && fileResult.failed.length > 0 ? ` (${fileResult.failed.length} failed mid-push \u2014 see files.failed)` : ''}${ignoredSuffix}`,\n });\n } catch (error) {\n return errorResponse(`Push failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_status - Check sync status\n server.tool(\n 'farseer_status',\n `Check the synchronization status between local files and the remote Farseer instance.\n\nShows which files are:\n- Modified locally (changed since last sync)\n- Modified remotely (changed on server since last sync)\n- Only local (new files not yet pushed)\n- Only remote (files not yet pulled)\n- In sync (no changes)\n\nAlso shows app sync status if using JWT authentication.\n\nOut-of-scope local files: \\`files.ignoredLocal\\` is an array of\n\\`{ path, reason }\\` entries listing user-authored files that exist on disk\nbut were silently skipped because they don't match the current sync scope\n(default scope is .ts / .js). \\`reason\\` is one of \\`unsupportedExtension\\`\n(extension not in default scope \u2014 broaden via \\`--include-ext\\`) or\n\\`blocklistedFolder\\` (file lives under a tooling-output folder like\nnode_modules/ or dist/ \u2014 opting in is unusual). Use this to detect the\n\"local edits exist but status reports clean\" failure mode before reporting\n\"everything is in sync\" to the user. Hidden files (.env, .git/, .vscode/)\nare NEVER listed there \u2014 those require explicit opt-in via the CLI's\n\\`farseer config include\\` and the response does not advertise widening\nscope to include them. \\`ignoredLocalTotal\\` carries the uncapped count\nwhen the slice was truncated.\n\nSync includes: If the user has configured extra file types via \"farseer config include\"\n(e.g., .json extensions or specific folders like \"Config\"), those files are automatically\nincluded in the status check alongside default script files.\n\nDeep vs shallow: Default is deep \u2014 every remote file is hashed so the response surfaces\nremote-side content edits made since the last pull. Pass shallow=true to skip the hash\ncheck (faster on big tenants; trusts the recorded baseline, so it cannot detect content\nedits to existing remote files). Matches the CLI's --shallow flag.`,\n statusSchema,\n async (params: {\n all?: boolean;\n shallow?: boolean;\n deep?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client, authType } = gate.session;\n\n try {\n // Normalise extensions: agents may pass them dotless (\"json\"\n // vs \".json\"), but downstream comparisons are against\n // `path.extname()` which always has a dot.\n const syncService = new SyncService(tenant, client);\n // Deep is the default; `shallow: true` opts into the faster\n // list-only path. Matches the CLI's --shallow flag.\n //\n // `deep` is a deprecated backwards-compat alias for callers\n // written against the 1.6.1 schema. Resolution order:\n // 1. shallow=true \u2192 deep: false (explicit opt-out wins)\n // 2. deep=false \u2192 deep: false (legacy fast-path)\n // 3. deep=true or unset \u2192 deep: true (the new default)\n // This keeps the schema-validated surface backwards-\n // compatible with existing MCP callers that haven't been\n // rewritten yet, without confusing combinations.\n const effectiveDeep = params.shallow === true ? false : params.deep !== false;\n const fileStatus = await syncService.getStatus({\n all: params.all,\n deep: effectiveDeep,\n includeExtensions: params.includeExtensions\n ? normalizeExtensions(params.includeExtensions)\n : undefined,\n includeFolders: params.includeFolders,\n });\n\n // Get app status (only with JWT auth)\n let appStatus = null;\n if (authType === 'jwt') {\n const appSyncService = new AppSyncService(tenant, client);\n appStatus = await appSyncService.getStatus();\n }\n\n const hasChanges =\n fileStatus.modifiedLocally.length > 0 ||\n fileStatus.modifiedRemotely.length > 0 ||\n fileStatus.addedLocally.length > 0 ||\n fileStatus.addedRemotely.length > 0 ||\n fileStatus.deletedLocally.length > 0 ||\n fileStatus.deletedRemotely.length > 0 ||\n fileStatus.conflicts.length > 0;\n\n // Surface scope-skipped files so agents calling MCP see\n // the same silent-skip signal CLI users get. Without this\n // an agent that ran status on a tenant where the user has\n // unsaved .csv / .md / .py edits gets a clean \"Everything\n // is in sync\" \u2014 exactly the failure the CLI fix addressed.\n // Hidden files (.env, .git/) are upstream-excluded so the\n // response can't tell the agent to widen scope to include\n // a credential file.\n return successResponse({\n tenant,\n organisation,\n files: {\n addedLocally: fileStatus.addedLocally,\n modifiedLocally: fileStatus.modifiedLocally,\n deletedLocally: fileStatus.deletedLocally,\n addedRemotely: fileStatus.addedRemotely,\n modifiedRemotely: fileStatus.modifiedRemotely,\n deletedRemotely: fileStatus.deletedRemotely,\n inSync: fileStatus.inSync.length,\n deepCompare: fileStatus.deepCompare,\n conflicts: fileStatus.conflicts.map((c) => ({\n file: c.filePath,\n type: c.type,\n description: c.description,\n })),\n ignoredLocal: fileStatus.ignoredLocal,\n ignoredLocalTotal: fileStatus.ignoredLocalTotal,\n ignoredLocalTotalByReason: fileStatus.ignoredLocalTotalByReason,\n },\n apps: appStatus\n ? {\n newLocal: appStatus.newLocal,\n newRemote: appStatus.newRemote,\n modified: appStatus.modified,\n synced: appStatus.synced.length,\n }\n : { note: 'App sync requires browser login (JWT)' },\n summary: (() => {\n if (fileStatus.conflicts?.length) {\n return `${fileStatus.conflicts.length} conflict(s) detected`;\n }\n if (hasChanges) return 'Changes detected';\n if (fileStatus.ignoredLocalTotal > 0) {\n // No drift within scope \u2014 but local files\n // outside scope exist. Agents quote this\n // summary back to users; a flat \"Everything is\n // in sync\" would hide that .md / .csv / .py\n // work was never compared. Include the reason\n // breakdown so the user sees whether they need\n // to broaden by extension or are looking at\n // ignored tooling output.\n //\n // Drive the breakdown from the UNCAPPED per-\n // reason totals so e.g. \"250 outside scope\"\n // doesn't pair with \"100 with unsupported\n // extension\" when all 250 are that reason.\n const breakdown = summariseIgnoredReasons(fileStatus.ignoredLocalTotalByReason);\n const suffix = breakdown\n ? `${fileStatus.ignoredLocalTotal} local file(s) outside scope: ${breakdown}`\n : `${fileStatus.ignoredLocalTotal} local file(s) outside scope`;\n return `Everything in sync within current scope (${suffix} \u2014 see files.ignoredLocal)`;\n }\n return 'Everything is in sync';\n })(),\n });\n } catch (error) {\n return errorResponse(`Status check failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_diff - Show file differences\n server.tool(\n 'farseer_diff',\n `Show the differences between local and remote versions of files.\n\nCan show:\n- Unified diff format (default)\n- Just the remote content (showRemote=true)\n\nUseful for reviewing changes before pull or push.\n\nIf no file is specified, shows diffs for all changed files.`,\n diffSchema,\n async (params: { file?: string; showRemote?: boolean }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const syncService = new SyncService(tenant, client);\n\n if (params.file) {\n // Single file diff\n const { localContent, remoteContent } = await syncService.getFileDiff(params.file);\n\n if (params.showRemote) {\n return successResponse({\n file: params.file,\n remoteContent: remoteContent || '(file does not exist on remote)',\n });\n }\n\n const diff = createPatch(params.file, remoteContent || '', localContent || '', 'remote', 'local');\n\n return successResponse({\n file: params.file,\n localExists: localContent !== null,\n remoteExists: remoteContent !== null,\n diff,\n });\n } else {\n // All changed files\n const status = await syncService.getStatus();\n const changedFiles = [\n ...status.addedLocally,\n ...status.modifiedLocally,\n ...status.deletedLocally,\n ...status.addedRemotely,\n ...status.modifiedRemotely,\n ...status.deletedRemotely,\n ];\n\n const diffs: Array<{\n file: string;\n localExists: boolean;\n remoteExists: boolean;\n diff: string;\n }> = [];\n\n for (const f of changedFiles.slice(0, 10)) {\n // Limit to 10 files\n const { localContent, remoteContent } = await syncService.getFileDiff(f);\n const diff = createPatch(f, remoteContent || '', localContent || '', 'remote', 'local');\n diffs.push({\n file: f,\n localExists: localContent !== null,\n remoteExists: remoteContent !== null,\n diff,\n });\n }\n\n return successResponse({\n totalChangedFiles: changedFiles.length,\n diffs,\n note:\n changedFiles.length > 10\n ? `Showing first 10 of ${changedFiles.length} changed files`\n : undefined,\n });\n }\n } catch (error) {\n return errorResponse(`Diff failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_list_files - List remote files\n server.tool(\n 'farseer_list_files',\n `Lists files stored on the remote Farseer instance in the Files/ folder.\n\nIMPORTANT: this tool defaults to script files only (.ts, .js),\nmatching the CLI's \"farseer files list\" command which is intended for\ninspecting app scripts. This is NARROWER than the default sync scope used\nby farseer_pull / farseer_status / farseer_push (which sync developer files\n(.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder\nblocklist; data files like .csv / .xlsx / .parquet are backend-accepted\nbut excluded from default).\n\nUse all=true to list every file the remote knows about.\n\nReturns file paths relative to the Files/ folder.`,\n listFilesSchema,\n async (params: { all?: boolean }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client } = gate.session;\n\n try {\n let files = await client.listFiles();\n\n // Filter to scripts unless --all\n if (!params.all) {\n const scriptExtensions = ['.ts', '.js'];\n files = files.filter((f) => scriptExtensions.some((ext) => f.name.toLowerCase().endsWith(ext)));\n }\n\n // Group by directory\n const byDirectory: Record<string, string[]> = {};\n for (const file of files) {\n const dir = file.path.includes('/') ? file.path.split('/').slice(0, -1).join('/') : '.';\n if (!byDirectory[dir]) {\n byDirectory[dir] = [];\n }\n byDirectory[dir].push(file.name);\n }\n\n return successResponse({\n tenant,\n organisation,\n totalFiles: files.length,\n files: files.map((f) => ({\n name: f.name,\n path: f.path,\n reference: f.reference,\n })),\n byDirectory,\n });\n } catch (error) {\n return errorResponse(`List files failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA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AA;AAAA;AAAA,IAaA;AAAA,IACA,OAAO,WAA8B;AACjC,YAAM,OAAO,UAAM,+BAAe;AAClC,UAAI,CAAC,KAAK,GAAI,QAAO,KAAK;AAC1B,YAAM,EAAE,cAAc,QAAQ,OAAO,IAAI,KAAK;AAE9C,UAAI;AACA,YAAI,QAAQ,MAAM,OAAO,UAAU;AAGnC,YAAI,CAAC,OAAO,KAAK;AACb,gBAAM,mBAAmB,CAAC,OAAO,KAAK;AACtC,kBAAQ,MAAM,OAAO,CAAC,MAAM,iBAAiB,KAAK,CAAC,QAAQ,EAAE,KAAK,YAAY,EAAE,SAAS,GAAG,CAAC,CAAC;AAAA,QAClG;AAGA,cAAM,cAAwC,CAAC;AAC/C,mBAAW,QAAQ,OAAO;AACtB,gBAAM,MAAM,KAAK,KAAK,SAAS,GAAG,IAAI,KAAK,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG,IAAI;AACpF,cAAI,CAAC,YAAY,GAAG,GAAG;AACnB,wBAAY,GAAG,IAAI,CAAC;AAAA,UACxB;AACA,sBAAY,GAAG,EAAE,KAAK,KAAK,IAAI;AAAA,QACnC;AAEA,mBAAO,gCAAgB;AAAA,UACnB;AAAA,UACA;AAAA,UACA,YAAY,MAAM;AAAA,UAClB,OAAO,MAAM,IAAI,CAAC,OAAO;AAAA,YACrB,MAAM,EAAE;AAAA,YACR,MAAM,EAAE;AAAA,YACR,WAAW,EAAE;AAAA,UACjB,EAAE;AAAA,UACF;AAAA,QACJ,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,8BAAc,sBAAsB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MAChG;AAAA,IACJ;AAAA,EACJ;AACJ;",
|
|
4
|
+
"sourcesContent": ["/**\n * File Synchronization Tools\n *\n * Tools for syncing files between local repository and Farseer instance.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { createPatch } from 'diff';\nimport { SyncService } from '../../services/syncService';\nimport { AppSyncService } from '../../services/appSyncService';\nimport { requireSession } from '../utils/session';\nimport { successResponse, errorResponse } from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\nimport { normalizeExtensions } from '../../utils/cliOptions';\n\n/**\n * Format a category breakdown for the MCP summary string when\n * `ignoredLocal` is non-empty. Agents quote the summary verbatim back\n * to users, so the breakdown has to fit on one line and stay readable\n * without the structured array.\n *\n * Examples:\n * - \"5 with unsupported extension\"\n * - \"3 in blocklisted folders\"\n * - \"5 with unsupported extension, 3 in blocklisted folders\"\n *\n * Takes the UNCAPPED per-reason totals tracked during the walk, not\n * counts from the stored slice. The slice is capped at\n * `IGNORED_LOCAL_CAP` to bound memory, so counting it would give the\n * user a number that disagrees with the headline \u2014 e.g. headline\n * \"250 outside scope\" with breakdown \"100 with unsupported extension\"\n * when all 250 are unsupported-extension files.\n *\n * Returns an empty string when both totals are zero; the caller still\n * gates on `total > 0` and falls back to a plain pointer when this\n * comes back empty.\n */\nfunction summariseIgnoredReasons(totals: { unsupportedExtension: number; blocklistedFolder: number }): string {\n const parts: string[] = [];\n if (totals.unsupportedExtension > 0) parts.push(`${totals.unsupportedExtension} with unsupported extension`);\n if (totals.blocklistedFolder > 0) parts.push(`${totals.blocklistedFolder} in blocklisted folders`);\n return parts.join(', ');\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\n//\n// `includeExtensions` and `includeFolders` mirror the CLI's `--include-ext` /\n// `--include-folder` flags. Without them on the MCP surface, an agent could\n// only choose between the default scope and \"all\" \u2014 there was no way to\n// scope a pull/push/status to \"default plus this one folder\" the way a CLI\n// user can.\nconst includeExtensionsSchema = z\n .array(z.string())\n .optional()\n .describe(\n 'Extra file extensions to include alongside the default scope (developer files ' +\n '(.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). ' +\n 'Data files (.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 ' +\n 'opt in here (e.g. [\"csv\"]). Supply with or without leading dot (\".csv\" or \"csv\") \u2014 ' +\n \"both work; the handler normalises before matching. Mirrors the CLI's --include-ext flag.\",\n );\nconst includeFoldersSchema = z\n .array(z.string())\n .optional()\n .describe(\n 'Extra folder paths whose files (any extension) are included alongside the default scope. ' +\n 'Useful for opting into hidden or blocklisted folders. Each path is interpreted ' +\n 'relative to the tenant root, e.g. \"Data\" or \".vscode\" or \"dist\". ' +\n \"Mirrors the CLI's --include-folder flag.\",\n );\n\nconst pullSchema = {\n all: z\n .boolean()\n .optional()\n .describe(\n 'Pull every non-hidden, non-blocklisted file (default: developer files (.ts, .js, .py, ' +\n '.yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). Data files ' +\n '(.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 opt in ' +\n 'via includeExtensions (e.g. [\"csv\"]) or pass all=true to broaden everything.',\n ),\n force: z\n .boolean()\n .optional()\n .describe(\n 'DESTRUCTIVE \u2014 overwrites EVERY locally-modified file with the remote version, including ' +\n \"local edits that have no remote conflict (e.g. a file you've been editing but the remote \" +\n 'is still on the baseline version). Use only when the user has explicitly asked to ' +\n 'discard local changes. Does NOT delete local-only files (that destructive wipe stays ' +\n 'on the CLI side behind the interactive confirm prompt).',\n ),\n includeExtensions: includeExtensionsSchema,\n includeFolders: includeFoldersSchema,\n};\n\nconst pushSchema = {\n force: z\n .boolean()\n .optional()\n .describe(\n 'Skip the drift check and overwrite remote even if it diverged from baseline. ' +\n 'Does NOT delete remote-only files; pass mirror=true for that.',\n ),\n mirror: z\n .boolean()\n .optional()\n .describe(\n 'Also delete remote files that have no local counterpart \u2014 destructive \"make remote = local\" semantics. ' +\n \"Implies the upload step still respects the user's local presence, so this only fires for files \" +\n 'genuinely missing locally. Combine with force=true if the drift check would otherwise refuse the push.',\n ),\n all: z\n .boolean()\n .optional()\n .describe(\n 'Push every non-hidden, non-blocklisted file (default: developer files (.ts, .js, .py, ' +\n '.yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). Data files ' +\n '(.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 opt in ' +\n 'via includeExtensions. Hidden files / blocklisted folders still require explicit ' +\n 'opt-in via includeFolders.',\n ),\n includeExtensions: includeExtensionsSchema,\n includeFolders: includeFoldersSchema,\n};\n\nconst statusSchema = {\n all: z\n .boolean()\n .optional()\n .describe(\n 'Show status for every non-hidden, non-blocklisted file (default: developer files ' +\n '(.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). ' +\n 'Data files (.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 ' +\n 'opt in via includeExtensions (e.g. [\"csv\"]) or pass all=true to broaden everything.',\n ),\n // Deep is the default \u2014 matches the CLI's `farseer status` behaviour\n // (deep-by-default since 1.6.2). Agents should pass `shallow: true`\n // only when they have independent reason to trust the last-pull\n // baseline (e.g. checking immediately after a successful pull) and\n // want the faster path on a large tenant.\n shallow: z\n .boolean()\n .optional()\n .describe(\n 'Skip remote-content hashing. Faster on big tenants but cannot detect remote-side edits to existing ' +\n 'files made since the last pull. Default is deep \u2014 every remote file is hashed.',\n ),\n // Backwards-compat alias for callers written against the 1.6.1 MCP\n // schema, where deep=false was the fast-path opt-out. We map it to\n // shallow internally; if both are passed, shallow wins (explicit\n // opt-out beats the legacy positive). New callers should use shallow.\n deep: z\n .boolean()\n .optional()\n .describe(\n '(Deprecated) Backwards-compat alias for the pre-1.6.2 fast-path control. ' +\n 'Pass shallow=true instead. If both are supplied, shallow takes precedence.',\n ),\n includeExtensions: includeExtensionsSchema,\n includeFolders: includeFoldersSchema,\n};\n\nconst diffSchema = {\n file: z.string().optional().describe('Specific file path to diff. If omitted, shows all differences.'),\n showRemote: z.boolean().optional().describe('Show only the remote content instead of diff'),\n};\n\nconst listFilesSchema = {\n all: z\n .boolean()\n .optional()\n .describe(\n 'By default, lists files with script extensions only (.ts, .js, .mjs, .cjs), matching ' +\n \"the CLI's `farseer files list`. This is NARROWER than the default sync scope used \" +\n 'by farseer_pull/status/push. Set all=true to list every file on the remote.',\n ),\n};\n\nexport function registerSyncTools(server: McpServer): void {\n // farseer_pull - Download files from remote\n server.tool(\n 'farseer_pull',\n `Pull (download) files and app configurations from a Farseer instance to the local repository.\n\nFor a prepared data pipeline, use farseer_pipeline operation=pull to sync that pipeline's source scope. Start with operation=guide topic=method when authoring a pipeline.\n\nWhat gets pulled:\n- Files from the tenant Files/ folder (searched recursively)\n- App configurations (saved as JSON in apps/ folder)\n\nFiles are saved to: farseer-apps/<tenant>/files/\nApps are saved to: farseer-apps/<tenant>/apps/\n\nDefault sync scope: developer files (.ts, .js, .py, .yml, .yaml, .md, .json) that sit\noutside hidden directories (.git/, .vscode/, .env*) and the folder blocklist\n(node_modules/, dist/, build/, vendor/, target/, tmp/, \u2026). Data files (.csv,\n.xlsx, .parquet, .pdf, images, \u2026) are backend-accepted but EXCLUDED from default\n\u2014 opt in via includeExtensions (e.g. [\"csv\"]). Hidden paths and blocklisted\nfolders require explicit opt-in.\nUse all=true to broaden the scope to every non-hidden, non-blocklisted file\n(extensions outside the backend whitelist, files with no extension, etc.).\nUse includeExtensions / includeFolders to broaden the scope without pulling everything\n(e.g. includeFolders=[\".vscode\"] adds the .vscode folder regardless of extension).\nThese mirror the CLI's --include-ext / --include-folder flags and are additive on\ntop of the default scope.\n\nConflict handling:\n- Per-file conflict resolution (keep_local / keep_remote / keep_both / merge_markers)\n is CLI-only \u2014 it requires an interactive prompt and the MCP can't answer one.\n- The MCP path returns conflicts in response.conflicts[] so the agent can re-pull\n with force=true once the user has confirmed they want to discard their edits.\n- force=true is DESTRUCTIVE: it overwrites every locally-modified file with the\n remote version (even local edits that don't conflict with remote). It does NOT\n wipe local-only files (that destructive step lives behind the CLI's confirm prompt).\n Only pass force=true when the user has explicitly accepted losing local changes.\n\nSync includes (middle ground between the default scope and all):\n- Users can configure extra extensions and folders via \"farseer config include\" CLI command\n- These are stored per-tenant in ~/.farseer/config.json under \"syncIncludes\"\n- When configured, pull/push/status automatically include those files alongside the default scope\n- Example: syncIncludes may add extra extensions or otherwise blocklisted folders like \"dist\" or \".vscode\"\n- The sync includes are respected automatically \u2014 no extra parameters needed here`,\n pullSchema,\n async (params: { all?: boolean; force?: boolean; includeExtensions?: string[]; includeFolders?: string[] }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client, authType } = gate.session;\n\n try {\n // Pull files (use tenant for folder path).\n // Normalise extensions: agents pass them with or without a\n // leading dot (\".json\" vs \"json\"), but downstream comparisons\n // are against `path.extname()` which always has a dot.\n // Without this, includeExtensions=[\"json\"] would silently\n // never match anything.\n const syncService = new SyncService(tenant, client);\n const fileResult = await syncService.pull({\n all: params.all,\n force: params.force,\n includeExtensions: params.includeExtensions\n ? normalizeExtensions(params.includeExtensions)\n : undefined,\n includeFolders: params.includeFolders,\n });\n\n // Pull apps (only with JWT auth)\n let appResult = null;\n if (authType === 'jwt') {\n const appSyncService = new AppSyncService(tenant, client);\n appResult = await appSyncService.pull();\n }\n\n const response: Record<string, any> = {\n tenant,\n organisation,\n files: {\n downloaded: fileResult.downloaded,\n deleted: fileResult.deleted,\n unchanged: fileResult.unchanged.length,\n },\n apps: appResult\n ? {\n created: appResult.created,\n updated: appResult.updated,\n deleted: appResult.deleted,\n unchanged: appResult.unchanged.length,\n }\n : { note: 'App sync requires browser login (JWT)' },\n message: `Pulled ${fileResult.downloaded.length} files${appResult ? ` and ${appResult.created.length + appResult.updated.length} apps` : ''}`,\n };\n\n if (fileResult.conflicts.length > 0) {\n response.conflicts = fileResult.conflicts.map((c) => ({\n file: c.filePath,\n type: c.type,\n description: c.description,\n }));\n response.message = `Pulled ${fileResult.downloaded.length} files but ${fileResult.conflicts.length} conflict(s) need resolution`;\n response.hint =\n 'Use force=true to overwrite local changes, or resolve conflicts via CLI: farseer pull <tenant>';\n }\n\n if (fileResult.conflictFilesWritten.length > 0) {\n response.conflictFilesWritten = fileResult.conflictFilesWritten;\n }\n\n return successResponse(response);\n } catch (error) {\n return errorResponse(`Pull failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_push - Upload files to remote\n server.tool(\n 'farseer_push',\n `Push (upload) local file and app changes to a Farseer instance.\n\nFor a prepared data pipeline, use farseer_pipeline operation=push to sync that pipeline's source scope. Start with operation=guide topic=method when authoring a pipeline.\n\nWhat gets pushed:\n- New/modified files from farseer-apps/<tenant>/files/ (filtered by sync scope \u2014\n default is developer files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories\n and the folder blocklist. Data files like .csv / .xlsx / .parquet are backend-accepted\n but excluded from default; broaden via includeExtensions / includeFolders / all on\n this tool, or via persistent sync includes set with the CLI's \"farseer config include\").\n- New/modified app configurations from farseer-apps/<tenant>/apps/.\n- Deleted files (when they were previously synced \u2014 preserves \"I rm'd this\" semantics).\n\nPre-flight (runs before any HTTP call):\n- Refuses files the backend would refuse anyway: extension not on whitelist,\n filename longer than 256 chars, empty body, unresolved git-style merge markers\n (<<<<<<< LOCAL / ======= / >>>>>>> REMOTE) left over from a merge_markers pull.\n- Returns rejected files in the response. If every candidate is rejected (and\n no deletes/updates either), the tool call returns VALIDATION_ERROR.\n\nDrift / mirror semantics:\n- force=true skips the drift check (push over remote-side adds/deletes).\n- mirror=true (separate param) also deletes remote files that have no local\n counterpart, within the current sync scope. Combine with force when both are\n needed.\n\nOut-of-scope files (e.g. a hidden .vscode/settings.json next to in-scope files)\nare INVISIBLE to push \u2014 never uploaded, never deleted. Hidden paths require\nexplicit opt-in via --include-folder (extension includes never widen scope to\nhidden files \u2014 that would let a generic .json broadening leak credentials).\n\nSilent-skip signal: \\`files.ignoredLocal\\` is an array of\n\\`{ path, reason }\\` entries listing non-hidden user files that exist on\ndisk but were outside the active sync scope and therefore NOT pushed.\n\\`reason\\` is one of:\n - \\`unsupportedExtension\\`: file extension isn't in default scope (e.g.\n .csv, .md). Tell the user to broaden with \\`--include-ext <ext>\\`.\n - \\`blocklistedFolder\\`: file is in a tooling-output folder (node_modules/,\n dist/, build/). These are almost never user content \u2014 warn the user\n that opting in is unusual instead of suggesting the flag outright.\n\\`files.ignoredLocalTotal\\` carries the uncapped count when the list was\ntruncated. Hidden files (.env, .git/, .vscode/) never appear here \u2014 the\nresponse does not advertise widening scope to include them. Use this list to\ndetect \"push succeeded but my local .csv / .md / .py files weren't sent\"\nbefore reporting success to the user.\n\nSync includes: if user configured via \"farseer config include\", drift and scope\nchecks respect those settings automatically.`,\n pushSchema,\n async (params: {\n force?: boolean;\n mirror?: boolean;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client, authType } = gate.session;\n\n try {\n const syncService = new SyncService(tenant, client);\n\n // Normalise extensions once: agents may pass them dotless\n // (\"json\" vs \".json\"), but downstream comparisons are\n // against `path.extname()` which always has a dot. Build\n // the scope once and reuse it so the drift check and push\n // run in identical scope.\n const scopeOptions = {\n all: params.all,\n includeExtensions: params.includeExtensions\n ? normalizeExtensions(params.includeExtensions)\n : undefined,\n includeFolders: params.includeFolders,\n };\n\n // Non-force push must not silently overwrite remote-side\n // drift. The previous `checkRemoteChanges` gate was a\n // list-only diff against the recorded baseline \u2014 it could\n // see remote-side adds/deletes but not content edits to\n // existing files. That's the same Matej-class blind spot\n // the CLI gate closed in 1.6.2: run a DEEP status so\n // remote content drift surfaces, then block if any\n // remote-side bucket has paths in scope.\n if (!params.force) {\n const status = await syncService.getStatus({\n ...scopeOptions,\n deep: true,\n });\n const conflicting = [\n ...status.modifiedRemotely,\n ...status.addedRemotely,\n ...status.deletedRemotely,\n ];\n if (conflicting.length > 0) {\n // Mirror the CLI's behaviour at push.ts:211-216 \u2014\n // echo the active scope flags back into the\n // suggested pull command so a default-scope pull\n // doesn't run, report \"Already up to date\", and\n // leave the agent stuck in the same drift loop.\n const scopeFlags: string[] = [];\n if (params.all) scopeFlags.push('--all');\n for (const ext of params.includeExtensions ?? []) scopeFlags.push(`--include-ext ${ext}`);\n for (const folder of params.includeFolders ?? [])\n scopeFlags.push(`--include-folder \"${folder}\"`);\n const pullCmd = ['farseer pull', tenant, ...scopeFlags].join(' ');\n return errorResponse(\n `Remote has changes for ${conflicting.length} file(s) since last pull:\\n` +\n conflicting.map((p) => ` - ${p}`).join('\\n') +\n `\\n\\nRun \\`${pullCmd}\\` first, or use force=true to overwrite remote.`,\n 'VALIDATION_ERROR',\n );\n }\n }\n\n // Push files. Pass `mirror` separately from `force` so an\n // agent must opt in explicitly to remote-side deletes \u2014 the\n // CLI gates this behind a confirm prompt, the MCP can't, so\n // we make it a separate parameter the caller has to set.\n const fileResult = await syncService.push({\n ...scopeOptions,\n force: params.force,\n mirror: params.mirror,\n });\n\n // Check for conflicts\n if (fileResult.conflicts.length > 0) {\n return errorResponse(\n `Push blocked by ${fileResult.conflicts.length} conflict(s):\\n${fileResult.conflicts.map((c) => ` - ${c.filePath}: ${c.description}`).join('\\n')}\\n\\nPull first or use force=true.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Pre-flight rejected files. A push that produced zero side\n // effects (no upload, no update, no delete) because every\n // candidate was rejected is a failure from the agent's\n // perspective \u2014 surface it as VALIDATION_ERROR so the tool\n // call doesn't quietly look like a success.\n //\n // Note `appliedAny` includes deletes: a mirror push that\n // removed remote-only files BUT had every upload candidate\n // rejected has still mutated remote state, so the response\n // must show the deletes (treated as a partial success), not\n // an error that hides them.\n if (fileResult.rejected && fileResult.rejected.length > 0) {\n const summary = fileResult.rejected.map((r) => ` - ${r.filePath}: ${r.detail}`).join('\\n');\n const appliedAny =\n fileResult.uploaded.length + fileResult.updated.length + fileResult.deleted.length > 0;\n if (!appliedAny) {\n return errorResponse(\n `Push rejected \u2014 backend would refuse every candidate file:\\n${summary}`,\n 'VALIDATION_ERROR',\n );\n }\n // Partial success: at least some side effects applied.\n // Fall through to successResponse below so the caller\n // sees the full files.{uploaded,updated,deleted,rejected}\n // breakdown and can decide how strict to be.\n }\n\n // Per-file mid-push failures (5xx, transient errors). These\n // reach the agent as a separate signal from `rejected`\n // (pre-flight). We always surface them \u2014 if the entire push\n // failed mid-flight with no side effects, return error so\n // the agent retries; otherwise let the partial success\n // through so the agent can see what stuck.\n if (fileResult.failed && fileResult.failed.length > 0) {\n const failureSummary = fileResult.failed\n .map((f) => ` - ${f.filePath} (${f.operation}): ${f.reason}`)\n .join('\\n');\n const appliedAny =\n fileResult.uploaded.length + fileResult.updated.length + fileResult.deleted.length > 0;\n if (!appliedAny) {\n return errorResponse(\n `Push failed mid-flight \u2014 every attempted file errored:\\n${failureSummary}`,\n 'NETWORK_ERROR',\n );\n }\n }\n\n // Push apps (only with JWT auth)\n let appResult = null;\n if (authType === 'jwt') {\n const appSyncService = new AppSyncService(tenant, client);\n appResult = await appSyncService.push();\n }\n\n const ignoredLocalEntries = fileResult.ignoredLocal ?? [];\n const ignoredLocalCount = fileResult.ignoredLocalTotal ?? 0;\n const ignoredLocalTotalByReason = fileResult.ignoredLocalTotalByReason ?? {\n unsupportedExtension: 0,\n blocklistedFolder: 0,\n };\n // Drive the breakdown from the UNCAPPED per-reason totals so\n // the numbers in the suffix agree with the headline even\n // when the path slice was truncated.\n const ignoredBreakdown = summariseIgnoredReasons(ignoredLocalTotalByReason);\n const ignoredSuffix =\n ignoredLocalCount > 0\n ? ignoredBreakdown\n ? ` (${ignoredLocalCount} local file(s) outside scope: ${ignoredBreakdown} \u2014 see files.ignoredLocal)`\n : ` (${ignoredLocalCount} local file(s) outside scope \u2014 see files.ignoredLocal)`\n : '';\n return successResponse({\n tenant,\n organisation,\n files: {\n uploaded: fileResult.uploaded,\n updated: fileResult.updated,\n deleted: fileResult.deleted,\n unchanged: fileResult.unchanged.length,\n rejected: fileResult.rejected ?? [],\n failed: fileResult.failed ?? [],\n // Surface scope-skipped files so an agent calling\n // push gets the same silent-skip signal CLI users\n // see in the warning line. Without this, agents\n // reported \"push complete\" while local .csv / .md /\n // .py work-in-progress sat unsent on disk.\n // Entries are { path, reason } so the agent can\n // present category-specific advice \u2014 extension\n // broadening vs blocklisted-folder warning.\n ignoredLocal: ignoredLocalEntries,\n ignoredLocalTotal: ignoredLocalCount,\n ignoredLocalTotalByReason,\n },\n apps: appResult\n ? {\n created: appResult.created,\n updated: appResult.updated,\n unchanged: appResult.unchanged.length,\n }\n : { note: 'App sync requires browser login (JWT)' },\n summary: `Pushed ${fileResult.uploaded.length + fileResult.updated.length} files${appResult ? ` and ${appResult.created.length + appResult.updated.length} apps` : ''}${fileResult.rejected && fileResult.rejected.length > 0 ? ` (${fileResult.rejected.length} skipped \u2014 see files.rejected)` : ''}${fileResult.failed && fileResult.failed.length > 0 ? ` (${fileResult.failed.length} failed mid-push \u2014 see files.failed)` : ''}${ignoredSuffix}`,\n });\n } catch (error) {\n return errorResponse(`Push failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_status - Check sync status\n server.tool(\n 'farseer_status',\n `Check the synchronization status between local files and the remote Farseer instance.\n\nShows which files are:\n- Modified locally (changed since last sync)\n- Modified remotely (changed on server since last sync)\n- Only local (new files not yet pushed)\n- Only remote (files not yet pulled)\n- In sync (no changes)\n\nAlso shows app sync status if using JWT authentication.\n\nOut-of-scope local files: \\`files.ignoredLocal\\` is an array of\n\\`{ path, reason }\\` entries listing user-authored files that exist on disk\nbut were silently skipped because they don't match the current sync scope\n(default scope is .ts / .js). \\`reason\\` is one of \\`unsupportedExtension\\`\n(extension not in default scope \u2014 broaden via \\`--include-ext\\`) or\n\\`blocklistedFolder\\` (file lives under a tooling-output folder like\nnode_modules/ or dist/ \u2014 opting in is unusual). Use this to detect the\n\"local edits exist but status reports clean\" failure mode before reporting\n\"everything is in sync\" to the user. Hidden files (.env, .git/, .vscode/)\nare NEVER listed there \u2014 those require explicit opt-in via the CLI's\n\\`farseer config include\\` and the response does not advertise widening\nscope to include them. \\`ignoredLocalTotal\\` carries the uncapped count\nwhen the slice was truncated.\n\nSync includes: If the user has configured extra file types via \"farseer config include\"\n(e.g., .json extensions or specific folders like \"Config\"), those files are automatically\nincluded in the status check alongside default script files.\n\nDeep vs shallow: Default is deep \u2014 every remote file is hashed so the response surfaces\nremote-side content edits made since the last pull. Pass shallow=true to skip the hash\ncheck (faster on big tenants; trusts the recorded baseline, so it cannot detect content\nedits to existing remote files). Matches the CLI's --shallow flag.`,\n statusSchema,\n async (params: {\n all?: boolean;\n shallow?: boolean;\n deep?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client, authType } = gate.session;\n\n try {\n // Normalise extensions: agents may pass them dotless (\"json\"\n // vs \".json\"), but downstream comparisons are against\n // `path.extname()` which always has a dot.\n const syncService = new SyncService(tenant, client);\n // Deep is the default; `shallow: true` opts into the faster\n // list-only path. Matches the CLI's --shallow flag.\n //\n // `deep` is a deprecated backwards-compat alias for callers\n // written against the 1.6.1 schema. Resolution order:\n // 1. shallow=true \u2192 deep: false (explicit opt-out wins)\n // 2. deep=false \u2192 deep: false (legacy fast-path)\n // 3. deep=true or unset \u2192 deep: true (the new default)\n // This keeps the schema-validated surface backwards-\n // compatible with existing MCP callers that haven't been\n // rewritten yet, without confusing combinations.\n const effectiveDeep = params.shallow === true ? false : params.deep !== false;\n const fileStatus = await syncService.getStatus({\n all: params.all,\n deep: effectiveDeep,\n includeExtensions: params.includeExtensions\n ? normalizeExtensions(params.includeExtensions)\n : undefined,\n includeFolders: params.includeFolders,\n });\n\n // Get app status (only with JWT auth)\n let appStatus = null;\n if (authType === 'jwt') {\n const appSyncService = new AppSyncService(tenant, client);\n appStatus = await appSyncService.getStatus();\n }\n\n const hasChanges =\n fileStatus.modifiedLocally.length > 0 ||\n fileStatus.modifiedRemotely.length > 0 ||\n fileStatus.addedLocally.length > 0 ||\n fileStatus.addedRemotely.length > 0 ||\n fileStatus.deletedLocally.length > 0 ||\n fileStatus.deletedRemotely.length > 0 ||\n fileStatus.conflicts.length > 0;\n\n // Surface scope-skipped files so agents calling MCP see\n // the same silent-skip signal CLI users get. Without this\n // an agent that ran status on a tenant where the user has\n // unsaved .csv / .md / .py edits gets a clean \"Everything\n // is in sync\" \u2014 exactly the failure the CLI fix addressed.\n // Hidden files (.env, .git/) are upstream-excluded so the\n // response can't tell the agent to widen scope to include\n // a credential file.\n return successResponse({\n tenant,\n organisation,\n files: {\n addedLocally: fileStatus.addedLocally,\n modifiedLocally: fileStatus.modifiedLocally,\n deletedLocally: fileStatus.deletedLocally,\n addedRemotely: fileStatus.addedRemotely,\n modifiedRemotely: fileStatus.modifiedRemotely,\n deletedRemotely: fileStatus.deletedRemotely,\n inSync: fileStatus.inSync.length,\n deepCompare: fileStatus.deepCompare,\n conflicts: fileStatus.conflicts.map((c) => ({\n file: c.filePath,\n type: c.type,\n description: c.description,\n })),\n ignoredLocal: fileStatus.ignoredLocal,\n ignoredLocalTotal: fileStatus.ignoredLocalTotal,\n ignoredLocalTotalByReason: fileStatus.ignoredLocalTotalByReason,\n },\n apps: appStatus\n ? {\n newLocal: appStatus.newLocal,\n newRemote: appStatus.newRemote,\n modified: appStatus.modified,\n synced: appStatus.synced.length,\n }\n : { note: 'App sync requires browser login (JWT)' },\n summary: (() => {\n if (fileStatus.conflicts?.length) {\n return `${fileStatus.conflicts.length} conflict(s) detected`;\n }\n if (hasChanges) return 'Changes detected';\n if (fileStatus.ignoredLocalTotal > 0) {\n // No drift within scope \u2014 but local files\n // outside scope exist. Agents quote this\n // summary back to users; a flat \"Everything is\n // in sync\" would hide that .md / .csv / .py\n // work was never compared. Include the reason\n // breakdown so the user sees whether they need\n // to broaden by extension or are looking at\n // ignored tooling output.\n //\n // Drive the breakdown from the UNCAPPED per-\n // reason totals so e.g. \"250 outside scope\"\n // doesn't pair with \"100 with unsupported\n // extension\" when all 250 are that reason.\n const breakdown = summariseIgnoredReasons(fileStatus.ignoredLocalTotalByReason);\n const suffix = breakdown\n ? `${fileStatus.ignoredLocalTotal} local file(s) outside scope: ${breakdown}`\n : `${fileStatus.ignoredLocalTotal} local file(s) outside scope`;\n return `Everything in sync within current scope (${suffix} \u2014 see files.ignoredLocal)`;\n }\n return 'Everything is in sync';\n })(),\n });\n } catch (error) {\n return errorResponse(`Status check failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_diff - Show file differences\n server.tool(\n 'farseer_diff',\n `Show the differences between local and remote versions of files.\n\nCan show:\n- Unified diff format (default)\n- Just the remote content (showRemote=true)\n\nUseful for reviewing changes before pull or push.\n\nIf no file is specified, shows diffs for all changed files.`,\n diffSchema,\n async (params: { file?: string; showRemote?: boolean }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n const syncService = new SyncService(tenant, client);\n\n if (params.file) {\n // Single file diff\n const { localContent, remoteContent } = await syncService.getFileDiff(params.file);\n\n if (params.showRemote) {\n return successResponse({\n file: params.file,\n remoteContent: remoteContent || '(file does not exist on remote)',\n });\n }\n\n const diff = createPatch(params.file, remoteContent || '', localContent || '', 'remote', 'local');\n\n return successResponse({\n file: params.file,\n localExists: localContent !== null,\n remoteExists: remoteContent !== null,\n diff,\n });\n } else {\n // All changed files\n const status = await syncService.getStatus();\n const changedFiles = [\n ...status.addedLocally,\n ...status.modifiedLocally,\n ...status.deletedLocally,\n ...status.addedRemotely,\n ...status.modifiedRemotely,\n ...status.deletedRemotely,\n ];\n\n const diffs: Array<{\n file: string;\n localExists: boolean;\n remoteExists: boolean;\n diff: string;\n }> = [];\n\n for (const f of changedFiles.slice(0, 10)) {\n // Limit to 10 files\n const { localContent, remoteContent } = await syncService.getFileDiff(f);\n const diff = createPatch(f, remoteContent || '', localContent || '', 'remote', 'local');\n diffs.push({\n file: f,\n localExists: localContent !== null,\n remoteExists: remoteContent !== null,\n diff,\n });\n }\n\n return successResponse({\n totalChangedFiles: changedFiles.length,\n diffs,\n note:\n changedFiles.length > 10\n ? `Showing first 10 of ${changedFiles.length} changed files`\n : undefined,\n });\n }\n } catch (error) {\n return errorResponse(`Diff failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_list_files - List remote files\n server.tool(\n 'farseer_list_files',\n `Lists files stored on the remote Farseer instance in the Files/ folder.\n\nIMPORTANT: this tool defaults to script files only (.ts, .js),\nmatching the CLI's \"farseer files list\" command which is intended for\ninspecting app scripts. This is NARROWER than the default sync scope used\nby farseer_pull / farseer_status / farseer_push (which sync developer files\n(.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder\nblocklist; data files like .csv / .xlsx / .parquet are backend-accepted\nbut excluded from default).\n\nUse all=true to list every file the remote knows about.\n\nReturns file paths relative to the Files/ folder.`,\n listFilesSchema,\n async (params: { all?: boolean }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client } = gate.session;\n\n try {\n let files = await client.listFiles();\n\n // Filter to scripts unless --all\n if (!params.all) {\n const scriptExtensions = ['.ts', '.js'];\n files = files.filter((f) => scriptExtensions.some((ext) => f.name.toLowerCase().endsWith(ext)));\n }\n\n // Group by directory\n const byDirectory: Record<string, string[]> = {};\n for (const file of files) {\n const dir = file.path.includes('/') ? file.path.split('/').slice(0, -1).join('/') : '.';\n if (!byDirectory[dir]) {\n byDirectory[dir] = [];\n }\n byDirectory[dir].push(file.name);\n }\n\n return successResponse({\n tenant,\n organisation,\n totalFiles: files.length,\n files: files.map((f) => ({\n name: f.name,\n path: f.path,\n reference: f.reference,\n })),\n byDirectory,\n });\n } catch (error) {\n return errorResponse(`List files failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,kBAA4B;AAC5B,yBAA4B;AAC5B,4BAA+B;AAC/B,qBAA+B;AAC/B,qBAA+C;AAC/C,4BAAkC;AAClC,wBAAoC;AAwBp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O,KAAK;AAC1B,YAAM,EAAE,cAAc,QAAQ,OAAO,IAAI,KAAK;AAE9C,UAAI;AACA,YAAI,QAAQ,MAAM,OAAO,UAAU;AAGnC,YAAI,CAAC,OAAO,KAAK;AACb,gBAAM,mBAAmB,CAAC,OAAO,KAAK;AACtC,kBAAQ,MAAM,OAAO,CAAC,MAAM,iBAAiB,KAAK,CAAC,QAAQ,EAAE,KAAK,YAAY,EAAE,SAAS,GAAG,CAAC,CAAC;AAAA,QAClG;AAGA,cAAM,cAAwC,CAAC;AAC/C,mBAAW,QAAQ,OAAO;AACtB,gBAAM,MAAM,KAAK,KAAK,SAAS,GAAG,IAAI,KAAK,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG,IAAI;AACpF,cAAI,CAAC,YAAY,GAAG,GAAG;AACnB,wBAAY,GAAG,IAAI,CAAC;AAAA,UACxB;AACA,sBAAY,GAAG,EAAE,KAAK,KAAK,IAAI;AAAA,QACnC;AAEA,mBAAO,gCAAgB;AAAA,UACnB;AAAA,UACA;AAAA,UACA,YAAY,MAAM;AAAA,UAClB,OAAO,MAAM,IAAI,CAAC,OAAO;AAAA,YACrB,MAAM,EAAE;AAAA,YACR,MAAM,EAAE;AAAA,YACR,WAAW,EAAE;AAAA,UACjB,EAAE;AAAA,UACF;AAAA,QACJ,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,8BAAc,sBAAsB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MAChG;AAAA,IACJ;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": []
|
|
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;A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C;AACA,MAAI,UAAU,SAAS,aAAa;AAChC,UAAM,WAAW,QAAQ,QAAQ,eAAe,QAAQ,QAAQ,eAAe;AAC/E,UAAM,UAAU,UAAM,yCAAkB,QAAQ,GAAG,IAAI,KAAK,UAAU,UAAU,SAAS,QAAQ;AACjG,WAAO,EAAE,OAAO,cAAc,SAAS,kBAAkB,EAAE;AAAA,EAC/D;AACA,SAAO,EAAE,OAAO,cAAc,GAAG,QAAQ,UAAU,WAAW,KAAK,QAAQ,eAAe,WAAW,EAAE;AAC3G;",
|
|
6
|
+
"names": ["realm", "login"]
|
|
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)();
|