Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix: remint Codex mcp-host JWTs and omit ChatGPT sampling fields

Alfredo Lopez68367f09be11
diff --git a/codex-llm-proxy/src/codexTransport.ts b/codex-llm-proxy/src/codexTransport.ts
index b16c480ad..806605d8a 100644
--- a/codex-llm-proxy/src/codexTransport.ts
+++ b/codex-llm-proxy/src/codexTransport.ts
@@ -287,12 +287,10 @@ function toUpstreamPayload(request: CodexCompletionRequestV1): Record<string, un
}))
payload.parallel_tool_calls = true
}
- if (request.generation?.maxOutputTokens !== undefined) {
- payload.max_output_tokens = request.generation.maxOutputTokens
- }
- if (request.generation?.temperature !== undefined) {
- payload.temperature = request.generation.temperature
- }
+ // ChatGPT `/codex/responses` rejects sampling fields that Chat Completions
+ // treats as portable. Keep them on CodexCompletionRequestV1 (authorize hash)
+ // and omit them on the upstream wire. The CLI Codex client also omits
+ // max_output_tokens / temperature.
if (request.generation?.toolChoice) {
payload.tool_choice = request.generation.toolChoice
}
diff --git a/codex-llm-proxy/test/codexTransport.conformance.test.ts b/codex-llm-proxy/test/codexTransport.conformance.test.ts
index 43fc0afbe..ed2944652 100644
--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts
+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts
@@ -537,6 +537,112 @@ describe('streamCodexCompletion', () => {
{ type: 'function_call', call_id: 'call-1', name: 'echo', arguments: '{"x":1}' },
{ type: 'function_call_output', call_id: 'call-1', output: 'ok' },
])
+ expect(body).not.toHaveProperty('max_output_tokens')
+ expect(body).not.toHaveProperty('temperature')
+ })
+
+ it('omits Notify-like generation fields on the Responses wire', async () => {
+ const fetchFn = vi.fn(async () =>
+ sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])
+ )
+ await streamCodexCompletion({
+ executionTicket: 'ticket-1',
+ requestHash: REQUEST_HASH,
+ request: REQUEST,
+ ticket: {
+ jti: 'jti-1',
+ hostRef: 'research-host',
+ model: 'gpt-5.1',
+ requestHash: REQUEST_HASH,
+ providerAttemptId: 'att-1',
+ },
+ redeem: async () => redeemSuccess(),
+ finalize: vi.fn(async () => ({
+ providerAttemptId: 'att-1',
+ outcome: 'success',
+ duplicate: false,
+ })),
+ fetchFn,
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ })
+ const body = JSON.parse(String(fetchFn.mock.calls[0]?.[1]?.body)) as Record<string, unknown>
+ expect(body.instructions).toBeUndefined()
+ expect(body).not.toHaveProperty('max_output_tokens')
+ expect(body).not.toHaveProperty('temperature')
+ expect(body.store).toBe(false)
+ expect(body.input).toEqual([{ role: 'user', content: 'hello' }])
+ })
+
+ it('keeps analysis instructions but omits max_output_tokens and temperature', async () => {
+ const request = {
+ ...REQUEST,
+ messages: [
+ { role: 'system' as const, content: 'review this repository' },
+ { role: 'user' as const, content: 'findings' },
+ ],
+ generation: { maxOutputTokens: 4096, temperature: 0.2 },
+ }
+ const requestHash = hashCodexCompletionRequestV1(request)
+ const fetchFn = vi.fn(async () =>
+ sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])
+ )
+ await streamCodexCompletion({
+ executionTicket: 'ticket-1',
+ requestHash,
+ request,
+ ticket: {
+ jti: 'jti-1',
+ hostRef: 'research-host',
+ model: 'gpt-5.1',
+ requestHash,
+ providerAttemptId: 'att-1',
+ },
+ redeem: async () => redeemSuccess(),
+ finalize: vi.fn(async () => ({
+ providerAttemptId: 'att-1',
+ outcome: 'success',
+ duplicate: false,
+ })),
+ fetchFn,
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ })
+ const body = JSON.parse(String(fetchFn.mock.calls[0]?.[1]?.body)) as Record<string, unknown>
+ expect(body.instructions).toBe('review this repository')
+ expect(body.input).toEqual([{ role: 'user', content: 'findings' }])
+ expect(body).not.toHaveProperty('max_output_tokens')
+ expect(body).not.toHaveProperty('temperature')
+ })
+
+ it('maps upstream 400 to invalid_request and finalizes error without usage', async () => {
+ const finalize = vi.fn(async () => ({
+ providerAttemptId: 'att-1',
+ outcome: 'error' as const,
+ duplicate: false,
+ }))
+ await expect(
+ streamCodexCompletion({
+ executionTicket: 'ticket-1',
+ requestHash: REQUEST_HASH,
+ request: REQUEST,
+ ticket: {
+ jti: 'jti-1',
+ hostRef: 'research-host',
+ model: 'gpt-5.1',
+ requestHash: REQUEST_HASH,
+ providerAttemptId: 'att-1',
+ },
+ redeem: async () => redeemSuccess(),
+ finalize,
+ fetchFn: vi.fn(async () => new Response('bad request', { status: 400 })),
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ })
+ ).rejects.toMatchObject({ code: 'invalid_request' })
+ expect(finalize).toHaveBeenCalledWith(
+ expect.objectContaining({
+ receipt: expect.objectContaining({ outcome: 'error' }),
+ })
+ )
+ expect(finalize.mock.calls[0]?.[0]?.receipt?.usage).toBeUndefined()
})
it('emits a tool call only after argument deltas complete', async () => {
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index b4bc5f33b..19d142c68 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.322",
+ "version": "0.1.323",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.322",
+ "version": "0.1.323",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index d317b9731..7907fb24a 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.322",
+ "version": "0.1.323",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/k8sClient.test.ts b/workflow-recipes/src/k8sClient.test.ts
index d3cff3bf0..6daab5089 100644
--- a/workflow-recipes/src/k8sClient.test.ts
+++ b/workflow-recipes/src/k8sClient.test.ts
@@ -1397,6 +1397,60 @@ describe('workload status refresh loop helpers', () => {
expect(reconcile).not.toHaveBeenCalled()
})
+ it('reconciles when Codex connection-ref changes without a generation bump', async () => {
+ const cached = makeWorkloadRecipe({
+ metadata: { name: 'active-recipe', namespace: 'sandbox-recipes', generation: 7 },
+ status: { phase: 'active', message: 'All workloads deployed' },
+ })
+ const granted = makeWorkloadRecipe({
+ metadata: {
+ name: 'active-recipe',
+ namespace: 'sandbox-recipes',
+ generation: 7,
+ resourceVersion: 'next',
+ annotations: { 'clerum.io/codex-connection-ref': 'codex-ba832480dffd9095' },
+ },
+ status: { phase: 'active', message: 'All workloads deployed' },
+ })
+ const reconcile = vi.fn().mockResolvedValue({
+ phase: 'active',
+ message: 'All workloads deployed',
+ workloadStatuses: [],
+ })
+
+ type InternalWatcher = {
+ recipes: Map<string, WorkflowRecipeCRD>
+ transientRetries: Map<string, { timer: ReturnType<typeof setTimeout>; attempts: number }>
+ stopped: boolean
+ reconciler: {
+ reconcile: typeof reconcile
+ isRecipeStillActive: ReturnType<typeof vi.fn>
+ ensureFinalizer: ReturnType<typeof vi.fn>
+ patchStatus: ReturnType<typeof vi.fn>
+ }
+ handleRecipeEvent: (type: string, recipe: WorkflowRecipeCRD) => Promise<void>
+ scheduleTransientRetry: ReturnType<typeof vi.fn>
+ clearTransientRetry: ReturnType<typeof vi.fn>
+ }
+ const internal = Object.create(WorkflowRecipeWatcher.prototype) as InternalWatcher
+ internal.recipes = new Map([[cached.metadata.name, cached]])
+ internal.transientRetries = new Map()
+ internal.stopped = false
+ internal.reconciler = {
+ reconcile,
+ isRecipeStillActive: vi.fn().mockResolvedValue(true),
+ ensureFinalizer: vi.fn().mockResolvedValue(undefined),
+ patchStatus: vi.fn().mockResolvedValue(undefined),
+ }
+ internal.scheduleTransientRetry = vi.fn()
+ internal.clearTransientRetry = vi.fn()
+
+ await internal.handleRecipeEvent('MODIFIED', granted)
+
+ expect(internal.recipes.get(granted.metadata.name)).toBe(granted)
+ expect(reconcile).toHaveBeenCalledWith(granted)
+ })
+
it('forces a full reconcile when status-only refresh observes workload drift', async () => {
const recipe = makeWorkloadRecipe({
metadata: { name: 'active-recipe', namespace: 'sandbox-recipes', generation: 7 },
diff --git a/workflow-recipes/src/k8sClient.ts b/workflow-recipes/src/k8sClient.ts
index fac1f8959..61e518eee 100644
--- a/workflow-recipes/src/k8sClient.ts
+++ b/workflow-recipes/src/k8sClient.ts
@@ -54,6 +54,7 @@ import {
} from './types'
import { createDbRunChildRecipe } from './workflow/dbRunChildRecipeCreator'
import type { JwtTokenFactory } from './workflow/jwtTokenFactory'
+import { CODEX_CONNECTION_REF_ANNOTATION } from './workflow/llmAllowedModelsSnapshot'
const PLURAL = 'workflowrecipes'
const MIN_RUNTIME_CREDENTIAL_REFRESH_INTERVAL_MS = 5_000
@@ -1110,11 +1111,18 @@ export class WorkflowRecipeWatcher implements WorkflowRecipeProvider {
const cached = this.recipes.get(recipe.metadata.name)
const cachedGeneration = cached?.metadata.generation
const nextGeneration = recipe.metadata.generation
- return (
- cachedGeneration !== undefined &&
- nextGeneration !== undefined &&
- cachedGeneration === nextGeneration
- )
+ if (
+ cachedGeneration === undefined ||
+ nextGeneration === undefined ||
+ cachedGeneration !== nextGeneration
+ ) {
+ return false
+ }
+ // Grant identity is a metadata annotation and does not bump generation.
+ // Treat it as a real reconcile, not a status-only skip.
+ const cachedRef = cached?.metadata.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
+ const nextRef = recipe.metadata.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
+ return cachedRef === nextRef
}
/**
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
index 870c53b65..69b9f1e38 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
@@ -38,7 +38,11 @@ function podWithPhase(
function makeProvisioner(
podImage: string,
phase: 'Running' | 'Pending' = 'Running',
- opts: { deleting?: boolean; runtimeContractHash?: string } = {}
+ opts: {
+ deleting?: boolean
+ runtimeContractHash?: string
+ tokenRefresh?: { reminted: boolean; reason?: 'scope' | 'binding' | 'ttl' }
+ } = {}
) {
const readNamespacedPod = vi.fn().mockResolvedValue(podWithPhase(podImage, phase, opts))
const deleteNamespacedPod = vi.fn().mockResolvedValue({})
@@ -54,7 +58,7 @@ function makeProvisioner(
config: TEST_CONFIG,
tokenFactory: {},
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
- ensureMcpHostSecrets: vi.fn().mockResolvedValue(undefined),
+ ensureMcpHostSecrets: vi.fn().mockResolvedValue(opts.tokenRefresh),
applyWorkflowNetworkPolicies: vi.fn().mockResolvedValue(undefined),
ensureMcpHostHeadlessService: vi.fn().mockResolvedValue(undefined),
modelConfigHandler: {
@@ -498,3 +502,52 @@ describe('ensureEagerSdkMcpHost image-drift roll', () => {
expect(await reconcile()).toBe('deploying')
})
})
+
+describe('ensureEagerSdkMcpHost runtime token roll', () => {
+ it('rolls a healthy eager mcp-host when runtime JWT scopes were reminted', async () => {
+ const { provisioner, deleteNamespacedPod, createNamespacedPod } = makeProvisioner(
+ DESIRED_IMAGE,
+ 'Running',
+ {
+ runtimeContractHash: desiredRuntimeContractHash(),
+ tokenRefresh: { reminted: true, reason: 'scope' },
+ }
+ )
+
+ const status = await provisioner.ensureEagerSdkMcpHost(
+ RECIPE,
+ 'recipe-uid',
+ SANDBOX_NS,
+ RECIPE,
+ SPEC,
+ RUNTIME,
+ { mcpHostPhase: 'Running' }
+ )
+
+ expect(status).toBe('deploying')
+ expect(deleteNamespacedPod).toHaveBeenCalledWith({
+ name: `${RECIPE}-mcp-host`,
+ namespace: SANDBOX_NS,
+ })
+ expect(createNamespacedPod).not.toHaveBeenCalled()
+ })
+
+ it('does not roll the eager mcp-host on a TTL-only runtime token remint', async () => {
+ const { provisioner, deleteNamespacedPod } = makeProvisioner(DESIRED_IMAGE, 'Running', {
+ runtimeContractHash: desiredRuntimeContractHash(),
+ tokenRefresh: { reminted: true, reason: 'ttl' },
+ })
+
+ await provisioner.ensureEagerSdkMcpHost(
+ RECIPE,
+ 'recipe-uid',
+ SANDBOX_NS,
+ RECIPE,
+ SPEC,
+ RUNTIME,
+ { mcpHostPhase: 'Running' }
+ )
+
+ expect(deleteNamespacedPod).not.toHaveBeenCalled()
+ })
+})
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
index f14f732ad..6e2b94dda 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
@@ -45,6 +45,25 @@ export type EagerSdkMcpHostStatus =
| 'failed'
| 'provider_unavailable'
+/** Why the mcp-host runtime JWT Secret was reminted. */
+export type McpHostRuntimeTokenRefreshReason = 'scope' | 'binding' | 'ttl'
+
+export type McpHostRuntimeTokenRefreshResult = {
+ reminted: boolean
+ reason?: McpHostRuntimeTokenRefreshReason
+}
+
+export const NO_MCP_HOST_RUNTIME_TOKEN_REFRESH: McpHostRuntimeTokenRefreshResult = {
+ reminted: false,
+}
+
+/** Env-injected access/refresh JWTs only update on a new process. */
+export function eagerMcpHostRequiresTokenRoll(
+ result: McpHostRuntimeTokenRefreshResult | void
+): boolean {
+ return result?.reminted === true && (result.reason === 'scope' || result.reason === 'binding')
+}
+
export interface EagerSdkBootstrapProof {
ready: true
contractVersion: 2 | 3
@@ -93,7 +112,7 @@ export type PluginWorkloadSdkProvisionerDeps = {
runtimeScopeRecipeName: string,
spec: WorkflowRecipeSpec,
recipeUid?: string
- ) => Promise<void>
+ ) => Promise<McpHostRuntimeTokenRefreshResult | void>
applyWorkflowNetworkPolicies: (
recipeName: string,
recipeUid: string,
@@ -203,7 +222,7 @@ export class PluginWorkloadSdkProvisioner {
return 'failed'
}
- await this.deps.ensureMcpHostSecrets(
+ const tokenRefresh = await this.deps.ensureMcpHostSecrets(
namespace,
recipeName,
runtimeScopeRecipeName,
@@ -259,6 +278,29 @@ export class PluginWorkloadSdkProvisioner {
}
}
+ // Runtime JWT scope/binding remint. Access/refresh tokens are env-injected
+ // on a bare Pod, so a Secret patch does not update process.env. HCC rolls
+ // on contract_changed; WRC must do the same or authorize keeps the first-boot
+ // JWT (insufficient_scope after reservation-only Codex).
+ if (
+ eagerMcpHostRequiresTokenRoll(tokenRefresh) &&
+ (mcpHostPhase === 'Running' || mcpHostPhase === 'Pending')
+ ) {
+ const runningPod = await readMcpHostPodDriftStateIfExists(
+ this.deps.coreApi,
+ `${recipeName}-mcp-host`,
+ this.deps.config.sandboxNamespace
+ )
+ if (runningPod?.deleting) {
+ return 'deploying'
+ }
+ log.info('Plugin Workload SDK eager mcp-host runtime token drift; rolling Pod', {
+ reason: tokenRefresh?.reason,
+ })
+ await this.rollEagerSdkMcpHostPod(recipeName)
+ return 'deploying'
+ }
+
// Image-drift roll. The eager SDK mcp-host is a bare Pod (no Deployment),
// so a platform mcp-host image bump never reaches a long-lived recipe on
// its own: createIfNotExists is a no-op while the stale pod stays healthy,
diff --git a/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts b/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
index feb44b088..f725ce689 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
@@ -378,6 +378,7 @@ describe('WorkflowReconciler Codex scope provenance', () => {
},
})
runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mockClear()
+ crashRecoveryMocks.deletePodIfExists.mockClear()
await reconcileRecipe(
reconciler,
@@ -386,6 +387,11 @@ describe('WorkflowReconciler Codex scope provenance', () => {
expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(crashRecoveryMocks.deletePodIfExists).toHaveBeenCalledWith(
+ expect.anything(),
+ 'codex-recipe-mcp-host',
+ sandboxNamespace
+ )
expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
name: CODEX_PROXY_POLICY,
namespace: sandboxNamespace,
@@ -399,11 +405,46 @@ describe('WorkflowReconciler Codex scope provenance', () => {
expect(issuedScopes()).toContain('llm:codex:execute')
coreApi.readNamespacedConfigMap.mockResolvedValue(eligibleCodexConfigMap(true))
+ const futureExp = Math.floor(Date.now() / 1000) + 3600
+ const binding = {
+ exp: futureExp,
+ recipeNamespace: sandboxNamespace,
+ recipeName: 'codex-recipe',
+ hostRefs: [`${sandboxNamespace}/codex-recipe`],
+ workflowControlScopes: ['llm:codex:execute'],
+ scopes: ['llm:codex:execute', 'gfs.read'],
+ }
+ coreApi.readNamespacedSecret.mockResolvedValue({
+ data: {
+ 'mcp-host-runtime-access-token': Buffer.from(unsignedRuntimeJwt(binding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-runtime-refresh-token': Buffer.from(unsignedRuntimeJwt(binding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-workflow-control-token': Buffer.from(unsignedRuntimeJwt(binding)).toString(
+ 'base64'
+ ),
+ 'mcp-host-gfs-token': Buffer.from(
+ unsignedRuntimeJwt({
+ ...binding,
+ sub: `host:3rd:${sandboxNamespace}/codex-recipe`,
+ scopes: ['gfs.read'],
+ })
+ ).toString('base64'),
+ },
+ })
runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mockClear()
+ crashRecoveryMocks.deletePodIfExists.mockClear()
await reconcileRecipe(reconciler, makeCodexSpec())
expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(crashRecoveryMocks.deletePodIfExists).toHaveBeenCalledWith(
+ expect.anything(),
+ 'codex-recipe-mcp-host',
+ sandboxNamespace
+ )
expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
name: CODEX_PROXY_POLICY,
namespace: sandboxNamespace,
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 1bfb7d314..201d65a31 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -75,6 +75,9 @@ import { NetworkPolicyConfig, buildWorkflowNetworkPolicies } from './networkPoli
import { ObjectStorageClient, StorageCredentials, StorageRef } from './objectStorageClient'
import {
type EagerSdkBootstrapProof,
+ type McpHostRuntimeTokenRefreshReason,
+ type McpHostRuntimeTokenRefreshResult,
+ NO_MCP_HOST_RUNTIME_TOKEN_REFRESH,
PluginWorkloadSdkProvisioner,
} from './pluginWorkloadSdkProvisioner'
import type {
@@ -3708,8 +3711,8 @@ export class WorkflowReconciler {
runtimeScopeRecipeName: string,
spec: WorkflowRecipeSpec,
recipeUid?: string
- ): Promise<void> {
- await this.ensureMcpHostRuntimeTokenSecret(
+ ): Promise<McpHostRuntimeTokenRefreshResult> {
+ const tokenRefresh = await this.ensureMcpHostRuntimeTokenSecret(
namespace,
recipeName,
runtimeScopeRecipeName,
@@ -3719,6 +3722,7 @@ export class WorkflowReconciler {
if (this.deps.config.pluginWorkloadSdkEnabled && spec.pluginWorkloadSdk) {
await this.pluginWorkloadSdkProvisioner.ensurePluginWorkloadSdkTokenSecret(recipeName, spec)
}
+ return tokenRefresh
}
/**
@@ -4649,7 +4653,7 @@ export class WorkflowReconciler {
runtimeScopeRecipeName = recipeName,
workflowControlScopes: EffectiveWorkflowControlScope[] = [],
gfsScopes: WorkflowRecipeGfsScope[] = ['gfs.read']
- ): Promise<void> {
+ ): Promise<McpHostRuntimeTokenRefreshResult> {
const secretName = `wf-${recipeName}-mcp-host-runtime-tokens`
const sandboxNamespace = this.deps.config.sandboxNamespace
@@ -4658,7 +4662,7 @@ export class WorkflowReconciler {
name: secretName,
namespace: sandboxNamespace,
})
- await this.refreshMcpHostRuntimeTokensIfExpiring(
+ return await this.refreshMcpHostRuntimeTokensIfExpiring(
recipeNamespace,
recipeName,
runtimeScopeRecipeName,
@@ -4666,7 +4670,6 @@ export class WorkflowReconciler {
gfsScopes,
existing
)
- return
} catch (err) {
if (getErrorCode(err) !== 404) throw err
}
@@ -4695,13 +4698,14 @@ export class WorkflowReconciler {
body: mcpHostRuntimeSecret,
})
this.log.info(`Created Secret "${secretName}"`)
+ return NO_MCP_HOST_RUNTIME_TOKEN_REFRESH
} catch (err) {
if (getErrorCode(err) !== 409) throw err
const existing = await this.deps.coreApi.readNamespacedSecret({
name: secretName,
namespace: sandboxNamespace,
})
- await this.refreshMcpHostRuntimeTokensIfExpiring(
+ const tokenRefresh = await this.refreshMcpHostRuntimeTokensIfExpiring(
recipeNamespace,
recipeName,
runtimeScopeRecipeName,
@@ -4710,6 +4714,7 @@ export class WorkflowReconciler {
existing
)
this.log.info(`Secret "${secretName}" already exists (skip)`)
+ return tokenRefresh
}
}
@@ -4725,7 +4730,7 @@ export class WorkflowReconciler {
workflowControlScopes: EffectiveWorkflowControlScope[],
expectedGfsScopes: WorkflowRecipeGfsScope[],
existing: k8s.V1Secret
- ): Promise<void> {
+ ): Promise<McpHostRuntimeTokenRefreshResult> {
const rawAccess = existing.data?.['mcp-host-runtime-access-token']
const rawRefresh = existing.data?.['mcp-host-runtime-refresh-token']
const accessJwt = rawAccess ? Buffer.from(rawAccess, 'base64').toString('utf-8') : ''
@@ -4806,8 +4811,16 @@ export class WorkflowReconciler {
gfsScopesMismatch ||
gfsAccessExp - nowSecs < refreshBeforeSeconds
- if (!needsMcpHostRuntimeRefresh && !needsWorkflowControlRefresh && !needsGfsAccessRefresh)
- return
+ if (!needsMcpHostRuntimeRefresh && !needsWorkflowControlRefresh && !needsGfsAccessRefresh) {
+ return NO_MCP_HOST_RUNTIME_TOKEN_REFRESH
+ }
+
+ const refreshReason: McpHostRuntimeTokenRefreshReason =
+ runtimeScopesMismatch || controlScopesMismatch
+ ? 'scope'
+ : runtimeBindingMismatch || controlBindingMismatch
+ ? 'binding'
+ : 'ttl'
if (
runtimeBindingMismatch ||
@@ -4883,8 +4896,18 @@ export class WorkflowReconciler {
{ middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')] }
)
this.log.info(
- `Refreshed workflow auth Secret for ${recipeName} (mcpHostRuntime=${needsMcpHostRuntimeRefresh}, mcpHostControl=${needsWorkflowControlRefresh})`
+ `Refreshed workflow auth Secret for ${recipeName} (mcpHostRuntime=${needsMcpHostRuntimeRefresh}, mcpHostControl=${needsWorkflowControlRefresh}, reason=${refreshReason})`
)
+ if (refreshReason === 'scope' || refreshReason === 'binding') {
+ // Access/refresh JWTs are env-injected. A Secret patch does not update
+ // the running process; refresh/reissue copy the stale scopes.
+ await deletePodIfExists(
+ this.deps.coreApi,
+ `${recipeName}-mcp-host`,
+ this.deps.config.sandboxNamespace
+ )
+ }
+ return { reminted: true, reason: refreshReason }
} catch (err) {
this.log.error(`Failed to refresh mcpHost runtime tokens for ${recipeName}`, {
error: err instanceof Error ? err.message : String(err),