Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

[Authz 5/N]: Implement agent token exchange for turn (#601)

Chirag Jaincb69de944837
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 420eeb30e..90bb22259 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -8232,7 +8232,7 @@
}
}
},
- "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
+ "description": "Unsupported operation because the MCP servers are managed by external system"
}
},
"summary": "Create an MCP server",
@@ -8296,7 +8296,7 @@
}
}
},
- "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
+ "description": "Unsupported operation because the MCP servers are managed by external system"
}
},
"summary": "Create or replace an MCP server",
@@ -8455,7 +8455,7 @@
}
}
},
- "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
+ "description": "Unsupported operation because the model providers are managed by external system"
}
},
"summary": "Create a model provider",
@@ -8509,7 +8509,7 @@
}
}
},
- "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
+ "description": "Unsupported operation because the model providers are managed by external system"
}
},
"summary": "Create or replace a model provider",
diff --git a/docs/openapi.json b/docs/openapi.json
index 420eeb30e..90bb22259 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -8232,7 +8232,7 @@
}
}
},
- "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
+ "description": "Unsupported operation because the MCP servers are managed by external system"
}
},
"summary": "Create an MCP server",
@@ -8296,7 +8296,7 @@
}
}
},
- "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
+ "description": "Unsupported operation because the MCP servers are managed by external system"
}
},
"summary": "Create or replace an MCP server",
@@ -8455,7 +8455,7 @@
}
}
},
- "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
+ "description": "Unsupported operation because the model providers are managed by external system"
}
},
"summary": "Create a model provider",
@@ -8509,7 +8509,7 @@
}
}
},
- "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
+ "description": "Unsupported operation because the model providers are managed by external system"
}
},
"summary": "Create or replace a model provider",
diff --git a/packages/trueforge/.env.example b/packages/trueforge/.env.example
index d9a0fab3d..5b48d8ebc 100644
--- a/packages/trueforge/.env.example
+++ b/packages/trueforge/.env.example
@@ -28,6 +28,8 @@ PORT=8790
## turns call the tenant's default AI Gateway. Unset = local API-key model catalog. Mutually
## exclusive with OIDC.
# TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL=https://servicefoundry-server.truefoundry.svc.cluster.local
+## Required when TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL is set. Used only to vend agent tokens for saved-agent turns.
+# TRUEFOUNDRY_API_KEY=
## Max ms for non-agent ServiceFoundry HTTP calls. Default 10000.
# TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS=10000
## Max ms for ServiceFoundry agent create/update/delete calls. Default 3000.
diff --git a/packages/trueforge/src/apis/schedules.ts b/packages/trueforge/src/apis/schedules.ts
index d89f1b34d..dafd9b0aa 100644
--- a/packages/trueforge/src/apis/schedules.ts
+++ b/packages/trueforge/src/apis/schedules.ts
@@ -7,7 +7,7 @@ import type { Context } from 'hono';
import type { Authorizer } from '../auth/authorizer';
import { createdBySubjectFromRequestContext, type RequestContext, type ResolveRequestContext } from '../auth/identity';
import { ScheduleAgentNotFoundError, startScheduleRun } from '../controller/scheduleDispatch';
-import type { IAgentStore } from '../db/agentStore';
+import type { AgentRecord, IAgentStore } from '../db/agentStore';
import {
manualRunName,
ScheduleNameConflictError,
@@ -41,7 +41,7 @@ export interface SchedulesRouterDeps<TTransaction> {
scheduleStore: IScheduleStore<TTransaction>;
resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
sessions: Sessions;
- resolveTurnDeps: (c: Context) => BeginTurnExecutionDeps;
+ resolveTurnDeps: (c: Context, runAsAgent?: AgentRecord) => BeginTurnExecutionDeps;
withTransaction: WithTransaction<TTransaction>;
resolveRequestContext: ResolveRequestContext;
authorizer: Authorizer;
@@ -223,7 +223,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
sessions: deps.sessions,
agentStore: deps.resolveAgentStore(c),
startTurn: async turnParams => {
- await startTurnInProcess({ ...turnParams, deps: deps.resolveTurnDeps(c) });
+ await startTurnInProcess({ ...turnParams, deps: deps.resolveTurnDeps(c, agent) });
},
});
} catch (error) {
diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.ts
index ef639a792..53599eea3 100644
--- a/packages/trueforge/src/apis/turns.ts
+++ b/packages/trueforge/src/apis/turns.ts
@@ -32,7 +32,7 @@ import type { Logger } from 'winston';
import type { Authorizer } from '../auth/authorizer';
import type { ResolveRequestContext } from '../auth/identity';
import configuration from '../config';
-import type { IAgentStore } from '../db/agentStore';
+import type { AgentRecord, IAgentStore } from '../db/agentStore';
import type { IMcpServerWithAuthStore } from '../db/mcpServerStore';
import type { IModelProviderStore } from '../db/modelProviderStore';
import type { ISandboxProviderStore } from '../db/sandboxProviderStore';
@@ -105,8 +105,8 @@ export interface TurnsRouterDeps {
sessions: Sessions;
sessionStore: ISessionStore;
activeTurns: ActiveTurnRegistry;
- resolveModelProviderStore: (c: Context) => IModelProviderStore;
- resolveMcpServerStore: (c: Context) => IMcpServerWithAuthStore;
+ resolveModelProviderStore: (c: Context, runAsAgent?: AgentRecord) => IModelProviderStore;
+ resolveMcpServerStore: (c: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore;
skillStore: ISkillStore;
resolveAgentStore: (c: Context) => IAgentStore;
/** Resumable live turn-event transport: create-turn writes, subscribe polls. */
@@ -727,6 +727,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
return c.json({ error: { message: FORBIDDEN_CREATE_TURN } }, 403);
}
+ let referencedAgent: AgentRecord | undefined;
if (session.record.agent.type === 'reference') {
const agentId = session.record.agent.id;
const agent = await deps.resolveAgentStore(c).getAgent({
@@ -744,6 +745,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
if (!canUseAgent) {
return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);
}
+ referencedAgent = agent;
}
const turnParams = {
@@ -753,8 +755,8 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
userRef: requestContext.subject.id,
deps: {
...deps,
- modelProviderStore: deps.resolveModelProviderStore(c),
- mcpServerStore: deps.resolveMcpServerStore(c),
+ modelProviderStore: deps.resolveModelProviderStore(c, referencedAgent),
+ mcpServerStore: deps.resolveMcpServerStore(c, referencedAgent),
agentStore: deps.resolveAgentStore(c),
sandboxProviderStore: deps.resolveSandboxProviderStore(c),
},
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index fdc9c2397..2fcc996e5 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -32,7 +32,7 @@ import type { ModelCatalog } from './catalog/ModelCatalog';
import type { SandboxCatalog } from './catalog/SandboxCatalog';
import type { SkillCatalog } from './catalog/SkillCatalog';
import configuration, { getTrueForgeAuthMode, TrueForgeAuthMode } from './config';
-import type { IAgentStore } from './db/agentStore';
+import type { AgentRecord, IAgentStore } from './db/agentStore';
import type { IMcpServerWithAuthStore } from './db/mcpServerStore';
import type { IModelProviderStore } from './db/modelProviderStore';
import type { ISandboxProviderStore } from './db/sandboxProviderStore';
@@ -167,12 +167,12 @@ export interface ServerDeps<TTransaction> {
skillCatalog: SkillCatalog;
sandboxCatalog: SandboxCatalog;
/** Per-request store: DB singleton, or a token-bound TrueFoundry store in TrueFoundry mode. */
- resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
+ resolveModelProviderStore: (c: Context, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction>;
/**
* Per-request store: DB singleton, or a token-bound TrueFoundry store in TrueFoundry mode.
* The unauthenticated OAuth callback has no context and gets the DB persistence store.
*/
- resolveMcpServerStore: (c?: Context) => IMcpServerWithAuthStore<TTransaction>;
+ resolveMcpServerStore: (c?: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore<TTransaction>;
/** Per-request store: DB singleton, or a token-bound TrueFoundry decorator in TrueFoundry mode. */
resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
/**
@@ -319,11 +319,11 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
scheduleStore: deps.scheduleStore,
resolveAgentStore: deps.resolveAgentStore,
sessions: deps.sessions,
- resolveTurnDeps: c => ({
+ resolveTurnDeps: (c, runAsAgent) => ({
activeTurns: deps.activeTurns,
eventSubscriptions: deps.eventSubscriptions,
- modelProviderStore: deps.resolveModelProviderStore(c),
- mcpServerStore: deps.resolveMcpServerStore(c),
+ modelProviderStore: deps.resolveModelProviderStore(c, runAsAgent),
+ mcpServerStore: deps.resolveMcpServerStore(c, runAsAgent),
skillStore: deps.skillStore,
agentStore: deps.resolveAgentStore(c),
sandboxProviderStore: deps.resolveSandboxProviderStore(c),
diff --git a/packages/trueforge/src/auth/createAuthenticator.ts b/packages/trueforge/src/auth/createAuthenticator.ts
index 281198888..2cda9ef58 100644
--- a/packages/trueforge/src/auth/createAuthenticator.ts
+++ b/packages/trueforge/src/auth/createAuthenticator.ts
@@ -1,9 +1,9 @@
import { TrueForgeAuthMode } from '../config';
+import { TrueFoundryAuthenticator } from '../truefoundry/TrueFoundryAuthenticator';
import type { TrueFoundryServiceFoundryServerClient } from '../truefoundry/TrueFoundryServiceFoundryServerClient';
import type { Authenticator } from './authenticator';
import { OidcAuthenticator } from './oidcAuthenticator';
import { StandaloneAuthenticator } from './standaloneAuthenticator';
-import { TrueFoundryAuthenticator } from './trueFoundryAuthenticator';
export type CreateAuthenticatorParams =
| { mode: TrueForgeAuthMode.Standalone }
diff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.ts
index a6eaf2698..52c3679af 100644
--- a/packages/trueforge/src/config.ts
+++ b/packages/trueforge/src/config.ts
@@ -558,6 +558,10 @@ export type DistributedServerConfiguration = SharedServerConfiguration & {
* Env: `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL`.
*/
TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: string | undefined;
+ /**
+ * Required when `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set. Env: `TRUEFOUNDRY_API_KEY`.
+ */
+ TRUEFOUNDRY_API_KEY: string | undefined;
/** Max ms for non-agent ServiceFoundry HTTP calls. Env: `TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS`. Default 10000. */
TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS: number;
/** Max ms for agent CRUD ServiceFoundry HTTP calls. Env: `TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS`. Default 3000. */
@@ -734,6 +738,7 @@ const configuration: ServerConfiguration = standalone
REDIS_URL: resolveRedisUrl(),
OIDC: resolveOIDCConfig(),
TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL', { required: false }),
+ TRUEFOUNDRY_API_KEY: getEnv('TRUEFOUNDRY_API_KEY', { required: false }),
TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS: parsePositiveInt({
envKey: 'TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS',
raw: getEnv('TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS'),
@@ -804,6 +809,10 @@ if (isTrueFoundryModeEnabled(configuration)) {
'TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL (TrueFoundry mode) and OIDC (SSO) cannot both be enabled at once.',
);
}
+ // TRUEFOUNDRY_API_KEY is required when TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL is set.
+ if (configuration.TRUEFOUNDRY_API_KEY === undefined) {
+ throw new Error('TRUEFOUNDRY_API_KEY is required when TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL is set.');
+ }
// Shared sandbox: TRUEFOUNDRY_SANDBOX_ENABLED requires a provider (Daytona today).
if (configuration.TRUEFOUNDRY_SANDBOX_ENABLED) {
if (
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index 3c02dfc4f..cf549f4a8 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -11,7 +11,6 @@
*/
import { extractErrorLogFields } from '@truefoundry/trueforge-core/core';
import type { Context } from 'hono';
-import { HTTPException } from 'hono/http-exception';
import { mkdir } from 'node:fs/promises';
import path from 'node:path';
import {
@@ -66,7 +65,7 @@ import { SandboxCatalog } from './catalog/SandboxCatalog';
import { SkillCatalog } from './catalog/SkillCatalog';
import { type DistributedServerConfiguration } from './config';
import { createController } from './controller';
-import type { IAgentStore } from './db/agentStore';
+import type { AgentRecord, IAgentStore } from './db/agentStore';
import type { IMcpServerStore, IMcpServerWithAuthStore } from './db/mcpServerStore';
import { McpServerWithAuthStore } from './db/McpServerWithAuthStore';
import type { IModelProviderStore } from './db/modelProviderStore';
@@ -98,8 +97,8 @@ import { TrueFoundryServiceFoundryServerClient } from './truefoundry/TrueFoundry
interface ServerPersistence<TTransaction> {
sessionStore: ISessionStore;
sessionMetricsStore: ISessionMetricsStore;
- resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
- resolveMcpServerStore: (c?: Context) => IMcpServerWithAuthStore<TTransaction>;
+ resolveModelProviderStore: (c: Context, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction>;
+ resolveMcpServerStore: (c?: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore<TTransaction>;
resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
resolveSandboxProviderStore: (c: Context) => ISandboxProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
@@ -112,41 +111,43 @@ interface ServerPersistence<TTransaction> {
serviceFoundryClient: TrueFoundryServiceFoundryServerClient | undefined;
}
-function requireRequestCredentialToken(c: Context): string {
- const credential = resolveRequestContext(c).user_credential;
- if (credential === null) {
- throw new HTTPException(401, {
- message: 'Authentication token required to list or call TrueFoundry models, MCP servers, agents, and sandbox',
- });
- }
- return credential;
-}
-
/** Shared ServiceFoundry HTTP client when TrueFoundry mode is on; otherwise undefined. */
function createServiceFoundryServerClient(logger: Logger): TrueFoundryServiceFoundryServerClient | undefined {
if (!isTrueFoundryModeEnabled(configuration)) {
return undefined;
}
+ const apiKey = configuration.TRUEFOUNDRY_API_KEY;
+ if (apiKey === undefined) {
+ // this is unreachable because the config validation fails if TRUEFOUNDRY_API_KEY is not set
+ // we will refactor config itself later to have a truefoundry section where this will be required
+ throw new Error('TRUEFOUNDRY_API_KEY is required when TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL is set.');
+ }
return new TrueFoundryServiceFoundryServerClient({
serviceFoundryServerUrl: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL,
logger,
httpTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS,
httpAgentTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS,
tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },
+ apiKey,
});
}
-/** Per-request model-provider store over a shared ServiceFoundry client, else {@link persistenceStore}. */
+/**
+ * Per-request model-provider store over a shared ServiceFoundry client, else {@link persistenceStore}.
+ * `runAsAgent` is set only when a turn should use a saved agent's token.
+ */
function buildResolveModelProviderStore<TTransaction>(options: {
persistenceStore: IModelProviderStore<TTransaction>;
client: TrueFoundryServiceFoundryServerClient | undefined;
-}): (c: Context) => IModelProviderStore<TTransaction> {
- return (c: Context) => {
+}): (c: Context, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction> {
+ return (c: Context, runAsAgent?: AgentRecord) => {
const { persistenceStore, client } = options;
if (client) {
+ const requestContext = resolveRequestContext(c);
return new TrueFoundryModelProviderStore<TTransaction>({
client,
- accessToken: requireRequestCredentialToken(c),
+ context: requestContext,
+ agent: runAsAgent,
});
}
return persistenceStore;
@@ -155,22 +156,22 @@ function buildResolveModelProviderStore<TTransaction>(options: {
/**
* Per-request MCP store over ServiceFoundry. Without request context (scheduler / OAuth callback)
- * falls back to the local with-auth store.
+ * falls back to the local with-auth store. `runAsAgent` selects a saved agent's token for turns.
*/
function buildResolveMcpServerStore<TTransaction>(options: {
persistenceStore: IMcpServerStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
client: TrueFoundryServiceFoundryServerClient | undefined;
-}): (c?: Context) => IMcpServerWithAuthStore<TTransaction> {
- return (c?: Context) => {
+}): (c?: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore<TTransaction> {
+ return (c?: Context, runAsAgent?: AgentRecord) => {
const { persistenceStore, tokenStore, client } = options;
if (c && client) {
const requestContext = resolveRequestContext(c);
const rawPerServerHeaders = c.req.header(X_TFG_MCP_HEADERS);
return new TrueFoundryMcpServerStore<TTransaction>({
client,
- accessToken: requireRequestCredentialToken(c),
- subject: requestContext.subject,
+ context: requestContext,
+ agent: runAsAgent,
perServerHeaders: rawPerServerHeaders ? parsePerServerMcpHeaders(rawPerServerHeaders) : {},
});
}
@@ -195,7 +196,7 @@ function buildResolveAgentStore(options: {
return new TrueFoundryAgentStore({
inner: persistenceStore,
client,
- accessToken: requireRequestCredentialToken(c),
+ context: resolveRequestContext(c),
db,
});
}
@@ -216,7 +217,7 @@ function buildResolveSandboxProviderStore<TTransaction>(options: {
}
return c =>
new TrueFoundrySandboxProviderStore<TTransaction>({
- accessToken: requireRequestCredentialToken(c),
+ context: resolveRequestContext(c),
});
}
@@ -343,26 +344,30 @@ async function createDistributedPersistence(options: {
const modelProviderStore = new PostgresModelProviderStore(db);
const mcpServerStore = new PostgresMcpServerStore(db);
const serviceFoundryClient = createServiceFoundryServerClient(logger);
+ const resolveModelProviderStore = buildResolveModelProviderStore({
+ persistenceStore: modelProviderStore,
+ client: serviceFoundryClient,
+ });
+ const resolveMcpServerStore = buildResolveMcpServerStore({
+ persistenceStore: mcpServerStore,
+ tokenStore,
+ client: serviceFoundryClient,
+ });
+ const resolveAgentStore = buildResolveAgentStore({
+ persistenceStore: agentStore,
+ db,
+ client: serviceFoundryClient,
+ });
+ const resolveSandboxProviderStore = buildResolveSandboxProviderStore({
+ persistenceStore: new PostgresSandboxProviderStore(db),
+ });
return {
sessionStore: new PostgresSessionStore(db),
sessionMetricsStore: new PostgresSessionMetricsStore(db),
- resolveModelProviderStore: buildResolveModelProviderStore({
- persistenceStore: modelProviderStore,
- client: serviceFoundryClient,
- }),
- resolveMcpServerStore: buildResolveMcpServerStore({
- persistenceStore: mcpServerStore,
- tokenStore,
- client: serviceFoundryClient,
- }),
- resolveAgentStore: buildResolveAgentStore({
- persistenceStore: agentStore,
- db,
- client: serviceFoundryClient,
- }),
- resolveSandboxProviderStore: buildResolveSandboxProviderStore({
- persistenceStore: new PostgresSandboxProviderStore(db),
- }),
+ resolveModelProviderStore,
+ resolveMcpServerStore,
+ resolveAgentStore,
+ resolveSandboxProviderStore,
withTransaction: callback => db.transaction().execute(callback),
tokenStore,
skillStore: new PostgresSkillStore(db),
diff --git a/packages/trueforge/src/routes/mcpServerRoutes.ts b/packages/trueforge/src/routes/mcpServerRoutes.ts
index bcc486a9a..a03a0a9d2 100644
--- a/packages/trueforge/src/routes/mcpServerRoutes.ts
+++ b/packages/trueforge/src/routes/mcpServerRoutes.ts
@@ -9,7 +9,6 @@ import {
McpAuthStatusSchema,
UpdateMcpServerRequestSchema,
} from '../schemas/mcpServer';
-import { trueFoundryManagedResponse } from '../truefoundry/trueFoundryManaged';
import { TOKEN_PAGINATION } from './fernExtensions';
import { OpenApiTag } from './openapiTags';
@@ -149,7 +148,10 @@ export const createMcpServerRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint).',
},
- 424: trueFoundryManagedResponse,
+ 424: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Unsupported operation because the MCP servers are managed by external system',
+ },
},
});
@@ -181,7 +183,10 @@ export const putMcpServerRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint).',
},
- 424: trueFoundryManagedResponse,
+ 424: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Unsupported operation because the MCP servers are managed by external system',
+ },
},
});
diff --git a/packages/trueforge/src/routes/modelProviderRoutes.ts b/packages/trueforge/src/routes/modelProviderRoutes.ts
index 132208e1d..c0b8058a4 100644
--- a/packages/trueforge/src/routes/modelProviderRoutes.ts
+++ b/packages/trueforge/src/routes/modelProviderRoutes.ts
@@ -11,7 +11,6 @@ import {
ListModelProvidersResponseSchema,
UpdateModelProviderRequestSchema,
} from '../schemas/modelProvider';
-import { trueFoundryManagedResponse } from '../truefoundry/trueFoundryManaged';
import { OpenApiTag } from './openapiTags';
export const listModelProvidersRoute = createRoute({
@@ -67,7 +66,10 @@ export const createModelProviderRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'A model provider with this name already exists.',
},
- 424: trueFoundryManagedResponse,
+ 424: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Unsupported operation because the model providers are managed by external system',
+ },
},
});
@@ -96,6 +98,9 @@ export const putModelProviderRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Invalid request body, or redacted API key with no stored secret to keep.',
},
- 424: trueFoundryManagedResponse,
+ 424: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Unsupported operation because the model providers are managed by external system',
+ },
},
});
diff --git a/packages/trueforge/src/sandbox/localRuntime.ts b/packages/trueforge/src/sandbox/localRuntime.ts
index 598d544fa..f4cb1816f 100644
--- a/packages/trueforge/src/sandbox/localRuntime.ts
+++ b/packages/trueforge/src/sandbox/localRuntime.ts
@@ -2,7 +2,7 @@
* Process-scoped local-sandbox probe cache. `isSupported()` inits SRT and
* creates a temp sandbox — run once at standalone boot, never per request.
*/
-import configuration, { isTrueFoundryModeEnabled } from '../config';
+import configuration from '../config';
import type { LocalSandboxSupportResult } from './local/provider/LocalSandboxProvider';
let cachedSupport: LocalSandboxSupportResult | undefined;
@@ -17,8 +17,5 @@ export function getCachedLocalSandboxSupport(): LocalSandboxSupportResult | unde
/** Standalone + cached probe succeeded. No DB row required. Never in TrueFoundry mode. */
export function isLocalSandboxFallbackEnabled(): boolean {
- if (isTrueFoundryModeEnabled(configuration)) {
- return false;
- }
return configuration.STANDALONE && cachedSupport?.supported === true;
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts
index 468ab7d07..c20266f8a 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts
@@ -1,5 +1,6 @@
import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';
import { sql, type Kysely, type Transaction } from 'kysely';
+import type { RequestContext } from '../auth/identity';
import {
type AgentRecord,
type CreateAgentInput,
@@ -11,6 +12,7 @@ import {
} from '../db/agentStore';
import { PostgresAgentStore } from '../db/postgres/agent-store/PostgresAgentStore';
import type { Database } from '../db/postgres/types';
+import { callerAccessToken, type ResolveAccessToken } from './accessToken';
import {
TrueFoundryServiceFoundryServerClient,
type PutRemoteAgentInput,
@@ -66,18 +68,18 @@ function toPutRemoteAgentPayload({
export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>> {
readonly #inner: PostgresAgentStore;
readonly #client: TrueFoundryServiceFoundryServerClient;
- readonly #accessToken: string;
+ readonly #resolveAccessToken: ResolveAccessToken;
readonly #db: Kysely<Database>;
constructor(input: {
inner: PostgresAgentStore;
client: TrueFoundryServiceFoundryServerClient;
- accessToken: string;
+ context: RequestContext;
db: Kysely<Database>;
}) {
this.#inner = input.inner;
this.#client = input.client;
- this.#accessToken = input.accessToken;
+ this.#resolveAccessToken = callerAccessToken(input.context);
this.#db = input.db;
}
@@ -114,7 +116,7 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>
let externalId: string | undefined;
try {
({ externalId } = await this.#client.putRemoteAgent({
- accessToken: this.#accessToken,
+ accessToken: await this.#resolveAccessToken(),
...toPutRemoteAgentPayload({ name: input.name, manifest: input.manifest }),
}));
const updated = await this.#inner.updateAgent(
@@ -129,7 +131,7 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>
const failures = [asError(error)];
if (externalId !== undefined) {
try {
- await this.#client.deleteRemoteAgent({ accessToken: this.#accessToken, externalId });
+ await this.#client.deleteRemoteAgent({ accessToken: await this.#resolveAccessToken(), externalId });
} catch (cleanupError) {
failures.push(asError(cleanupError));
}
@@ -160,7 +162,7 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>
}
const { externalId } = await this.#client.putRemoteAgent({
- accessToken: this.#accessToken,
+ accessToken: await this.#resolveAccessToken(),
...toPutRemoteAgentPayload({ name: previous.name, manifest: nextManifest }),
});
@@ -177,7 +179,7 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>
} catch (error) {
try {
await this.#client.putRemoteAgent({
- accessToken: this.#accessToken,
+ accessToken: await this.#resolveAccessToken(),
...toPutRemoteAgentPayload({ name: previous.name, manifest: previous.manifest }),
});
} catch (restoreError) {
@@ -197,7 +199,7 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>
const previous = await this.#inner.getAgent({ tenant_id: input.tenant_id, id: input.id }, txn);
if (previous?.external_id) {
await this.#client.deleteRemoteAgent({
- accessToken: this.#accessToken,
+ accessToken: await this.#resolveAccessToken(),
externalId: previous.external_id,
});
}
diff --git a/packages/trueforge/src/auth/trueFoundryAuthenticator.ts b/packages/trueforge/src/truefoundry/TrueFoundryAuthenticator.ts
similarity index 74%
rename from packages/trueforge/src/auth/trueFoundryAuthenticator.ts
rename to packages/trueforge/src/truefoundry/TrueFoundryAuthenticator.ts
index 5eb674bd1..7ae4e7fca 100644
--- a/packages/trueforge/src/auth/trueFoundryAuthenticator.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryAuthenticator.ts
@@ -1,10 +1,11 @@
import type { Context } from 'hono';
import { HTTPException } from 'hono/http-exception';
-import type { GetSessionResponse } from '../truefoundry/TrueFoundryServiceFoundryServerClient';
-import type { Authenticator } from './authenticator';
-import type { RequestContext } from './identity';
-import { extractRequestToken } from './token';
+import type { Authenticator } from '../auth/authenticator';
+import type { RequestContext } from '../auth/identity';
+import { extractRequestToken } from '../auth/token';
+import { createTrueFoundryRequestContext } from './accessToken';
+import type { GetSessionResponse } from './TrueFoundryServiceFoundryServerClient';
/** Narrow port used by the authenticator (avoids depending on the full SFY client). */
export interface TrueFoundrySessionClient {
@@ -26,7 +27,7 @@ export class TrueFoundryAuthenticator implements Authenticator {
const session = await this.#client.getSession(token);
const { subject } = session.user;
- return {
+ return createTrueFoundryRequestContext({
tenant_id: session.user.tenantName,
subject: {
id: subject.subjectId,
@@ -35,6 +36,6 @@ export class TrueFoundryAuthenticator implements Authenticator {
},
roles: session.user.roles,
user_credential: token,
- };
+ });
}
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
index 6b4e1afd3..11aa0fbe6 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
@@ -5,9 +5,10 @@ import {
} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';
import { McpConnectionError, type RemoteMcpHeaders } from '@truefoundry/trueforge-core/core';
import { HTTPException } from 'hono/http-exception';
-import type { RequestSubject } from '../auth/identity';
+import type { RequestContext, RequestSubject } from '../auth/identity';
import { safeReturnTo } from '../auth/safeReturnTo';
import { getPublicBaseUrl } from '../config';
+import type { AgentRecord } from '../db/agentStore';
import {
McpServerNotFoundError,
type AuthorizeMcpServerInput,
@@ -22,6 +23,8 @@ import {
} from '../db/mcpServerStore';
import type { OAuthClientRecord } from '../mcp/auth/types';
import { resolveMcpAuthStatus, type McpAuthStatus } from '../schemas/mcpServer';
+import { accessTokenForRequest, asTrueFoundryRequestContext, type ResolveAccessToken } from './accessToken';
+import { trueFoundryManaged } from './errors';
import { resolveDefaultGatewayUrl } from './mapEnabledModels';
import {
mapSfyMcpServers,
@@ -30,7 +33,6 @@ import {
type SfyMcpServerSummary,
} from './mapSfyMcpServers';
import type { PerServerMcpHeaders } from './perServerMcpHeaders';
-import { TRUEFOUNDRY_MANAGED_MESSAGE, TRUEFOUNDRY_MANAGED_STATUS } from './trueFoundryManaged';
import type { TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';
export type TrueFoundryMcpApiClient = Pick<
@@ -41,12 +43,9 @@ export type TrueFoundryMcpApiClient = Pick<
| 'getMcpAuthorize'
| 'getMcpAuthStatus'
| 'deleteMcpAuth'
+ | 'vendToken'
>;
-function managed(): never {
- throw new HTTPException(TRUEFOUNDRY_MANAGED_STATUS, { message: TRUEFOUNDRY_MANAGED_MESSAGE });
-}
-
function withoutAuthorization(headers: Record<string, string> | undefined): Record<string, string> {
if (headers === undefined) {
return {};
@@ -68,30 +67,34 @@ export function resolveAuthorizeRedirectURL(input: { returnTo?: string }): strin
/** Read-only MCP registry for TrueFoundry mode (writes managed elsewhere). */
export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServerWithAuthStore<TTransaction> {
readonly #client: TrueFoundryMcpApiClient;
- readonly #accessToken: string;
+ readonly #resolveAccessToken: ResolveAccessToken;
readonly #subject: RequestSubject;
readonly #perServerHeaders: PerServerMcpHeaders;
#gatewayUrl: string | undefined;
constructor(input: {
client: TrueFoundryMcpApiClient;
- accessToken: string;
- subject: RequestSubject;
+ context: RequestContext;
+ agent: AgentRecord | undefined;
perServerHeaders?: PerServerMcpHeaders;
}) {
this.#client = input.client;
- this.#accessToken = input.accessToken;
- this.#subject = input.subject;
+ this.#resolveAccessToken = accessTokenForRequest({
+ client: input.client,
+ context: asTrueFoundryRequestContext(input.context),
+ agent: input.agent,
+ });
+ this.#subject = input.context.subject;
this.#perServerHeaders = input.perServerHeaders ?? {};
}
- /** Caller Bearer plus optional per-server overrides; oauth servers re-check auth before invoke. */
+ /** Bearer resolved at connect time plus optional per-server overrides; oauth servers re-check auth first. */
resolveInvokeHeaders(input: { record: McpServerRecord; userRef: string }): RemoteMcpHeaders {
const { record, userRef } = input;
- const staticHeaders = {
+ const headers = async (): Promise<Record<string, string>> => ({
...withoutAuthorization(this.#perServerHeaders[record.name]),
- Authorization: `Bearer ${this.#accessToken}`,
- };
+ Authorization: `Bearer ${await this.#resolveAccessToken()}`,
+ });
if (record.manifest.auth?.type === 'dcr') {
return async () => {
const status = await this.authorize({
@@ -112,10 +115,10 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
},
};
}
- return { headers: staticHeaders };
+ return { headers: await headers() };
};
}
- return staticHeaders;
+ return async () => ({ headers: await headers() });
}
async listServers(
@@ -128,9 +131,10 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
return paginateOffsetRows([], input.limit, offset);
}
+ const accessToken = await this.#resolveAccessToken();
const [rows, gatewayUrl] = await Promise.all([
this.#client.listMcpServers({
- accessToken: this.#accessToken,
+ accessToken,
limit: input.limit + 1,
offset,
...(input.names !== undefined ? { names: input.names } : {}),
@@ -145,8 +149,9 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
async getServer(input: GetMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord | undefined> {
void transaction;
+ const accessToken = await this.#resolveAccessToken();
const [row, gatewayUrl] = await Promise.all([
- this.#client.getMcpServerByName({ accessToken: this.#accessToken, name: input.name }),
+ this.#client.getMcpServerByName({ accessToken, name: input.name }),
this.#resolveGatewayUrl(),
]);
if (row === undefined) {
@@ -159,37 +164,37 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
getServerForUpdate(input: GetMcpServerInput, transaction: TTransaction): Promise<McpServerRecord | undefined> {
void input;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
createServer(input: CreateMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord> {
void input;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
upsertServer(input: UpsertMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord> {
void input;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
saveClient(params: { id: string; record: OAuthClientRecord }, transaction?: TTransaction): Promise<void> {
void params;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
getClient(params: { id: string }, transaction?: TTransaction): Promise<OAuthClientRecord | undefined> {
void params;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
deleteClient(params: { id: string }, transaction?: TTransaction): Promise<void> {
void params;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
async resolveAuthStatuses(input: ResolveMcpAuthStatusesInput): Promise<ReadonlyMap<string, McpAuthStatus>> {
@@ -208,7 +213,7 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
out.set(
record.name,
await this.#client.getMcpAuthStatus({
- accessToken: this.#accessToken,
+ accessToken: await this.#resolveAccessToken(),
mcpServerId: record.id,
subjectId: this.#subject.id,
subjectType: this.#subject.type,
@@ -228,7 +233,7 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
throw new McpServerNotFoundError(input.name);
}
return this.#client.getMcpAuthorize({
- accessToken: this.#accessToken,
+ accessToken: await this.#resolveAccessToken(),
mcpServerId: record.id,
redirectURL: resolveAuthorizeRedirectURL({
...(input.returnTo !== undefined ? { returnTo: input.returnTo } : {}),
@@ -243,7 +248,7 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
throw new McpServerNotFoundError(input.name);
}
await this.#client.deleteMcpAuth({
- accessToken: this.#accessToken,
+ accessToken: await this.#resolveAccessToken(),
mcpServerId: record.id,
subjectId: this.#subject.id,
subjectType: this.#subject.type,
@@ -253,7 +258,8 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
async #resolveGatewayUrl(): Promise<string> {
if (this.#gatewayUrl === undefined) {
- this.#gatewayUrl = resolveDefaultGatewayUrl(await this.#client.listGatewayInstallations(this.#accessToken));
+ const installations = await this.#client.listGatewayInstallations(await this.#resolveAccessToken());
+ this.#gatewayUrl = resolveDefaultGatewayUrl(installations);
}
return this.#gatewayUrl;
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryModelProviderStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryModelProviderStore.ts
index d9319ce59..fbd7e5552 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryModelProviderStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryModelProviderStore.ts
@@ -1,4 +1,5 @@
-import { HTTPException } from 'hono/http-exception';
+import type { RequestContext } from '../auth/identity';
+import type { AgentRecord } from '../db/agentStore';
import {
flattenProviderModels,
type CreateModelProviderInput,
@@ -9,21 +10,26 @@ import {
type UpsertModelProviderInput,
} from '../db/modelProviderStore';
import type { AvailableModel, ModelProviderManifest } from '../schemas/modelProvider';
+import { accessTokenForRequest, asTrueFoundryRequestContext, type ResolveAccessToken } from './accessToken';
+import { trueFoundryManaged } from './errors';
import { mapEnabledModels, resolveDefaultGatewayUrl, type TrueFoundryEnabledModel } from './mapEnabledModels';
-import { TRUEFOUNDRY_MANAGED_MESSAGE, TRUEFOUNDRY_MANAGED_STATUS } from './trueFoundryManaged';
import { TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';
-function managed(): never {
- throw new HTTPException(TRUEFOUNDRY_MANAGED_STATUS, { message: TRUEFOUNDRY_MANAGED_MESSAGE });
-}
-
export class TrueFoundryModelProviderStore<TTransaction = never> implements IModelProviderStore<TTransaction> {
readonly #client: TrueFoundryServiceFoundryServerClient;
- readonly #accessToken: string;
+ readonly #resolveAccessToken: ResolveAccessToken;
- constructor(input: { client: TrueFoundryServiceFoundryServerClient; accessToken: string }) {
+ constructor(input: {
+ client: TrueFoundryServiceFoundryServerClient;
+ context: RequestContext;
+ agent: AgentRecord | undefined;
+ }) {
this.#client = input.client;
- this.#accessToken = input.accessToken;
+ this.#resolveAccessToken = accessTokenForRequest({
+ client: input.client,
+ context: asTrueFoundryRequestContext(input.context),
+ agent: input.agent,
+ });
}
async listProviders(input: ListModelProvidersInput, transaction?: TTransaction): Promise<ModelProviderRecord[]> {
@@ -46,19 +52,19 @@ export class TrueFoundryModelProviderStore<TTransaction = never> implements IMod
): Promise<ModelProviderRecord | undefined> {
void input;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
createProvider(input: CreateModelProviderInput, transaction?: TTransaction): Promise<ModelProviderRecord> {
void input;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
upsertProvider(input: UpsertModelProviderInput, transaction?: TTransaction): Promise<ModelProviderRecord> {
void input;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
async listModels(input: ListModelProvidersInput, transaction?: TTransaction): Promise<AvailableModel[]> {
@@ -66,15 +72,16 @@ export class TrueFoundryModelProviderStore<TTransaction = never> implements IMod
}
async #records(input: { tenant_id: string }): Promise<ModelProviderRecord[]> {
+ const accessToken = await this.#resolveAccessToken();
const [integrations, installations] = await Promise.all([
- this.#client.listProviderIntegrations(this.#accessToken),
- this.#client.listGatewayInstallations(this.#accessToken),
+ this.#client.listProviderIntegrations(accessToken),
+ this.#client.listGatewayInstallations(accessToken),
]);
const gatewayUrl = resolveDefaultGatewayUrl(installations);
return toRecords({
tenant_id: input.tenant_id,
gatewayUrl,
- accessToken: this.#accessToken,
+ accessToken,
models: mapEnabledModels({ integrations }),
});
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundrySandboxProviderStore.ts b/packages/trueforge/src/truefoundry/TrueFoundrySandboxProviderStore.ts
index cbd09d91d..3e0ad1381 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundrySandboxProviderStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundrySandboxProviderStore.ts
@@ -1,14 +1,15 @@
-import { HTTPException } from 'hono/http-exception';
import { LRUCache } from 'lru-cache';
import { z } from 'zod';
+import type { RequestContext } from '../auth/identity';
import type {
ISandboxProviderStore,
SandboxProviderRecord,
UpdateSandboxStatusInput,
UpsertSandboxProviderInput,
} from '../db/sandboxProviderStore';
+import { callerAccessToken, type ResolveAccessToken } from './accessToken';
+import { trueFoundryManaged } from './errors';
import { resolveTrueFoundrySandboxProviderConfig } from './resolveTrueFoundrySandboxProviderConfig';
-import { TRUEFOUNDRY_MANAGED_MESSAGE, TRUEFOUNDRY_MANAGED_STATUS } from './trueFoundryManaged';
const SETTINGS_CACHE_TTL_MS = 5 * 60 * 1000;
const SETTINGS_FETCH_TIMEOUT_MS = 10_000;
@@ -74,15 +75,11 @@ async function resolveDaytonaSandboxSettings({
return settings;
}
-function managed(): never {
- throw new HTTPException(TRUEFOUNDRY_MANAGED_STATUS, { message: TRUEFOUNDRY_MANAGED_MESSAGE });
-}
-
export class TrueFoundrySandboxProviderStore<TTransaction = never> implements ISandboxProviderStore<TTransaction> {
- readonly #accessToken: string;
+ readonly #resolveAccessToken: ResolveAccessToken;
- constructor(input: { accessToken: string }) {
- this.#accessToken = input.accessToken;
+ constructor(input: { context: RequestContext }) {
+ this.#resolveAccessToken = callerAccessToken(input.context);
}
async getSandboxProvider(tenantId: string, transaction?: TTransaction): Promise<SandboxProviderRecord | undefined> {
@@ -92,7 +89,7 @@ export class TrueFoundrySandboxProviderStore<TTransaction = never> implements IS
return undefined;
}
const settings = await resolveDaytonaSandboxSettings({
- accessToken: this.#accessToken,
+ accessToken: await this.#resolveAccessToken(),
settingsServerUrl: providerConfig.settingsServerUrl,
});
const now = new Date().toISOString();
@@ -119,13 +116,13 @@ export class TrueFoundrySandboxProviderStore<TTransaction = never> implements IS
getSandboxProviderForUpdate(tenantId: string, transaction: TTransaction): Promise<SandboxProviderRecord | undefined> {
void tenantId;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
upsertSandboxProvider(input: UpsertSandboxProviderInput, transaction?: TTransaction): Promise<SandboxProviderRecord> {
void input;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
updateSandboxStatus(
@@ -134,6 +131,6 @@ export class TrueFoundrySandboxProviderStore<TTransaction = never> implements IS
): Promise<SandboxProviderRecord | undefined> {
void input;
void transaction;
- return managed();
+ return trueFoundryManaged();
}
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
index 2b92945b0..aa3b8d3b7 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
@@ -14,6 +14,8 @@ const MCP_SERVERS_PATH = 'v1/mcp';
const TFG_AGENTS_PATH = 'internal/tfg/agents';
const SESSION_PATH = 'v1/session';
const AGENT_PERMISSIONS_PATH = 'v1/authorize/permissions';
+/** In-cluster ServiceFoundry path; public gateway is `/api/svc/v1/x/vend-token`. */
+const VEND_TOKEN_PATH = 'v1/x/vend-token';
const INTEGRATIONS_PAGE_SIZE = 1000;
/**
@@ -77,6 +79,10 @@ const AgentPermissionsSchema = z.record(
);
export type AgentPermissions = z.infer<typeof AgentPermissionsSchema>;
+const VendTokenResponseSchema = z.object({
+ token: z.string().min(1),
+});
+
export interface PutRemoteAgentInput {
accessToken: string;
name: string;
@@ -117,6 +123,7 @@ export class TrueFoundryServiceFoundryServerClient {
readonly #dispatcher: Dispatcher | undefined;
readonly #httpTimeoutMs: number;
readonly #httpAgentTimeoutMs: number;
+ readonly #apiKey: string;
constructor(input: {
serviceFoundryServerUrl: string;
@@ -124,6 +131,8 @@ export class TrueFoundryServiceFoundryServerClient {
tls: InternalTlsOptions;
httpTimeoutMs: number;
httpAgentTimeoutMs: number;
+ /** Service API key for `vend-token` only; user calls still pass a bearer `accessToken`. */
+ apiKey: string;
}) {
const tls = input.tls;
this.#baseUrl = normalizeInternalTlsUrl({ url: input.serviceFoundryServerUrl, enabled: tls.enabled }).replace(
@@ -134,6 +143,7 @@ export class TrueFoundryServiceFoundryServerClient {
this.#logger = input.logger;
this.#httpTimeoutMs = input.httpTimeoutMs;
this.#httpAgentTimeoutMs = input.httpAgentTimeoutMs;
+ this.#apiKey = input.apiKey;
}
async listProviderIntegrations(accessToken: string): Promise<unknown[]> {
@@ -397,6 +407,40 @@ export class TrueFoundryServiceFoundryServerClient {
return parsed.data;
}
+ /**
+ * Exchange a TrueFoundry API key for an agent-scoped token.
+ * Authenticated with the server API key, not the user bearer.
+ */
+ async vendToken(input: {
+ subject: { id: string; type: string; display_name: string };
+ agentId: string;
+ tenantName: string;
+ }): Promise<string> {
+ const payload = await this.#requestJson({
+ url: this.#url(VEND_TOKEN_PATH),
+ accessToken: this.#apiKey,
+ method: 'POST',
+ body: {
+ identity: {
+ tenantName: input.tenantName,
+ subject: { id: input.subject.id, type: input.subject.type },
+ actor: { id: input.agentId, type: 'agent' },
+ },
+ },
+ });
+ const parsed = VendTokenResponseSchema.safeParse(payload);
+ if (!parsed.success) {
+ this.#logger.error('TrueFoundry ServiceFoundry vend-token response was malformed', {
+ ...extractErrorLogFields(parsed.error),
+ });
+ throw new HTTPException(424, {
+ message: 'TrueFoundry ServiceFoundry vend-token response was malformed',
+ cause: parsed.error,
+ });
+ }
+ return parsed.data.token;
+ }
+
#parseListResponse(payload: unknown): ListResponse {
const parsed = ListResponseSchema.safeParse(payload);
if (!parsed.success) {
@@ -473,8 +517,9 @@ export class TrueFoundryServiceFoundryServerClient {
durationMs: Date.now() - startedAt,
});
if (response.status === 401 || response.status === 403) {
+ const detail = await readServiceFoundryErrorMessage(response);
throw new HTTPException(response.status, {
- message: 'TrueFoundry ServiceFoundry server rejected the request',
+ message: `TrueFoundry ServiceFoundry server rejected the request: ${detail ?? `HTTP ${String(response.status)}`}`,
});
}
if (response.status === 404 && input.notFoundOk) {
diff --git a/packages/trueforge/src/truefoundry/accessToken.ts b/packages/trueforge/src/truefoundry/accessToken.ts
new file mode 100644
index 000000000..7add9bca6
--- /dev/null
+++ b/packages/trueforge/src/truefoundry/accessToken.ts
@@ -0,0 +1,96 @@
+import { HTTPException } from 'hono/http-exception';
+import type { RequestContext } from '../auth/identity';
+import type { AgentRecord } from '../db/agentStore';
+import { requireTrueFoundryAgentExternalId } from './errors';
+import type { TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';
+
+/**
+ * Token for one TrueFoundry call. Resolved on first use and reused for later calls on the same
+ * callable.
+ */
+export type ResolveAccessToken = () => Promise<string>;
+
+type AgentTokenVendor = Pick<TrueFoundryServiceFoundryServerClient, 'vendToken'>;
+
+/** Per-request map of saved-agent vends; not exported so only this module can read it. */
+const accessTokenCache: unique symbol = Symbol('truefoundryAccessTokenCache');
+
+/**
+ * Request context produced only in TrueFoundry auth. The cache lives on this object for the
+ * lifetime of one HTTP request; a later request gets a new context and vends again.
+ */
+export type TrueFoundryRequestContext = RequestContext & {
+ readonly [accessTokenCache]: Map<string, ResolveAccessToken>;
+};
+
+export function createTrueFoundryRequestContext(base: RequestContext): TrueFoundryRequestContext {
+ return { ...base, [accessTokenCache]: new Map() };
+}
+
+function isTrueFoundryRequestContext(context: RequestContext): context is TrueFoundryRequestContext {
+ return accessTokenCache in context;
+}
+
+export function asTrueFoundryRequestContext(context: RequestContext): TrueFoundryRequestContext {
+ if (!isTrueFoundryRequestContext(context)) {
+ throw new Error('TrueFoundry request context required for access token resolution');
+ }
+ return context;
+}
+
+/**
+ * Token scoped to a saved agent, for work the agent does on the caller's behalf.
+ * Throws 500 up front when the agent was never registered with TrueFoundry.
+ */
+export function agentAccessToken(input: {
+ client: AgentTokenVendor;
+ context: RequestContext;
+ agent: AgentRecord;
+}): ResolveAccessToken {
+ const { client, context } = input;
+ const agentId = requireTrueFoundryAgentExternalId(input.agent);
+ let pending: Promise<string> | undefined;
+ return () => {
+ pending ??= client
+ .vendToken({ subject: context.subject, agentId, tenantName: context.tenant_id })
+ .catch((error: unknown) => {
+ pending = undefined;
+ throw error;
+ });
+ return pending;
+ };
+}
+
+/** Token of whoever made the request. */
+export function callerAccessToken(context: RequestContext): ResolveAccessToken {
+ if (context.user_credential === null) {
+ throw new HTTPException(401, {
+ message: 'Authentication token required to list or call TrueFoundry models, MCP servers, and agents',
+ });
+ }
+ const token = context.user_credential;
+ return () => Promise.resolve(token);
+}
+
+/**
+ * Token for a TrueFoundry request, optionally scoped to the saved agent executing a turn.
+ * Saved-agent callables are stored on this request's context so model and MCP stores share one vend.
+ */
+export function accessTokenForRequest(input: {
+ client: AgentTokenVendor;
+ context: TrueFoundryRequestContext;
+ agent: AgentRecord | undefined;
+}): ResolveAccessToken {
+ if (input.agent === undefined) {
+ return callerAccessToken(input.context);
+ }
+ const agentId = requireTrueFoundryAgentExternalId(input.agent);
+ const cache = input.context[accessTokenCache];
+ const existing = cache.get(agentId);
+ if (existing !== undefined) {
+ return existing;
+ }
+ const resolve = agentAccessToken({ client: input.client, context: input.context, agent: input.agent });
+ cache.set(agentId, resolve);
+ return resolve;
+}
diff --git a/packages/trueforge/src/truefoundry/errors.ts b/packages/trueforge/src/truefoundry/errors.ts
new file mode 100644
index 000000000..4a4e5fdde
--- /dev/null
+++ b/packages/trueforge/src/truefoundry/errors.ts
@@ -0,0 +1,19 @@
+import { HTTPException } from 'hono/http-exception';
+import type { AgentRecord } from '../db/agentStore';
+
+export const AGENT_EXTERNAL_ID_REQUIRED = 'Agent is missing a TrueFoundry external id';
+export const TRUEFOUNDRY_MANAGED_STATUS = 424 as const;
+export const TRUEFOUNDRY_MANAGED_MESSAGE = 'This resource is managed by TrueFoundry';
+
+/** Require the remote identity needed for TrueFoundry agent operations. */
+export function requireTrueFoundryAgentExternalId(agent: Pick<AgentRecord, 'external_id'>): string {
+ if (agent.external_id === null) {
+ throw new HTTPException(500, { message: AGENT_EXTERNAL_ID_REQUIRED });
+ }
+ return agent.external_id;
+}
+
+/** Reject writes to resources whose lifecycle is owned by TrueFoundry. */
+export function trueFoundryManaged(): never {
+ throw new HTTPException(TRUEFOUNDRY_MANAGED_STATUS, { message: TRUEFOUNDRY_MANAGED_MESSAGE });
+}
diff --git a/packages/trueforge/src/truefoundry/trueFoundryManaged.ts b/packages/trueforge/src/truefoundry/trueFoundryManaged.ts
deleted file mode 100644
index 0899fa7e9..000000000
--- a/packages/trueforge/src/truefoundry/trueFoundryManaged.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { RequestErrorResponseSchema } from '../schemas/errors';
-
-export const TRUEFOUNDRY_MANAGED_STATUS = 424 as const;
-export const TRUEFOUNDRY_MANAGED_MESSAGE = 'This resource is managed by TrueFoundry';
-
-export const trueFoundryManagedResponse = {
- content: { 'application/json': { schema: RequestErrorResponseSchema } },
- description: 'Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set).',
-} as const;
diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.ts
index 56ac3d65f..0aea4dae3 100644
--- a/packages/trueforge/tests/unit/apis/turns.test.ts
+++ b/packages/trueforge/tests/unit/apis/turns.test.ts
@@ -269,8 +269,8 @@ describe('turns', () => {
sessionStore: new SqliteSessionStore(db),
activeTurns: new ActiveTurnRegistry(),
resolveModelProviderStore: () => modelProviderStore,
- resolveAgentStore: () => new SqliteAgentStore(db),
resolveMcpServerStore: () => mcpServerStoreWithAuth(db, tokenStore),
+ resolveAgentStore: () => new SqliteAgentStore(db),
skillStore: new SqliteSkillStore(db),
eventSubscriptions,
resolveSandboxProviderStore: () => new SqliteSandboxProviderStore(db),
diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts
index a449859dd..50028fb48 100644
--- a/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts
@@ -98,7 +98,12 @@ function tfStore(input: {
return new TrueFoundryAgentStore({
inner: input.inner,
client: input.client,
- accessToken: input.accessToken ?? TOKEN,
+ context: {
+ tenant_id: TENANT,
+ subject: { id: 'user-1', type: 'user', display_name: 'user-1' },
+ roles: [],
+ user_credential: input.accessToken ?? TOKEN,
+ },
db: input.db ?? mockDb(),
});
}
@@ -115,6 +120,7 @@ function mockClient(
tls: { enabled: false, dir: '' },
httpTimeoutMs: 10_000,
httpAgentTimeoutMs: 3_000,
+ apiKey: 'tfy-api-key',
});
client.putRemoteAgent =
overrides.putRemoteAgent ?? (async (): Promise<PutRemoteAgentResult> => ({ externalId: 'sf-1' }));
diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
index e6555ceb9..20b77045a 100644
--- a/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
@@ -1,5 +1,6 @@
import { getPublicBaseUrl } from '../../../src/config';
import { McpServerNotFoundError } from '../../../src/db/mcpServerStore';
+import { createTrueFoundryRequestContext } from '../../../src/truefoundry/accessToken';
import { MCP_PROXY_BASE_URL_TEMPLATE } from '../../../src/truefoundry/mapSfyMcpServers';
import type { TrueFoundryMcpApiClient } from '../../../src/truefoundry/TrueFoundryMcpServerStore';
import {
@@ -33,6 +34,7 @@ function createMockClient(): MockClient {
getMcpAuthorize: jest.fn(),
getMcpAuthStatus: jest.fn(),
deleteMcpAuth: jest.fn(),
+ vendToken: jest.fn(),
};
}
@@ -50,8 +52,13 @@ function createStore(input?: {
client.deleteMcpAuth.mockResolvedValue(undefined);
const store = new TrueFoundryMcpServerStore({
client,
- accessToken: input?.accessToken ?? ACCESS_TOKEN,
- subject: input?.subject ?? { id: 'user-1', type: 'user', display_name: 'user-1' },
+ context: createTrueFoundryRequestContext({
+ tenant_id: TENANT,
+ subject: input?.subject ?? { id: 'user-1', type: 'user', display_name: 'user-1' },
+ roles: [],
+ user_credential: input?.accessToken ?? ACCESS_TOKEN,
+ }),
+ agent: undefined,
});
return { store, client };
}
diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundrySandboxProviderStore.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundrySandboxProviderStore.test.ts
index a3cdf6d10..684ca222e 100644
--- a/packages/trueforge/tests/unit/truefoundry/TrueFoundrySandboxProviderStore.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundrySandboxProviderStore.test.ts
@@ -1,5 +1,6 @@
+import type { RequestContext } from '../../../src/auth/identity';
+import { TRUEFOUNDRY_MANAGED_MESSAGE, TRUEFOUNDRY_MANAGED_STATUS } from '../../../src/truefoundry/errors';
import { resolveTrueFoundrySandboxProviderConfig } from '../../../src/truefoundry/resolveTrueFoundrySandboxProviderConfig';
-import { TRUEFOUNDRY_MANAGED_MESSAGE, TRUEFOUNDRY_MANAGED_STATUS } from '../../../src/truefoundry/trueFoundryManaged';
import { TrueFoundrySandboxProviderStore } from '../../../src/truefoundry/TrueFoundrySandboxProviderStore';
jest.mock('../../../src/truefoundry/resolveTrueFoundrySandboxProviderConfig', () => {
@@ -16,6 +17,12 @@ const mockResolveConfig = resolveTrueFoundrySandboxProviderConfig as jest.Mocked
const ACCESS_TOKEN = 'caller-token';
const TENANT = 'acme';
+const context: RequestContext = {
+ tenant_id: TENANT,
+ subject: { id: 'user-1', type: 'user', display_name: 'user-1' },
+ roles: [],
+ user_credential: ACCESS_TOKEN,
+};
const SETTINGS_BODY = {
snapshotName: 'tfy-sandbox-snap',
autoStopIntervalInMinutes: 10,
@@ -52,7 +59,7 @@ describe('TrueFoundrySandboxProviderStore', () => {
it('get returns undefined when shared sandbox is not configured', async () => {
mockResolveConfig.mockReturnValue(undefined);
const fetchMock = mockSettingsFetch();
- const store = new TrueFoundrySandboxProviderStore({ accessToken: ACCESS_TOKEN });
+ const store = new TrueFoundrySandboxProviderStore({ context });
await expect(store.getSandboxProvider(TENANT)).resolves.toBeUndefined();
expect(fetchMock).not.toHaveBeenCalled();
});
@@ -61,14 +68,14 @@ describe('TrueFoundrySandboxProviderStore', () => {
const timeout = new Error('The operation was aborted due to timeout');
timeout.name = 'TimeoutError';
global.fetch = jest.fn().mockRejectedValue(timeout) as typeof fetch;
- const store = new TrueFoundrySandboxProviderStore({ accessToken: ACCESS_TOKEN });
+ const store = new TrueFoundrySandboxProviderStore({ context });
await expect(store.getSandboxProvider(TENANT)).rejects.toThrow('Sandbox settings endpoint timed out after 10s');
});
it('get returns ready Daytona record with snapshot build_ref from settings server', async () => {
const fetchMock = mockSettingsFetch();
- const store = new TrueFoundrySandboxProviderStore({ accessToken: ACCESS_TOKEN });
+ const store = new TrueFoundrySandboxProviderStore({ context });
const record = await store.getSandboxProvider(TENANT);
@@ -93,7 +100,7 @@ describe('TrueFoundrySandboxProviderStore', () => {
});
it('writes and get-for-update are managed (424)', () => {
- const store = new TrueFoundrySandboxProviderStore({ accessToken: ACCESS_TOKEN });
+ const store = new TrueFoundrySandboxProviderStore({ context });
const assertManaged = (run: () => unknown) => {
try {
run();
diff --git a/packages/trueforge/tests/unit/truefoundry/accessToken.test.ts b/packages/trueforge/tests/unit/truefoundry/accessToken.test.ts
new file mode 100644
index 000000000..e1b3073b7
--- /dev/null
+++ b/packages/trueforge/tests/unit/truefoundry/accessToken.test.ts
@@ -0,0 +1,131 @@
+import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';
+import { HTTPException } from 'hono/http-exception';
+import type { RequestContext } from '../../../src/auth/identity';
+import type { AgentRecord } from '../../../src/db/agentStore';
+import {
+ accessTokenForRequest,
+ agentAccessToken,
+ asTrueFoundryRequestContext,
+ callerAccessToken,
+ createTrueFoundryRequestContext,
+} from '../../../src/truefoundry/accessToken';
+
+const CONTEXT: RequestContext = {
+ tenant_id: 'acme',
+ subject: { id: 'user-1', type: 'user', display_name: 'User' },
+ roles: [],
+ user_credential: 'caller-token',
+};
+
+const AGENT: AgentRecord = {
+ id: 'agent-1',
+ tenant_id: 'acme',
+ name: 'named',
+ manifest: AgentSpecSchema.parse({ model: { name: 'p/m' } }),
+ external_id: 'ext-agent',
+ created_by_subject: { subject_id: 'user-1', subject_type: 'user', subject_display_name: 'User' },
+ created_at: '2026-01-01T00:00:00.000Z',
+ updated_at: '2026-01-01T00:00:00.000Z',
+};
+
+describe('callerAccessToken', () => {
+ it('resolves the caller bearer', async () => {
+ await expect(callerAccessToken(CONTEXT)()).resolves.toBe('caller-token');
+ });
+
+ it('rejects with 401 before any call is attempted when the caller has no token', () => {
+ expect(() => callerAccessToken({ ...CONTEXT, user_credential: null })).toThrow(
+ expect.objectContaining({ status: 401 }),
+ );
+ });
+});
+
+describe('agentAccessToken', () => {
+ it('vends a token scoped to the agent, naming the caller as the subject', async () => {
+ const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
+
+ await expect(agentAccessToken({ client, context: CONTEXT, agent: AGENT })()).resolves.toBe('agent-token');
+ expect(client.vendToken).toHaveBeenCalledWith({
+ subject: CONTEXT.subject,
+ agentId: 'ext-agent',
+ tenantName: 'acme',
+ });
+ });
+
+ it('vends once and reuses the token for later calls', async () => {
+ const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
+ const resolve = agentAccessToken({ client, context: CONTEXT, agent: AGENT });
+
+ await expect(Promise.all([resolve(), resolve()])).resolves.toEqual(['agent-token', 'agent-token']);
+ await expect(resolve()).resolves.toBe('agent-token');
+ expect(client.vendToken).toHaveBeenCalledTimes(1);
+ });
+
+ it('vends again after a failed exchange', async () => {
+ const client = {
+ vendToken: jest.fn().mockRejectedValueOnce(new Error('vend failed')).mockResolvedValue('agent-token'),
+ };
+ const resolve = agentAccessToken({ client, context: CONTEXT, agent: AGENT });
+
+ await expect(resolve()).rejects.toThrow('vend failed');
+ await expect(resolve()).resolves.toBe('agent-token');
+ expect(client.vendToken).toHaveBeenCalledTimes(2);
+ });
+
+ it('rejects with 422 when the agent was never registered with TrueFoundry', () => {
+ const client = { vendToken: jest.fn() };
+
+ expect(() => agentAccessToken({ client, context: CONTEXT, agent: { ...AGENT, external_id: null } })).toThrow(
+ HTTPException,
+ );
+ expect(client.vendToken).not.toHaveBeenCalled();
+ });
+});
+
+describe('asTrueFoundryRequestContext', () => {
+ it('rejects a plain request context that was not created for TrueFoundry', () => {
+ expect(() => asTrueFoundryRequestContext(CONTEXT)).toThrow('TrueFoundry request context required');
+ });
+});
+
+describe('accessTokenForRequest', () => {
+ it('uses the caller token without an agent', async () => {
+ const client = { vendToken: jest.fn() };
+ const context = createTrueFoundryRequestContext(CONTEXT);
+
+ await expect(accessTokenForRequest({ client, context, agent: undefined })()).resolves.toBe('caller-token');
+ expect(client.vendToken).not.toHaveBeenCalled();
+ });
+
+ it('uses a vended token with an agent', async () => {
+ const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
+ const context = createTrueFoundryRequestContext(CONTEXT);
+
+ await expect(accessTokenForRequest({ client, context, agent: AGENT })()).resolves.toBe('agent-token');
+ expect(client.vendToken).toHaveBeenCalledTimes(1);
+ });
+
+ it('shares one vend across stores on the same request', async () => {
+ const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
+ const context = createTrueFoundryRequestContext(CONTEXT);
+
+ const model = accessTokenForRequest({ client, context, agent: AGENT });
+ const mcp = accessTokenForRequest({ client, context, agent: AGENT });
+
+ expect(model).toBe(mcp);
+ await expect(Promise.all([model(), mcp()])).resolves.toEqual(['agent-token', 'agent-token']);
+ expect(client.vendToken).toHaveBeenCalledTimes(1);
+ });
+
+ it('vends again on a later request for the same user and agent', async () => {
+ const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
+ const firstRequest = createTrueFoundryRequestContext(CONTEXT);
+ const secondRequest = createTrueFoundryRequestContext(CONTEXT);
+
+ await expect(accessTokenForRequest({ client, context: firstRequest, agent: AGENT })()).resolves.toBe('agent-token');
+ await expect(accessTokenForRequest({ client, context: secondRequest, agent: AGENT })()).resolves.toBe(
+ 'agent-token',
+ );
+ expect(client.vendToken).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
index 64a9392b9..12d324429 100644
--- a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
@@ -1,7 +1,24 @@
import { HTTPException } from 'hono/http-exception';
import type { McpServerRecord } from '../../../src/db/mcpServerStore';
+import { createTrueFoundryRequestContext } from '../../../src/truefoundry/accessToken';
import { parsePerServerMcpHeaders } from '../../../src/truefoundry/perServerMcpHeaders';
-import { TrueFoundryMcpServerStore } from '../../../src/truefoundry/TrueFoundryMcpServerStore';
+import {
+ TrueFoundryMcpServerStore,
+ type TrueFoundryMcpApiClient,
+} from '../../../src/truefoundry/TrueFoundryMcpServerStore';
+
+function unusedClient(): TrueFoundryMcpApiClient {
+ const unused = (): Promise<never> => Promise.reject(new Error('unused'));
+ return {
+ getMcpServerByName: unused,
+ listMcpServers: unused,
+ listGatewayInstallations: unused,
+ getMcpAuthorize: unused,
+ getMcpAuthStatus: unused,
+ deleteMcpAuth: unused,
+ vendToken: () => Promise.resolve('caller-token'),
+ };
+}
const record = (name: string): McpServerRecord => ({
id: name,
@@ -19,14 +36,27 @@ const record = (name: string): McpServerRecord => ({
const storeWith = (perServerHeaders: Record<string, Record<string, string>>): TrueFoundryMcpServerStore =>
new TrueFoundryMcpServerStore({
- client: {} as never,
- accessToken: 'caller-token',
- subject: { id: 'user-1', type: 'user', display_name: 'user-1' },
+ client: unusedClient(),
+ context: createTrueFoundryRequestContext({
+ tenant_id: 'default',
+ subject: { id: 'user-1', type: 'user', display_name: 'user-1' },
+ roles: [],
+ user_credential: 'caller-token',
+ }),
+ agent: undefined,
perServerHeaders,
});
-function invokeHeaders(store: TrueFoundryMcpServerStore, name: string) {
- return store.resolveInvokeHeaders({ record: record(name), userRef: 'user-1' });
+async function invokeHeaders(store: TrueFoundryMcpServerStore, name: string): Promise<Record<string, string>> {
+ const resolve = store.resolveInvokeHeaders({ record: record(name), userRef: 'user-1' });
+ if (typeof resolve !== 'function') {
+ throw new Error('expected a headers resolver so the token is read at connect time');
+ }
+ const resolved = await resolve();
+ if (!('headers' in resolved)) {
+ throw new Error('expected headers rather than an auth-required signal');
+ }
+ return resolved.headers;
}
describe('parsePerServerMcpHeaders', () => {
@@ -56,14 +86,14 @@ describe('parsePerServerMcpHeaders', () => {
});
describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => {
- it('sends only the gateway Bearer when a server has no override', () => {
- expect(invokeHeaders(storeWith({}), 'tfy-docs-mcp')).toEqual({
+ it('sends only the gateway Bearer when a server has no override', async () => {
+ await expect(invokeHeaders(storeWith({}), 'tfy-docs-mcp')).resolves.toEqual({
Authorization: 'Bearer caller-token',
});
});
- it("merges that server's override on top of the Bearer", () => {
- const headers = invokeHeaders(
+ it("merges that server's override on top of the Bearer", async () => {
+ const headers = await invokeHeaders(
storeWith({
'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' },
}),
@@ -76,8 +106,8 @@ describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => {
});
});
- it('gives one server nothing of another, so an identity cannot reach the wrong upstream', () => {
- const headers = invokeHeaders(
+ it('gives one server nothing of another, so an identity cannot reach the wrong upstream', async () => {
+ const headers = await invokeHeaders(
storeWith({
'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' },
}),
@@ -89,8 +119,8 @@ describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => {
it.each(['Authorization', 'authorization', 'AUTHORIZATION', 'AuThOrIzAtIoN'])(
'drops an override under %s, which object keys would otherwise keep beside the Bearer',
- name => {
- const headers = invokeHeaders(
+ async name => {
+ const headers = await invokeHeaders(
storeWith({
'tfy-platform-mcp': { [name]: 'Bearer smuggled' },
}),
@@ -101,8 +131,8 @@ describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => {
},
);
- it('keeps the rest of an override that also carried an authorization key', () => {
- const headers = invokeHeaders(
+ it('keeps the rest of an override that also carried an authorization key', async () => {
+ const headers = await invokeHeaders(
storeWith({
'tfy-platform-mcp': { authorization: 'Bearer smuggled', 'x-tfy-mcp-headers': '{"a":"b"}' },
}),