/** * Copyright (c) 2026, Salesforce, Inc., * All rights reserved. * For full license text, see the LICENSE.txt file */ import { type ConnectOutput, type ConnectSpec } from "./types.js"; import { type PrimeDeps, primeSchemaWithLock, SchemaRefreshError } from "../lib/prime-schema.js"; export interface ConnectDeps { primeDeps?: PrimeDeps; } /** * Build the `sf_gql_connect` payload (W-22845606). Primes the schema cache for * `spec.org`, or — with `spec.forceRefresh` — re-downloads it and coherently * clears all three caches (on-disk introspection JSON, in-memory parsed schema, * ObjectInfo). * * Failure policy (Q6 of the plan): a failed *refresh* that leaves a usable * cached schema behind is recoverable, so we return a soft `ConnectOutput` * (`refreshed: false`, `cached: true`) carrying a staleness-aware `warnings[]` * entry — the agent can keep working on the still-valid schema. A failure with * no prior cache (or any non-refresh failure such as missing auth) propagates, * so the MCP SDK surfaces it as a hard tool error. */ export async function buildConnect( spec: ConnectSpec, deps: ConnectDeps = {}, ): Promise { try { const prime = await primeSchemaWithLock(spec.org, deps.primeDeps, { forceRefresh: spec.forceRefresh, }); return { org: spec.org, instanceUrl: prime.instanceUrl, refreshed: prime.refreshed, cached: prime.cached, durationMs: prime.durationMs, }; } catch (e) { if (e instanceof SchemaRefreshError && e.staleSince) { return { org: spec.org, instanceUrl: e.instanceUrl, refreshed: false, cached: true, durationMs: 0, warnings: [e.message], }; } throw e; } }