Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): carry Grok SDK binding over HTTP and reject non-success outcomes
Jose Gabriel Ramirez Encinasd7eaaee1331c
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 4aeebf225..cd2c9e27c 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.341",+ "version": "0.1.342","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.341",+ "version": "0.1.342","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 6a3664633..3e7ba5fc5 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.341",+ "version": "0.1.342","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/llm/__tests__/codexSubscription.test.ts b/mcp-host/src/llm/__tests__/codexSubscription.test.tsindex 79cfdab0b..54374b05c 100644--- a/mcp-host/src/llm/__tests__/codexSubscription.test.ts+++ b/mcp-host/src/llm/__tests__/codexSubscription.test.ts@@ -343,6 +343,35 @@ describe('CodexSubscriptionProvider', () => {).rejects.toMatchObject({ code: 'provider_unavailable' })})+ it.each([+ ['unknown', 'partial codex text', 'outcome_unknown'],+ ['canceled', '', 'canceled'],+ ['canceled', 'partial codex text', 'canceled'],+ ] as const)(+ 'rejects a non-success %s terminal outcome (text=%j) instead of completing',+ async (outcome, text, code) => {+ const stream = vi.fn().mockResolvedValue({ text, toolCalls: [], outcome })+ const provider = new CodexSubscriptionProvider('gpt-5.3-codex', deps({ stream }) as never)++ const single = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ await expect(single).rejects.toBeInstanceOf(CodexProxyError)+ await expect(single).rejects.toMatchObject({ code, dispatched: true })++ await expect(+ provider.completeSingleTurnWithTools(+ [{ role: 'user', content: 'hi' }],+ [{ name: 'echo', description: 'echo', parameters: {} }]+ )+ ).rejects.toMatchObject({ code, dispatched: true })++ const classified = provider.classifyError(new CodexProxyError(code, 'terminal'))+ expect(classified.code).toBe(LlmErrorCode.ApiCallFailed)+ expect(classified.retryable).toBe(false)+ expect(classified.providerDispatched).toBe(true)+ expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()+ }+ )+it('keeps insufficient_scope distinguishable', () => {const provider = new CodexSubscriptionProvider('gpt-5.3-codex', deps() as never)const classified = provider.classifyError(diff --git a/mcp-host/src/llm/__tests__/grokSubscription.test.ts b/mcp-host/src/llm/__tests__/grokSubscription.test.tsindex d5450fc98..22fdb33d4 100644--- a/mcp-host/src/llm/__tests__/grokSubscription.test.ts+++ b/mcp-host/src/llm/__tests__/grokSubscription.test.ts@@ -1,4 +1,6 @@import { describe, expect, it, vi } from 'vitest'+import { LlmErrorCode } from '../../core/errors'+import { classifyFailoverClass } from '../failover/classify'import { GrokProxyError } from '../grokLlmProxyClient'import { GrokSubscriptionProvider } from '../grokSubscription'@@ -70,4 +72,53 @@ describe('GrokSubscriptionProvider', () => {)).rejects.toBeInstanceOf(GrokProxyError)})+ it.each([+ ['unknown', 'partial grok text', 'outcome_unknown'],+ ['canceled', '', 'canceled'],+ ['canceled', 'partial grok text', 'canceled'],+ ] as const)(+ 'rejects a non-success %s terminal outcome (text=%j) instead of completing',+ async (outcome, text, code) => {+ const stream = vi.fn().mockResolvedValue({ text, toolCalls: [], outcome })+ const provider = new GrokSubscriptionProvider('grok-4.6', deps({ stream }) as never)++ const single = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ await expect(single).rejects.toBeInstanceOf(GrokProxyError)+ await expect(single).rejects.toMatchObject({ code, dispatched: true })++ await expect(+ provider.completeSingleTurnWithTools(+ [{ role: 'user', content: 'hi' }],+ [{ name: 'echo', description: 'echo', parameters: {} }]+ )+ ).rejects.toMatchObject({ code, dispatched: true })++ // A dispatched, non-success terminal state must stay fenced: not a+ // failover trigger and never proof that nothing was executed.+ const classified = provider.classifyError(new GrokProxyError(code, 'terminal'))+ expect(classified.code).toBe(LlmErrorCode.ApiCallFailed)+ expect(classified.retryable).toBe(false)+ expect(classified.providerDispatched).toBe(true)+ expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()+ }+ )++ it('still completes a successful terminal outcome', async () => {+ const provider = new GrokSubscriptionProvider('grok-4.6', deps() as never)+ await expect(+ provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ ).resolves.toMatchObject({ content: 'hello from grok proxy', finish_reason: 'stop' })+ })++ it('refuses to authorize without a Grok catalog policy binding using Grok wording', async () => {+ const wired = deps()+ wired.attemptContext = vi.fn().mockReturnValue({ policyRevision: 0, policyHash: '' })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)+ const attempt = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ await expect(attempt).rejects.toMatchObject({ code: 'no_grant' })+ await expect(attempt).rejects.toThrow(/Grok catalog policy binding is missing/)+ await expect(attempt).rejects.not.toThrow(/Codex/)+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()+ expect(wired.proxy.stream).not.toHaveBeenCalled()+ })})diff --git a/mcp-host/src/llm/codexSubscription.ts b/mcp-host/src/llm/codexSubscription.tsindex 455e69620..ad98ea4f5 100644--- a/mcp-host/src/llm/codexSubscription.ts+++ b/mcp-host/src/llm/codexSubscription.ts@@ -85,6 +85,22 @@ function assertTerminalCodexOutcome(result: {'proxy stream ended without a terminal outcome')}+ // Only `success` may become a completion. Partial text from an unknown+ // terminal state or a cancellation is interrupted output: surfacing it as a+ // finished answer would let callers ack it as complete and count it as a+ // healthy call. The request was already dispatched, so keep it fenced.+ if (result.outcome === 'unknown') {+ throw new CodexProxyError(+ 'outcome_unknown',+ 'proxy stream ended without a successful terminal outcome'+ )+ }+ if (result.outcome === 'canceled') {+ throw new CodexProxyError(+ 'canceled',+ 'proxy stream was canceled before a successful terminal outcome'+ )+ }}export class CodexSubscriptionProvider implements SingleTurnProvider {@@ -189,10 +205,7 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {content: result.text,usage: usage.usage,usage_reported: usage.usage_reported,- finish_reason:- result.outcome === 'canceled' || result.outcome === 'unknown'- ? FinishReason.Unknown- : FinishReason.Stop,+ finish_reason: FinishReason.Stop,providerAttemptId: result.providerAttemptId,providerAttemptIndex: result.providerAttemptIndex,}@@ -223,12 +236,7 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {: null,usage: usage.usage,usage_reported: usage.usage_reported,- finish_reason:- result.toolCalls.length > 0- ? FinishReason.ToolUse- : result.outcome === 'canceled' || result.outcome === 'unknown'- ? FinishReason.Unknown- : FinishReason.Stop,+ finish_reason: result.toolCalls.length > 0 ? FinishReason.ToolUse : FinishReason.Stop,}}diff --git a/mcp-host/src/llm/grokSubscription.ts b/mcp-host/src/llm/grokSubscription.tsindex d40d30165..0f71017ef 100644--- a/mcp-host/src/llm/grokSubscription.ts+++ b/mcp-host/src/llm/grokSubscription.ts@@ -85,6 +85,22 @@ function assertTerminalGrokOutcome(result: {'proxy stream ended without a terminal outcome')}+ // Only `success` may become a completion. Partial text from an unknown+ // terminal state or a cancellation is interrupted output: surfacing it as a+ // finished answer would let callers ack it as complete and count it as a+ // healthy call. The request was already dispatched, so keep it fenced.+ if (result.outcome === 'unknown') {+ throw new GrokProxyError(+ 'outcome_unknown',+ 'proxy stream ended without a successful terminal outcome'+ )+ }+ if (result.outcome === 'canceled') {+ throw new GrokProxyError(+ 'canceled',+ 'proxy stream was canceled before a successful terminal outcome'+ )+ }}export class GrokSubscriptionProvider implements SingleTurnProvider {@@ -189,10 +205,7 @@ export class GrokSubscriptionProvider implements SingleTurnProvider {content: result.text,usage: usage.usage,usage_reported: usage.usage_reported,- finish_reason:- result.outcome === 'canceled' || result.outcome === 'unknown'- ? FinishReason.Unknown- : FinishReason.Stop,+ finish_reason: FinishReason.Stop,providerAttemptId: result.providerAttemptId,providerAttemptIndex: result.providerAttemptIndex,}@@ -223,12 +236,7 @@ export class GrokSubscriptionProvider implements SingleTurnProvider {: null,usage: usage.usage,usage_reported: usage.usage_reported,- finish_reason:- result.toolCalls.length > 0- ? FinishReason.ToolUse- : result.outcome === 'canceled' || result.outcome === 'unknown'- ? FinishReason.Unknown- : FinishReason.Stop,+ finish_reason: result.toolCalls.length > 0 ? FinishReason.ToolUse : FinishReason.Stop,}}@@ -253,7 +261,7 @@ export class GrokSubscriptionProvider implements SingleTurnProvider {context.policyRevision < 1 ||!/^[a-f0-9]{64}$/.test(context.policyHash)) {- throw new CodexAuthorizeError('no_grant', 'Codex catalog policy binding is missing')+ throw new CodexAuthorizeError('no_grant', 'Grok catalog policy binding is missing')}const providerAttemptIndex = context.providerAttemptIndex ?? this.nextProviderAttemptIndex++const authorized = await this.deps.authorizer.authorize(diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.tsindex 1cafc5611..e457331b8 100644--- a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.ts@@ -103,6 +103,51 @@ describe('PluginWorkloadSdkBootstrapServer', () => {})})+ const bindingFields = {+ connectionKey: 'team-broker',+ catalogRevision: 4,+ credentialRevision: 2,+ model: 'broker-model',+ bindingHash: 'a'.repeat(64),+ }++ it.each([+ ['grok-subscription', 'subscriptionBinding', 'grok-4'],+ ['codex-subscription', 'codexBinding', 'gpt-5.4-codex'],+ ] as const)(+ 'projects the %s %s across the HTTP boundary with only binding fields',+ async (provider, bindingField, model) => {+ const { baseUrl, configure } = await start()+ const response = await fetch(`${baseUrl}/api/v1/workflow/plugin-workload-sdk/bootstrap`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ provider,+ model,+ contractVersion: 3,+ apiKey: 'must-not-cross-the-boundary',+ [bindingField]: {+ ...bindingFields,+ model,+ accessToken: 'binding-extra-must-not-cross',+ },+ }),+ })+ expect(response.status).toBe(200)+ expect(configure).toHaveBeenCalledTimes(1)+ const request = configure.mock.calls[0]![0] as Record<string, unknown>+ expect(+ Object.keys(request)+ .filter(key => request[key] !== undefined)+ .sort()+ ).toEqual(['contractVersion', 'model', 'provider', bindingField].sort())+ expect(request).toMatchObject({ provider, model, contractVersion: 3 })+ const binding = request[bindingField] as Record<string, unknown>+ expect(binding).toStrictEqual({ ...bindingFields, model })+ expect(JSON.stringify(request)).not.toContain('must-not-cross')+ }+ )+it('requires a configure-scoped WRC token bound to the Pod recipe', async () => {config.enableAuth = trueconfig.wrcPublicKey = publicKeyPemdiff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.tsindex ac29047a2..ae5c94e08 100644--- a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts@@ -1,6 +1,7 @@import express, { type NextFunction, type Request, type Response } from 'express'import { rateLimit } from 'express-rate-limit'import type http from 'node:http'+import { logger } from '../logger'import type { ConfigureResponse, PluginWorkloadSdkBootstrapRequest } from '../workflow/types'import {requireWorkflowAuth,@@ -12,6 +13,23 @@ const CONTROL_RATE_LIMIT_WINDOW_MS = 60_000const CONTROL_RATE_LIMIT_MAX = 60const CONTROL_RATE_LIMIT_MAX_BUCKETS = 10_000+type BootstrapBinding = NonNullable<PluginWorkloadSdkBootstrapRequest['codexBinding']>++/**+ * Field-level projection of a broker execution binding. Values are passed+ * through unvalidated (bootstrapIdentity verifies shape and hash); only the+ * known identity fields cross the handler boundary.+ */+function projectBinding(value: BootstrapBinding): BootstrapBinding {+ return {+ connectionKey: value.connectionKey,+ catalogRevision: value.catalogRevision,+ credentialRevision: value.credentialRevision,+ model: value.model,+ bindingHash: value.bindingHash,+ }+}+export type PluginWorkloadSdkBootstrapHandler = (request: PluginWorkloadSdkBootstrapRequest) => Promise<ConfigureResponse>@@ -88,7 +106,12 @@ export class PluginWorkloadSdkBootstrapServer {...(raw?.contractVersion === 2 || raw?.contractVersion === 3? { contractVersion: raw.contractVersion }: {}),- ...(raw?.codexBinding ? { codexBinding: raw.codexBinding } : {}),+ ...(raw?.codexBinding ? { codexBinding: projectBinding(raw.codexBinding) } : {}),+ // Grok writers emit `subscriptionBinding` only; dropping it here+ // would make every HTTP bootstrap resolve to binding_missing.+ ...(raw?.subscriptionBinding+ ? { subscriptionBinding: projectBinding(raw.subscriptionBinding) }+ : {}),}try {const result = await this.opts.configure(request)@@ -146,7 +169,7 @@ export class PluginWorkloadSdkBootstrapServer {server.once('error', reject)this.server = server})- console.log(`[PluginWorkloadSdk] SDK-only bootstrap server started on port ${this.opts.port}`)+ logger.info({ port: this.opts.port }, '[PluginWorkloadSdk] SDK-only bootstrap server started')}async stop(): Promise<void> {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.tsindex dbe3ab4f2..d3fa98522 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts@@ -5,6 +5,8 @@ import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'import { LlmErrorCode } from '../../core/errors'import { FinishReason } from '../../core/types'import type { SingleTurnProvider, createLLMProvider } from '../../llm'+import { CodexSubscriptionProvider } from '../../llm/codexSubscription'+import { GrokSubscriptionProvider } from '../../llm/grokSubscription'import type { ApiKeys, ModelConfig } from '../../types'import { CircuitBreaker } from '../domain/circuitBreaker'import { PluginWorkloadError } from '../domain/errors'@@ -697,19 +699,24 @@ describe('LlmBridge authorized multi-provider fallback', () => {credentialSlot: '',connectionRef: 'team-grok',}+ // A binding that would be fully valid for this Grok target (same model and+ // key, Grok hash) sits in the Codex slot. Only slot separation rejects it.replaceSdkOnlyCodexBinding({- connectionKey: 'team-plus',+ connectionKey: 'team-grok',catalogRevision: 1,credentialRevision: 1,- model: 'grok-4.6',- bindingHash: computeCodexPolicyHash({- model: 'grok-4.6',+ model: grok.model,+ bindingHash: computeGrokPolicyHash({+ model: grok.model,catalogRevision: 1,credentialRevision: 1,- connectionKey: 'team-plus',+ connectionKey: 'team-grok',}),})- const { bridge } = makeBridge({})+ replaceSdkOnlyGrokBinding(null)+ const provider = new FakeProvider(() => Promise.resolve(OK))+ const { bridge, providerCalls } = makeBridge({ [grok.model]: provider })+ const providerAttemptReporter = { report: vi.fn().mockResolvedValue(undefined) }const issuer = {issue: vi.fn(async () => ({credentialTicket: '',@@ -717,13 +724,21 @@ describe('LlmBridge authorized multi-provider fallback', () => {providerAttemptIndex: 1,})),}- await expect(- bridge.complete({- ...request,- targets: [{ target: grok }],- credentialTicketIssuer: issuer,- })- ).rejects.toMatchObject({ code: 'provider_unavailable' })+ const attempt = bridge.complete({+ ...request,+ targets: [{ target: grok }],+ credentialTicketIssuer: issuer,+ providerAttemptReporter,+ })+ await expect(attempt).rejects.toMatchObject({ code: 'provider_unavailable' })+ await expect(attempt).rejects.toThrow(/Grok execution binding is missing/)+ expect(providerCalls).toEqual([])+ expect(provider.completeSingleTurn).not.toHaveBeenCalled()+ expect(providerAttemptReporter.report).toHaveBeenCalledWith({+ providerAttemptId: 'sdk-attempt-grok',+ providerAttemptIndex: 1,+ status: 'failed',+ })})it('fails over after reserving a Codex target whose execution binding is missing', async () => {@@ -1242,4 +1257,91 @@ describe('LlmBridge oauth-broker terminal accounting', () => {status: 'failed',})})+ it.each([+ ['grok-subscription', 'unknown', 'partial output'],+ ['grok-subscription', 'canceled', ''],+ ['codex-subscription', 'unknown', 'partial output'],+ ['codex-subscription', 'canceled', ''],+ ] as const)(+ 'never acknowledges a %s %s terminal outcome as complete',+ async (providerId, outcome, text) => {+ const grok = providerId === 'grok-subscription'+ const target = grok ? grokTarget : codexTarget+ if (grok) installGrokBinding()+ else installCodexBinding()+ const authorize = vi.fn().mockResolvedValue({+ providerAttemptId: 'proxy-attempt-1',+ requestHash: 'c'.repeat(64),+ executionTicket: 'ticket-123456',+ expiresAt: '2026-08-20T10:00:00.000Z',+ })+ const stream = vi.fn().mockResolvedValue({+ text,+ toolCalls: [],+ outcome,+ usage: { inputTokens: 3, outputTokens: 4 },+ })+ const second = new FakeProvider(() => Promise.resolve(OK))+ const providerDeps = {+ authorizer: { authorize },+ proxy: { stream },+ attemptContext: () => ({ policyRevision: 1, policyHash: 'b'.repeat(64) }),+ }+ const real = grok+ ? new GrokSubscriptionProvider(target.model, providerDeps as never)+ : new CodexSubscriptionProvider(target.model, providerDeps as never)+ const breaker = new CircuitBreaker()+ const record = vi.spyOn(breaker, 'record')+ const { bridge } = makeBridge(+ {+ [target.model]: real as unknown as FakeProvider,+ [fallback.model]: second,+ },+ undefined,+ candidate => (candidate.targetRef === target.targetRef ? breaker : new CircuitBreaker())+ )+ const providerAttemptReporter = { report: vi.fn().mockResolvedValue(undefined) }+ const receipt = {+ providerAttemptId: `sdk-${target.targetRef}`,+ providerAttemptIndex: 1,+ target,+ attemptCount: 1,+ fallbackUsed: false,+ }++ for (const acknowledgementMode of [undefined, 'atomic_terminal_finalization'] as const) {+ providerAttemptReporter.report.mockClear()+ await expect(+ bridge.complete({+ ...request,+ ...(acknowledgementMode ? { acknowledgementMode } : {}),+ targets: [{ target }, { target: fallback }],+ credentialTicketIssuer: {+ issue: vi.fn(async ({ target: issued }: { target: PromptBridgeTarget }) => ({+ credentialTicket: issued.provider === providerId ? '' : 'fresh-fallback',+ providerAttemptId: `sdk-${issued.targetRef}`,+ providerAttemptIndex: issued.provider === providerId ? 1 : 2,+ })),+ },+ providerAttemptReporter,+ })+ ).rejects.toMatchObject({+ code: 'provider_unavailable',+ providerMayHaveExecuted: true,+ providerAttempt: receipt,+ })+ expect(providerAttemptReporter.report).toHaveBeenCalledTimes(1)+ expect(providerAttemptReporter.report).toHaveBeenCalledWith({+ providerAttemptId: receipt.providerAttemptId,+ providerAttemptIndex: 1,+ status: 'provider_unavailable',+ })+ }+ expect(stream).toHaveBeenCalledTimes(2)+ expect(record).not.toHaveBeenCalledWith(true)+ expect(record).toHaveBeenCalledWith(false)+ // Dispatched interrupted output must not fail over and double-execute.+ expect(second.completeSingleTurn).not.toHaveBeenCalled()+ }+ )})