farseer-cli 1.10.1 → 1.10.2

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.
@@ -23,8 +23,9 @@ __export(authTools_exports, {
23
23
  module.exports = __toCommonJS(authTools_exports);
24
24
  var import_zod = require("zod");
25
25
  var import_configService = require("../../services/configService");
26
- var import_farseerFactory = require("../../services/farseerFactory");
26
+ var import_preflight = require("../../services/preflight");
27
27
  var import_helpers = require("../utils/helpers");
28
+ var import_session = require("../utils/session");
28
29
  var import_tenantPin = require("../utils/tenantPin");
29
30
  const selectTenantSchema = {
30
31
  tenant: import_zod.z.string().describe(`Tenant to bind this session to (e.g. "salvus-prodaja"), from the user's request.`),
@@ -46,13 +47,15 @@ If not authenticated, run "farseer login" in a terminal.`,
46
47
  const status = (0, import_helpers.getAuthStatus)();
47
48
  const pin = status.tenant;
48
49
  const message = !pin ? "No tenant selected yet. Tell me which tenant/client to work on and I will call farseer_select_tenant to connect (once per session)." : status.launchPinned ? `This session is locked to tenant "${pin.tenant}" (org: ${pin.organisation}), fixed at launch.` : `This session is working on tenant "${pin.tenant}" (org: ${pin.organisation}), selected and locked for the session.`;
50
+ const warning = (0, import_session.getSessionWarning)();
49
51
  return (0, import_helpers.successResponse)({
50
52
  jwtValid: status.jwtValid,
51
53
  jwtExpiresAt: status.jwtExpiresAt,
52
54
  tenant: pin,
53
55
  tenantLocked: !!pin,
54
56
  configuredTenants: status.configuredTenants,
55
- message
57
+ warning: warning && (0, import_helpers.describeSessionWarning)(warning),
58
+ message: warning ? `${message} ${(0, import_helpers.describeSessionWarning)(warning)}` : message
56
59
  });
57
60
  }
58
61
  );
@@ -84,12 +87,9 @@ Use this before any other farseer tool when no tenant is set yet (farseer_whoami
84
87
  );
85
88
  }
86
89
  const org = organisation || (0, import_configService.getTenantOrg)(tenant) || tenant;
87
- const client = await (0, import_farseerFactory.getFarseerClientWithFallback)(org, tenant);
88
- if (!client) {
89
- return (0, import_helpers.errorResponse)(
90
- `Could not connect to tenant "${tenant}" (org: "${org}"). Check the tenant name and that you're logged in ("farseer login"), then call farseer_select_tenant again.`,
91
- "AUTH_REQUIRED"
92
- );
90
+ const outcome = await (0, import_preflight.openTenantSession)(org, tenant);
91
+ if (!outcome.ok) {
92
+ return (0, import_helpers.describeSessionFailure)(outcome.failure, "Correct it and call farseer_select_tenant again.");
93
93
  }
94
94
  const result = (0, import_tenantPin.selectTenant)({ organisation: org, tenant });
95
95
  if (!result.ok) {
@@ -98,9 +98,12 @@ Use this before any other farseer tool when no tenant is set yet (farseer_whoami
98
98
  "VALIDATION_ERROR"
99
99
  );
100
100
  }
101
+ (0, import_session.rememberSession)(result.checkout, outcome.auth, outcome.warning);
102
+ const selected = `Selected tenant "${result.checkout.tenant}" (org: ${result.checkout.organisation}). This session is now locked to it for its lifetime.`;
101
103
  return (0, import_helpers.successResponse)({
102
104
  tenant: result.checkout,
103
- message: `Selected tenant "${result.checkout.tenant}" (org: ${result.checkout.organisation}). This session is now locked to it for its lifetime.`
105
+ warning: outcome.warning && (0, import_helpers.describeSessionWarning)(outcome.warning),
106
+ message: outcome.warning ? `${selected} ${(0, import_helpers.describeSessionWarning)(outcome.warning)}` : selected
104
107
  });
105
108
  }
106
109
  );
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/tools/authTools.ts"],
4
- "sourcesContent": ["/**\n * Authentication + tenant-binding tools.\n *\n * A server operates on one tenant per session. It is bound either at launch\n * (`mcp-server --tenant`) or once at runtime via `farseer_select_tenant`, then\n * locked. Binding never touches `~/.farseer/config.json` \u2014 it is in-memory and\n * per-process, so concurrent sessions can hold different tenants without\n * colliding.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { getTenantOrg } from '../../services/configService';\nimport { getFarseerClientWithFallback } from '../../services/farseerFactory';\nimport { getAuthStatus, successResponse, errorResponse } from '../utils/helpers';\nimport { selectTenant, getTenantPin, isLaunchPinned } from '../utils/tenantPin';\n\n// Defined outside registration to avoid deep zod type instantiation.\nconst selectTenantSchema = {\n tenant: z.string().describe('Tenant to bind this session to (e.g. \"salvus-prodaja\"), from the user\\'s request.'),\n organisation: z\n .string()\n .optional()\n .describe('Organisation subdomain. Defaults to the saved mapping for the tenant, else the tenant name.'),\n};\n\nexport function registerAuthTools(server: McpServer): void {\n // farseer_whoami - Auth status + the tenant this session is bound to\n server.tool(\n 'farseer_whoami',\n `Check Farseer authentication status and the tenant this session is bound to.\n\nReturns:\n- Whether a JWT (browser login) is valid and when it expires\n- The tenant this session operates on, and whether it is locked\n- Tenants with API keys configured\n\nIf not authenticated, run \"farseer login\" in a terminal.`,\n {},\n async () => {\n const status = getAuthStatus();\n const pin = status.tenant;\n const message = !pin\n ? 'No tenant selected yet. Tell me which tenant/client to work on and I will call farseer_select_tenant to connect (once per session).'\n : status.launchPinned\n ? `This session is locked to tenant \"${pin.tenant}\" (org: ${pin.organisation}), fixed at launch.`\n : `This session is working on tenant \"${pin.tenant}\" (org: ${pin.organisation}), selected and locked for the session.`;\n return successResponse({\n jwtValid: status.jwtValid,\n jwtExpiresAt: status.jwtExpiresAt,\n tenant: pin,\n tenantLocked: !!pin,\n configuredTenants: status.configuredTenants,\n message,\n });\n },\n );\n\n // farseer_select_tenant - Bind this session to a tenant, once\n server.tool(\n 'farseer_select_tenant',\n `Bind this MCP session to a Farseer tenant. Call this once when the user says which tenant/client to work on.\n\nRules:\n- Works only if the server was launched without --tenant. If it was launched with --tenant, it is already locked and this returns an error.\n- Can be called only ONCE. After the first selection the tenant is locked for the session and cannot be changed. To work on a different tenant, start a new session.\n- The tenant must be reachable (you must be logged in). If it can't be connected \u2014 wrong name or not logged in \u2014 selection fails WITHOUT locking, so you can correct it and call again.\n\nUse this before any other farseer tool when no tenant is set yet (farseer_whoami tells you).`,\n selectTenantSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { tenant: string; organisation?: string }) => {\n const { tenant, organisation } = params;\n\n // A locked session can't change tenant. Reject before any network\n // call, and don't verify a tenant we won't bind to.\n if (isLaunchPinned()) {\n return errorResponse(\n `This server is pinned to tenant \"${getTenantPin()!.tenant}\" via --tenant; the tenant cannot be changed from here.`,\n 'VALIDATION_ERROR',\n );\n }\n const bound = getTenantPin();\n if (bound) {\n return errorResponse(\n `This session is already working on tenant \"${bound.tenant}\" and the tenant cannot be changed. Start a new session to use a different tenant.`,\n 'VALIDATION_ERROR',\n );\n }\n\n const org = organisation || getTenantOrg(tenant) || tenant;\n\n // Verify the tenant is reachable BEFORE locking. Selection is\n // one-shot, so without this a typo'd or unauthenticated tenant would\n // pin the session to a dead tenant for its whole lifetime, fixable\n // only by restarting the server.\n const client = await getFarseerClientWithFallback(org, tenant);\n if (!client) {\n return errorResponse(\n `Could not connect to tenant \"${tenant}\" (org: \"${org}\"). Check the tenant name and that you're logged in (\"farseer login\"), then call farseer_select_tenant again.`,\n 'AUTH_REQUIRED',\n );\n }\n\n const result = selectTenant({ organisation: org, tenant });\n if (!result.ok) {\n // Lost a race to a concurrent selection between the check above\n // and here \u2014 treat as already-bound.\n return errorResponse(\n `This session is already working on tenant \"${result.current.tenant}\" and the tenant cannot be changed. Start a new session to use a different tenant.`,\n 'VALIDATION_ERROR',\n );\n }\n return successResponse({\n tenant: result.checkout,\n message: `Selected tenant \"${result.checkout.tenant}\" (org: ${result.checkout.organisation}). This session is now locked to it for its lifetime.`,\n });\n },\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,iBAAkB;AAClB,2BAA6B;AAC7B,4BAA6C;AAC7C,qBAA8D;AAC9D,uBAA2D;AAG3D,MAAM,qBAAqB;AAAA,EACvB,QAAQ,aAAE,OAAO,EAAE,SAAS,kFAAmF;AAAA,EAC/G,cAAc,aACT,OAAO,EACP,SAAS,EACT,SAAS,6FAA6F;AAC/G;AAEO,SAAS,kBAAkB,QAAyB;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AA,UACnE;AAAA,QACJ;AAAA,MACJ;AACA,iBAAO,gCAAgB;AAAA,QACnB,QAAQ,OAAO;AAAA,QACf,SAAS,oBAAoB,OAAO,SAAS,MAAM,WAAW,OAAO,SAAS,YAAY;AAAA,MAC9F,CAAC;AAAA,IACL;AAAA,EACJ;AACJ;",
4
+ "sourcesContent": ["/** Authentication and tenant binding. See tenantPin.ts for the binding rules. */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { getTenantOrg } from '../../services/configService';\nimport { openTenantSession } from '../../services/preflight';\nimport {\n getAuthStatus,\n successResponse,\n errorResponse,\n describeSessionFailure,\n describeSessionWarning,\n} from '../utils/helpers';\nimport { getSessionWarning, rememberSession } from '../utils/session';\nimport { selectTenant, getTenantPin, isLaunchPinned } from '../utils/tenantPin';\n\n// Defined outside registration to avoid deep zod type instantiation.\nconst selectTenantSchema = {\n tenant: z.string().describe('Tenant to bind this session to (e.g. \"salvus-prodaja\"), from the user\\'s request.'),\n organisation: z\n .string()\n .optional()\n .describe('Organisation subdomain. Defaults to the saved mapping for the tenant, else the tenant name.'),\n};\n\nexport function registerAuthTools(server: McpServer): void {\n // farseer_whoami - Auth status + the tenant this session is bound to\n server.tool(\n 'farseer_whoami',\n `Check Farseer authentication status and the tenant this session is bound to.\n\nReturns:\n- Whether a JWT (browser login) is valid and when it expires\n- The tenant this session operates on, and whether it is locked\n- Tenants with API keys configured\n\nIf not authenticated, run \"farseer login\" in a terminal.`,\n {},\n async () => {\n const status = getAuthStatus();\n const pin = status.tenant;\n const message = !pin\n ? 'No tenant selected yet. Tell me which tenant/client to work on and I will call farseer_select_tenant to connect (once per session).'\n : status.launchPinned\n ? `This session is locked to tenant \"${pin.tenant}\" (org: ${pin.organisation}), fixed at launch.`\n : `This session is working on tenant \"${pin.tenant}\" (org: ${pin.organisation}), selected and locked for the session.`;\n const warning = getSessionWarning();\n return successResponse({\n jwtValid: status.jwtValid,\n jwtExpiresAt: status.jwtExpiresAt,\n tenant: pin,\n tenantLocked: !!pin,\n configuredTenants: status.configuredTenants,\n warning: warning && describeSessionWarning(warning),\n message: warning ? `${message} ${describeSessionWarning(warning)}` : message,\n });\n },\n );\n\n // farseer_select_tenant - Bind this session to a tenant, once\n server.tool(\n 'farseer_select_tenant',\n `Bind this MCP session to a Farseer tenant. Call this once when the user says which tenant/client to work on.\n\nRules:\n- Works only if the server was launched without --tenant. If it was launched with --tenant, it is already locked and this returns an error.\n- Can be called only ONCE. After the first selection the tenant is locked for the session and cannot be changed. To work on a different tenant, start a new session.\n- The tenant must be reachable (you must be logged in). If it can't be connected \u2014 wrong name or not logged in \u2014 selection fails WITHOUT locking, so you can correct it and call again.\n\nUse this before any other farseer tool when no tenant is set yet (farseer_whoami tells you).`,\n selectTenantSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { tenant: string; organisation?: string }) => {\n const { tenant, organisation } = params;\n\n // A locked session can't change tenant. Reject before any network\n // call, and don't verify a tenant we won't bind to.\n if (isLaunchPinned()) {\n return errorResponse(\n `This server is pinned to tenant \"${getTenantPin()!.tenant}\" via --tenant; the tenant cannot be changed from here.`,\n 'VALIDATION_ERROR',\n );\n }\n const bound = getTenantPin();\n if (bound) {\n return errorResponse(\n `This session is already working on tenant \"${bound.tenant}\" and the tenant cannot be changed. Start a new session to use a different tenant.`,\n 'VALIDATION_ERROR',\n );\n }\n\n const org = organisation || getTenantOrg(tenant) || tenant;\n\n // Before locking: selection is one-shot, so this is the last moment a\n // wrong organisation is still correctable. Costs no extra round trip.\n const outcome = await openTenantSession(org, tenant);\n if (!outcome.ok) {\n return describeSessionFailure(outcome.failure, 'Correct it and call farseer_select_tenant again.');\n }\n\n const result = selectTenant({ organisation: org, tenant });\n if (!result.ok) {\n // Lost a race to a concurrent selection between the check above\n // and here \u2014 treat as already-bound.\n return errorResponse(\n `This session is already working on tenant \"${result.current.tenant}\" and the tenant cannot be changed. Start a new session to use a different tenant.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // The pair is proven and can no longer change, so the first tool call\n // has nothing left to ask.\n rememberSession(result.checkout, outcome.auth, outcome.warning);\n\n const selected = `Selected tenant \"${result.checkout.tenant}\" (org: ${result.checkout.organisation}). This session is now locked to it for its lifetime.`;\n return successResponse({\n tenant: result.checkout,\n warning: outcome.warning && describeSessionWarning(outcome.warning),\n message: outcome.warning ? `${selected} ${describeSessionWarning(outcome.warning)}` : selected,\n });\n },\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAkB;AAClB,2BAA6B;AAC7B,uBAAkC;AAClC,qBAMO;AACP,qBAAmD;AACnD,uBAA2D;AAG3D,MAAM,qBAAqB;AAAA,EACvB,QAAQ,aAAE,OAAO,EAAE,SAAS,kFAAmF;AAAA,EAC/G,cAAc,aACT,OAAO,EACP,SAAS,EACT,SAAS,6FAA6F;AAC/G;AAEO,SAAS,kBAAkB,QAAyB;AAEvD,SAAO;AAAA,IACH;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQA,CAAC;AAAA,IACD,YAAY;AACR,YAAM,aAAS,8BAAc;AAC7B,YAAM,MAAM,OAAO;AACnB,YAAM,UAAU,CAAC,MACX,wIACA,OAAO,eACL,qCAAqC,IAAI,MAAM,WAAW,IAAI,YAAY,wBAC1E,sCAAsC,IAAI,MAAM,WAAW,IAAI,YAAY;AACnF,YAAM,cAAU,kCAAkB;AAClC,iBAAO,gCAAgB;AAAA,QACnB,UAAU,OAAO;AAAA,QACjB,cAAc,OAAO;AAAA,QACrB,QAAQ;AAAA,QACR,cAAc,CAAC,CAAC;AAAA,QAChB,mBAAmB,OAAO;AAAA,QAC1B,SAAS,eAAW,uCAAuB,OAAO;AAAA,QAClD,SAAS,UAAU,GAAG,OAAO,QAAI,uCAAuB,OAAO,CAAC,KAAK;AAAA,MACzE,CAAC;AAAA,IACL;AAAA,EACJ;A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21
  authRequiredResponse: () => authRequiredResponse,
22
+ describeSessionFailure: () => describeSessionFailure,
23
+ describeSessionWarning: () => describeSessionWarning,
22
24
  errorResponse: () => errorResponse,
23
25
  getAuthStatus: () => getAuthStatus,
24
- getClient: () => getClient,
25
26
  getSessionTenant: () => getSessionTenant,
26
27
  successResponse: () => successResponse,
27
28
  tenantRequiredResponse: () => tenantRequiredResponse
28
29
  });
29
30
  module.exports = __toCommonJS(helpers_exports);
30
31
  var import_configService = require("../../services/configService");
31
- var import_farseerFactory = require("../../services/farseerFactory");
32
32
  var import_tenantPin = require("./tenantPin");
33
33
  var import_fileLogger = require("../../utils/fileLogger");
34
34
  function getSessionTenant() {
35
35
  return (0, import_tenantPin.getTenantPin)() ?? null;
36
36
  }
37
- async function getClient(organisation, tenant) {
38
- const result = await (0, import_farseerFactory.getFarseerClientWithFallback)(organisation, tenant);
39
- return result?.client || null;
40
- }
41
37
  function successResponse(data) {
42
38
  return {
43
39
  content: [
@@ -99,12 +95,31 @@ function getAuthStatus() {
99
95
  configuredTenants: Object.keys(credentials)
100
96
  };
101
97
  }
98
+ function describeSessionFailure(failure, remedy) {
99
+ switch (failure.reason) {
100
+ case "no-credentials":
101
+ return authRequiredResponse(failure.tenant);
102
+ case "org-unknown":
103
+ return errorResponse(`No Farseer organisation at "${failure.organisation}". ${remedy}`, "VALIDATION_ERROR");
104
+ case "pair-refuted": {
105
+ const known = failure.orgTenants.length > 0 ? ` Tenants you can access under "${failure.organisation}": ${failure.orgTenants.join(", ")}.` : "";
106
+ return errorResponse(
107
+ `Tenant "${failure.tenant}" is not available under organisation "${failure.organisation}".${known} ${remedy}`,
108
+ "VALIDATION_ERROR"
109
+ );
110
+ }
111
+ }
112
+ }
113
+ function describeSessionWarning(warning) {
114
+ return `Organisation "${warning.organisation}" is not being used: the stored API key for "${warning.tenant}" carries its own host (${warning.host}). The tenant is the bound one; the organisation has no effect.`;
115
+ }
102
116
  // Annotate the CommonJS export names for ESM import in node:
103
117
  0 && (module.exports = {
104
118
  authRequiredResponse,
119
+ describeSessionFailure,
120
+ describeSessionWarning,
105
121
  errorResponse,
106
122
  getAuthStatus,
107
- getClient,
108
123
  getSessionTenant,
109
124
  successResponse,
110
125
  tenantRequiredResponse
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/utils/helpers.ts"],
4
- "sourcesContent": ["/**\n * MCP Utility Functions\n *\n * Helper functions for MCP tools including tenant resolution and response formatting.\n */\n\nimport { getUserAuth, isUserAuthValid, listCredentials } from '../../services/configService';\nimport { getFarseerClientWithFallback, IFarseerClient } from '../../services/farseerFactory';\nimport { getTenantPin, isLaunchPinned } from './tenantPin';\nimport { fileLogger } from '../../utils/fileLogger';\n\n/**\n * The tenant this MCP server operates on, or null if none is set yet.\n *\n * The server is bound to a single tenant for its whole lifetime \u2014 pinned at\n * launch (`--tenant <slug>` / `FARSEER_TENANT`) or chosen once via\n * farseer_select_tenant. The CLI reads the same env vars, but per command;\n * this server reads them once, at launch (see mcp/utils/launchPin.ts), so\n * re-exporting FARSEER_TENANT mid-session can't retarget a running server.\n * Tools take no per-call tenant, so a call can only ever reach the bound\n * tenant. Callers surface tenantRequiredResponse() when this returns null.\n */\nexport function getSessionTenant(): { organisation: string; tenant: string } | null {\n return getTenantPin() ?? null;\n}\n\n/**\n * Get authenticated Farseer client.\n * The factory takes (organisation, tenant) \u2014 organisation is the subdomain\n * used to build the base URL, tenant is the X-TENANT-ID header value.\n */\nexport async function getClient(organisation: string, tenant: string): Promise<IFarseerClient | null> {\n const result = await getFarseerClientWithFallback(organisation, tenant);\n return result?.client || null;\n}\n\n/**\n * Create a success response\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\n/**\n * Create an error response. Also logs to file for diagnostics.\n */\nexport function errorResponse(\n message: string,\n errorCode?: 'AUTH_REQUIRED' | 'NOT_FOUND' | 'NETWORK_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN',\n): { content: Array<{ type: 'text'; text: string }>; isError: true } {\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 * Create auth required error response\n */\nexport function authRequiredResponse(tenant?: string): {\n content: Array<{ type: 'text'; text: string }>;\n isError: true;\n} {\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/**\n * Error response for when the server has no usable tenant for a tool call \u2014\n * either it was started without --tenant, or the call named a tenant other than\n * the one this server is bound to. States only how to fix the current situation.\n */\nexport function tenantRequiredResponse(): { content: Array<{ type: 'text'; text: string }>; isError: true } {\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\n/**\n * Get auth status info, including the tenant this server is bound to.\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"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,2BAA8D;AAC9D,4BAA6D;AAC7D,uBAA6C;AAC7C,wBAA2B;AAapB,SAAS,mBAAoE;AAChF,aAAO,+BAAa,KAAK;AAC7B;AAOA,eAAsB,UAAU,cAAsB,QAAgD;AAClG,QAAM,SAAS,UAAM,oDAA6B,cAAc,MAAM;AACtE,SAAO,QAAQ,UAAU;AAC7B;AAKO,SAAS,gBAAgB,MAAmF;AAC/G,SAAO;AAAA,IACH,SAAS;AAAA,MACL;AAAA,QACI,MAAM;AAAA,QACN,MAAM,KAAK,UAAU,EAAE,SAAS,MAAM,GAAG,KAAK,GAAG,MAAM,CAAC;AAAA,MAC5D;AAAA,IACJ;AAAA,EACJ;AACJ;AAKO,SAAS,cACZ,SACA,WACiE;AAEjE,+BAAW,MAAM,YAAY,SAAS,EAAE,WAAW,aAAa,UAAU,CAAC;AAE3E,SAAO;AAAA,IACH,SAAS;AAAA,MACL;AAAA,QACI,MAAM;AAAA,QACN,MAAM,KAAK;AAAA,UACP;AAAA,YACI,SAAS;AAAA,YACT,OAAO;AAAA,YACP,WAAW,aAAa;AAAA,UAC5B;AAAA,UACA;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,IACA,SAAS;AAAA,EACb;AACJ;AAKO,SAAS,qBAAqB,QAGnC;AACE,QAAM,UAAU,SACV,uCAAuC,MAAM,4CAC7C;AAEN,SAAO,cAAc,SAAS,eAAe;AACjD;AAOO,SAAS,yBAA4F;AACxG,QAAM,UAAM,+BAAa;AACzB,MAAI,KAAK;AACL,WAAO;AAAA,MACH,sCAAsC,IAAI,MAAM;AAAA,MAChD;AAAA,IACJ;AAAA,EACJ;AAIA,QAAM,aAAa,OAAO,SAAK,sCAAgB,CAAC;AAChD,QAAM,OAAO,WAAW,SAAS,IAAI,gCAAgC,WAAW,KAAK,IAAI,CAAC,MAAM;AAChG,SAAO;AAAA,IACH,sLAAsL,IAAI;AAAA,IAC1L;AAAA,EACJ;AACJ;AAKO,SAAS,gBAMd;AACE,QAAM,WAAO,kCAAY;AACzB,QAAM,UAAM,+BAAa;AACzB,QAAM,kBAAc,sCAAgB;AAEpC,SAAO;AAAA,IACH,cAAU,sCAAgB;AAAA,IAC1B,cAAc,MAAM;AAAA,IACpB,QAAQ;AAAA,IACR,kBAAc,iCAAe;AAAA,IAC7B,mBAAmB,OAAO,KAAK,WAAW;AAAA,EAC9C;AACJ;",
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';\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\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"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,2BAA8D;AAE9D,uBAA6C;AAC7C,wBAA2B;AAOpB,SAAS,mBAAoE;AAChF,aAAO,+BAAa,KAAK;AAC7B;AAEO,SAAS,gBAAgB,MAAmF;AAC/G,SAAO;AAAA,IACH,SAAS;AAAA,MACL;AAAA,QACI,MAAM;AAAA,QACN,MAAM,KAAK,UAAU,EAAE,SAAS,MAAM,GAAG,KAAK,GAAG,MAAM,CAAC;AAAA,MAC5D;AAAA,IACJ;AAAA,EACJ;AACJ;AAIO,SAAS,cACZ,SACA,WACgB;AAEhB,+BAAW,MAAM,YAAY,SAAS,EAAE,WAAW,aAAa,UAAU,CAAC;AAE3E,SAAO;AAAA,IACH,SAAS;AAAA,MACL;AAAA,QACI,MAAM;AAAA,QACN,MAAM,KAAK;AAAA,UACP;AAAA,YACI,SAAS;AAAA,YACT,OAAO;AAAA,YACP,WAAW,aAAa;AAAA,UAC5B;AAAA,UACA;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,IACA,SAAS;AAAA,EACb;AACJ;AAEO,SAA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AgD,QAAQ,MAAM,2BAC1E,QAAQ,IAAI;AAE7C;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var session_exports = {};
20
+ __export(session_exports, {
21
+ getSessionWarning: () => getSessionWarning,
22
+ rememberSession: () => rememberSession,
23
+ requireSession: () => requireSession,
24
+ resetSessionCache: () => resetSessionCache
25
+ });
26
+ module.exports = __toCommonJS(session_exports);
27
+ var import_configService = require("../../services/configService");
28
+ var import_farseerFactory = require("../../services/farseerFactory");
29
+ var import_preflight = require("../../services/preflight");
30
+ var import_helpers = require("./helpers");
31
+ var import_tenantPin = require("./tenantPin");
32
+ let validated;
33
+ function credentialState(tenant, passedOverLogin) {
34
+ const credential = (0, import_configService.getCredential)(tenant);
35
+ const key = credential ? `${credential.basePath}|${credential.tenantId}|${credential.apiKey}` : "none";
36
+ const login = (0, import_configService.getUserAuth)();
37
+ const who = !login ? "none" : passedOverLogin ? `unusable:${login.refreshToken}` : `session:${loginSession(login)}`;
38
+ return `${who}|${key}`;
39
+ }
40
+ function passedOver(auth) {
41
+ return auth.kind === "apiKey" && !!(0, import_configService.getUserAuth)() && !(0, import_configService.isUserAuthValid)();
42
+ }
43
+ function loginSession(login) {
44
+ for (const token of [login.refreshToken, login.accessToken]) {
45
+ try {
46
+ const sid = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString("utf-8")).sid;
47
+ if (typeof sid === "string" && sid) {
48
+ return sid;
49
+ }
50
+ } catch {
51
+ }
52
+ }
53
+ return login.refreshToken;
54
+ }
55
+ async function requireSession() {
56
+ const pin = (0, import_tenantPin.getTenantPin)();
57
+ if (!pin) {
58
+ return { ok: false, response: (0, import_helpers.tenantRequiredResponse)() };
59
+ }
60
+ if (validated?.pin === pin && validated.credentials === credentialState(pin.tenant, validated.passedOverLogin)) {
61
+ const auth = await (0, import_farseerFactory.refreshAuth)(validated.auth);
62
+ if (!auth) {
63
+ validated = void 0;
64
+ return { ok: false, response: (0, import_helpers.authRequiredResponse)(pin.tenant) };
65
+ }
66
+ return { ok: true, session: (0, import_preflight.sessionFrom)(pin.organisation, pin.tenant, auth) };
67
+ }
68
+ const outcome = await (0, import_preflight.openTenantSession)(pin.organisation, pin.tenant);
69
+ if (!outcome.ok) {
70
+ return { ok: false, response: (0, import_helpers.describeSessionFailure)(outcome.failure, LOCKED_REMEDY) };
71
+ }
72
+ remember(pin, outcome.auth, outcome.warning);
73
+ return { ok: true, session: (0, import_preflight.sessionFrom)(outcome.organisation, outcome.tenant, outcome.auth) };
74
+ }
75
+ function rememberSession(pin, auth, warning) {
76
+ remember(pin, auth, warning);
77
+ }
78
+ function remember(pin, auth, warning) {
79
+ const passedOverLogin = passedOver(auth);
80
+ validated = { pin, auth, credentials: credentialState(pin.tenant, passedOverLogin), passedOverLogin, warning };
81
+ }
82
+ function getSessionWarning() {
83
+ const pin = (0, import_tenantPin.getTenantPin)();
84
+ return validated?.pin === pin ? validated?.warning : void 0;
85
+ }
86
+ function resetSessionCache() {
87
+ validated = void 0;
88
+ }
89
+ const LOCKED_REMEDY = "This session is locked to that pair for its lifetime \u2014 start a new server with the right organisation (--org, or FARSEER_ORG).";
90
+ // Annotate the CommonJS export names for ESM import in node:
91
+ 0 && (module.exports = {
92
+ getSessionWarning,
93
+ rememberSession,
94
+ requireSession,
95
+ resetSessionCache
96
+ });
97
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/mcp/utils/session.ts"],
4
+ "sourcesContent": ["/**\n * The tenant guard for MCP tools: the checks a CLI command runs, minus the exit.\n *\n * The pin cannot change for the life of the process, so the verdict is reached\n * once per credential. What is kept is the verdict and the credential, not a\n * built client \u2014 a browser token expires long before a long-lived server does.\n */\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n type CurrentCheckout,\n type UserAuth,\n} from '../../services/configService';\nimport { refreshAuth, type ResolvedAuth } from '../../services/farseerFactory';\nimport { openTenantSession, sessionFrom, type SessionWarning, type TenantSession } from '../../services/preflight';\nimport { authRequiredResponse, describeSessionFailure, tenantRequiredResponse } from './helpers';\nimport type { McpErrorResponse } from './helpers';\nimport { getTenantPin } from './tenantPin';\n\nexport type SessionResult = { ok: true; session: TenantSession } | { ok: false; response: McpErrorResponse };\n\n// Safe only because each server is a stdio process with a single client, on the\n// same terms as the pin it mirrors.\nlet validated:\n | {\n pin: CurrentCheckout;\n auth: ResolvedAuth;\n credentials: string;\n passedOverLogin: boolean;\n warning?: SessionWarning;\n }\n | undefined;\n\n/**\n * What the credential choice was made from, as one comparable value.\n *\n * A browser login is identified by its Keycloak session (`sid`), which token\n * rotation keeps and a new `farseer login` replaces \u2014 so the ordinary case, a\n * token renewed about once a minute, never re-runs the guard.\n *\n * A login the guard passed over for a key is the exception. Its refresh token\n * already failed, so nothing can rotate it, and a login made to recover can land\n * in the same Keycloak session when the browser still holds one. There the\n * refresh token itself is the identity: only replacing the login changes it.\n *\n * Without both, a key that stops working is reused until the process restarts,\n * while `farseer_whoami`, which reads the config directly, reports the new login\n * as valid.\n */\nfunction credentialState(tenant: string, passedOverLogin: boolean): string {\n const credential = getCredential(tenant);\n const key = credential ? `${credential.basePath}|${credential.tenantId}|${credential.apiKey}` : 'none';\n const login = getUserAuth();\n const who = !login ? 'none' : passedOverLogin ? `unusable:${login.refreshToken}` : `session:${loginSession(login)}`;\n return `${who}|${key}`;\n}\n\n/**\n * Read straight after a decision, when the guard has just tried to renew the\n * login: one that is still expired is one the refresh could not renew.\n */\nfunction passedOver(auth: ResolvedAuth): boolean {\n return auth.kind === 'apiKey' && !!getUserAuth() && !isUserAuthValid();\n}\n\nfunction loginSession(login: UserAuth): string {\n for (const token of [login.refreshToken, login.accessToken]) {\n try {\n const sid = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf-8')).sid;\n if (typeof sid === 'string' && sid) {\n return sid;\n }\n } catch {\n // Not a JWT; try the other token.\n }\n }\n // Unreadable, so the token itself: re-decides on every rotation \u2014 more often\n // than needed, never less.\n return login.refreshToken;\n}\n\n/** The gate every tool that talks to a tenant goes through. */\nexport async function requireSession(): Promise<SessionResult> {\n const pin = getTenantPin();\n if (!pin) {\n return { ok: false, response: tenantRequiredResponse() };\n }\n\n // Identity, not value: a different object means a different binding, and an\n // extra check is the safe way to be wrong. The credentials are part of the\n // key for the same reason \u2014 a verdict reached over one says nothing about\n // another. The pin survives either way; only the credential is re-decided.\n if (validated?.pin === pin && validated.credentials === credentialState(pin.tenant, validated.passedOverLogin)) {\n const auth = await refreshAuth(validated.auth);\n if (!auth) {\n // Drop the verdict rather than reuse a credential we can no longer mint.\n validated = undefined;\n return { ok: false, response: authRequiredResponse(pin.tenant) };\n }\n return { ok: true, session: sessionFrom(pin.organisation, pin.tenant, auth) };\n }\n\n const outcome = await openTenantSession(pin.organisation, pin.tenant);\n if (!outcome.ok) {\n return { ok: false, response: describeSessionFailure(outcome.failure, LOCKED_REMEDY) };\n }\n\n remember(pin, outcome.auth, outcome.warning);\n return { ok: true, session: sessionFrom(outcome.organisation, outcome.tenant, outcome.auth) };\n}\n\n/** Adopt a verdict reached elsewhere \u2014 `farseer_select_tenant` validates before it binds. */\nexport function rememberSession(pin: CurrentCheckout, auth: ResolvedAuth, warning?: SessionWarning): void {\n remember(pin, auth, warning);\n}\n\nfunction remember(pin: CurrentCheckout, auth: ResolvedAuth, warning?: SessionWarning): void {\n const passedOverLogin = passedOver(auth);\n validated = { pin, auth, credentials: credentialState(pin.tenant, passedOverLogin), passedOverLogin, warning };\n}\n\n/** Reported by `farseer_whoami`: true about this session, but not a failure. */\nexport function getSessionWarning(): SessionWarning | undefined {\n const pin = getTenantPin();\n return validated?.pin === pin ? validated?.warning : undefined;\n}\n\nexport function resetSessionCache(): void {\n validated = undefined;\n}\n\n// Past the lock there is no in-session fix.\nconst LOCKED_REMEDY =\n 'This session is locked to that pair for its lifetime \u2014 start a new server with the right organisation (--org, or FARSEER_ORG).';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,2BAMO;AACP,4BAA+C;AAC/C,uBAAwF;AACxF,qBAAqF;AAErF,uBAA6B;AAM7B,IAAI;AA0BJ,SAAS,gBAAgB,QAAgB,iBAAkC;AACvE,QAAM,iBAAa,oCAAc,MAAM;AACvC,QAAM,MAAM,aAAa,GAAG,WAAW,QAAQ,IAAI,WAAW,QAAQ,IAAI,WAAW,MAAM,KAAK;AAChG,QAAM,YAAQ,kCAAY;AAC1B,QAAM,MAAM,CAAC,QAAQ,SAAS,kBAAkB,YAAY,MAAM,YAAY,KAAK,WAAW,aAAa,KAAK,CAAC;AACjH,SAAO,GAAG,GAAG,IAAI,GAAG;AACxB;AAMA,SAAS,WAAW,MAA6B;AAC7C,SAAO,KAAK,SAAS,YAAY,CAAC,KAAC,kCAAY,KAAK,KAAC,sCAAgB;AACzE;AAEA,SAAS,aAAa,OAAyB;AAC3C,aAAW,SAAS,CAAC,MAAM,cAAc,MAAM,WAAW,GAAG;AACzD,QAAI;AACA,YAAM,MAAM,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,WAAW,EAAE,SAAS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,QAAQ,MAAM,WAAW,UAAU;AACzD;AAEO,SAAS,oBAA0B;AACtC,cAAY;AAChB;AAGA,MAAM,gBACF;",
6
+ "names": []
7
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/utils/tenantPin.ts"],
4
- "sourcesContent": ["/**\n * Per-process tenant binding for the MCP server.\n *\n * A server process operates on exactly one tenant for its whole lifetime. The\n * tenant is set once, one of two ways, then locked:\n *\n * - Launch pin: `mcp-server --tenant <slug>` binds it at startup (hard).\n * `farseer_select_tenant` is disabled in this mode.\n * - Runtime selection: launched without `--tenant`, an agent calls\n * `farseer_select_tenant` ONCE (e.g. when the user names a client). After\n * that first selection the tenant is locked and cannot be changed.\n *\n * State lives only in memory \u2014 the global checkout in `~/.farseer/config.json`\n * is never read or written. Each `farseer mcp-server` is its own process (stdio,\n * one client per process), so two sessions selecting different tenants can't\n * collide.\n */\n\nimport type { CurrentCheckout } from '../../services/configService';\n\n// Module singletons \u2014 safe ONLY because each server is a stdio process with a\n// single client. A client-multiplexing transport (HTTP/SSE) would share these\n// across clients and reintroduce the cross-tenant bleed this guards against.\nlet pin: CurrentCheckout | undefined;\nlet launchPinned = false;\n\n/** Bind at startup from `--tenant` (hard pin; disables runtime selection). */\nexport function setLaunchTenant(checkout: CurrentCheckout): void {\n pin = checkout;\n launchPinned = true;\n}\n\nexport type SelectResult =\n | { ok: true; checkout: CurrentCheckout }\n | { ok: false; reason: 'launch-pinned' | 'already-selected'; current: CurrentCheckout };\n\n/**\n * Runtime one-shot selection. Allowed only when the server was launched without\n * `--tenant` AND no tenant has been selected yet. Locks after the first success.\n */\nexport function selectTenant(checkout: CurrentCheckout): SelectResult {\n if (launchPinned) return { ok: false, reason: 'launch-pinned', current: pin! };\n if (pin) return { ok: false, reason: 'already-selected', current: pin };\n pin = checkout;\n return { ok: true, checkout };\n}\n\n/** The tenant this session is bound to, or undefined if not set yet. */\nexport function getTenantPin(): CurrentCheckout | undefined {\n return pin;\n}\n\n/** True when the tenant was fixed at launch via `--tenant`. */\nexport function isLaunchPinned(): boolean {\n return launchPinned;\n}\n\n/** Test helper: clear all binding state. */\nexport function resetTenantPin(): void {\n pin = undefined;\n launchPinned = false;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBA,IAAI;AACJ,IAAI,eAAe;AAGZ,SAAS,gBAAgB,UAAiC;AAC7D,QAAM;AACN,iBAAe;AACnB;AAUO,SAAS,aAAa,UAAyC;AAClE,MAAI,aAAc,QAAO,EAAE,IAAI,OAAO,QAAQ,iBAAiB,SAAS,IAAK;AAC7E,MAAI,IAAK,QAAO,EAAE,IAAI,OAAO,QAAQ,oBAAoB,SAAS,IAAI;AACtE,QAAM;AACN,SAAO,EAAE,IAAI,MAAM,SAAS;AAChC;AAGO,SAAS,eAA4C;AACxD,SAAO;AACX;AAGO,SAAS,iBAA0B;AACtC,SAAO;AACX;AAGO,SAAS,iBAAuB;AACnC,QAAM;AACN,iBAAe;AACnB;",
4
+ "sourcesContent": ["/**\n * Per-process tenant binding for the MCP server: set once, then locked, either\n * by `--tenant` at launch or by one `farseer_select_tenant` call.\n *\n * In memory only. The one thing that reaches `~/.farseer/config.json` is the\n * tenant->org mapping the guard records for a pair the organisation confirmed.\n * Whether a binding has been *checked* lives in session.ts.\n */\n\nimport type { CurrentCheckout } from '../../services/configService';\n\n// Safe ONLY because each server is a stdio process with a single client. A\n// multiplexing transport (HTTP/SSE) would share these and bleed across tenants.\nlet pin: CurrentCheckout | undefined;\nlet launchPinned = false;\n\n/** Bind at startup from `--tenant` (hard pin; disables runtime selection). */\nexport function setLaunchTenant(checkout: CurrentCheckout): void {\n pin = checkout;\n launchPinned = true;\n}\n\nexport type SelectResult =\n | { ok: true; checkout: CurrentCheckout }\n | { ok: false; reason: 'launch-pinned' | 'already-selected'; current: CurrentCheckout };\n\n/** One-shot selection: only when launched without `--tenant` and nothing bound yet. */\nexport function selectTenant(checkout: CurrentCheckout): SelectResult {\n if (launchPinned) return { ok: false, reason: 'launch-pinned', current: pin! };\n if (pin) return { ok: false, reason: 'already-selected', current: pin };\n pin = checkout;\n return { ok: true, checkout };\n}\n\nexport function getTenantPin(): CurrentCheckout | undefined {\n return pin;\n}\n\nexport function isLaunchPinned(): boolean {\n return launchPinned;\n}\n\nexport function resetTenantPin(): void {\n pin = undefined;\n launchPinned = false;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaA,IAAI;AACJ,IAAI,eAAe;AAGZ,SAAS,gBAAgB,UAAiC;AAC7D,QAAM;AACN,iBAAe;AACnB;AAOO,SAAS,aAAa,UAAyC;AAClE,MAAI,aAAc,QAAO,EAAE,IAAI,OAAO,QAAQ,iBAAiB,SAAS,IAAK;AAC7E,MAAI,IAAK,QAAO,EAAE,IAAI,OAAO,QAAQ,oBAAoB,SAAS,IAAI;AACtE,QAAM;AACN,SAAO,EAAE,IAAI,MAAM,SAAS;AAChC;AAEO,SAAS,eAA4C;AACxD,SAAO;AACX;AAEO,SAAS,iBAA0B;AACtC,SAAO;AACX;AAEO,SAAS,iBAAuB;AACnC,QAAM;AACN,iBAAe;AACnB;",
6
6
  "names": []
7
7
  }
@@ -146,14 +146,16 @@ function resolveAppItemNodeId(remoteJobId, items) {
146
146
  return item.id;
147
147
  }
148
148
  class FarseerApi {
149
- constructor(accessToken, tenant, tenantId) {
149
+ // basePath is passed in rather than worked out here. It used to come from
150
+ // `getCredential(...)?.basePath` keyed on the organisation, so a stored API
151
+ // key named after the organisation silently decided where a browser-login
152
+ // request went — and the SDK client for the same pair never consulted it.
153
+ // The one decision now lives in ResolvedAuth (services/farseerFactory).
154
+ constructor(accessToken, basePath, tenantId) {
150
155
  this.isRefreshing = false;
151
156
  this.refreshSubscribers = [];
152
- this.tenant = tenant;
153
- this.tenantId = tenantId || tenant;
157
+ this.tenantId = tenantId;
154
158
  this.accessToken = accessToken;
155
- const credential = (0, import_configService.getCredential)(tenant);
156
- const basePath = credential?.basePath || `https://${tenant}.farseer.io/api/v3`;
157
159
  this.basePath = basePath;
158
160
  this.client = import_axios.default.create({
159
161
  baseURL: basePath,