Skip to content

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

TypeScript

feat(mcp-host): classify provider 404 as ModelNotAvailable, stop silent failover (Pieza A)

Diego Zacarias0f1a3354c358
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 6b495a027..a62cdc464 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.237",
+ "version": "0.1.238",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.237",
+ "version": "0.1.238",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index c4d1823eb..2b209bb31 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.237",
+ "version": "0.1.238",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/agent/__tests__/taskExecutor.test.ts b/mcp-host/src/agent/__tests__/taskExecutor.test.ts
index 9c9ed0d3f..bf45c8943 100644
--- a/mcp-host/src/agent/__tests__/taskExecutor.test.ts
+++ b/mcp-host/src/agent/__tests__/taskExecutor.test.ts
@@ -10,6 +10,8 @@ import {
} from '../../core/tools/workflowEffectiveTargets'
import type { Attachment, ChatMessage, MessageContentPart, TraceContextV1 } from '../../core/types'
import { TaskLifecycle } from '../../lifecycle/taskLifecycle'
+import { anthropicApiError } from '../../llm/__tests__/sdkErrorFixtures'
+import { ClaudeProvider } from '../../llm/claude'
import type { Task, TaskError } from '../../queue/types'
import { resolveProviderWorkflowCallerContext } from '../../workflow/providerWorkflowCallerContextClient'
import { TaskExecutor, type TaskExecutorDeps } from '../taskExecutor'
@@ -265,6 +267,45 @@ describe('TaskExecutor', () => {
)
})
+ it('surfaces a provider 404 as a non-retryable LLM_MODEL_NOT_AVAILABLE TaskError', async () => {
+ // Derive the LlmError from the real Claude classifier fed a real
+ // Anthropic.APIError (not a hand-built shape), then wrap it exactly as
+ // LlmPortAdapter.handleProviderError does, so the observable TaskError
+ // carries the classified code + additive fields (incl. the correctly-nested
+ // providerCode='not_found_error', not the envelope's 'error').
+ const provider = new ClaudeProvider('fake-key', 'claude-sonnet-4-6')
+ const err404 = anthropicApiError(404, 'not_found_error', 'model: x not found')
+ const c = provider.classifyError(err404)
+ const llmError = new LlmError(
+ c.message,
+ 'claude',
+ c.code,
+ c.retryable,
+ undefined,
+ c.httpStatus,
+ c.providerCode
+ )
+ ;(runToolUseLoop as ReturnType<typeof vi.fn>).mockRejectedValueOnce(llmError)
+
+ const deps = createDeps()
+ const task = createTask('Hello')
+ const executor = new TaskExecutor(task, deps)
+
+ await executor.run()
+
+ expect(executor.executorState).toBe('failed')
+ expect(deps.onFail).toHaveBeenCalledWith(
+ task,
+ expect.objectContaining({
+ code: 'LLM_MODEL_NOT_AVAILABLE',
+ retryable: false,
+ provider: 'claude',
+ httpStatus: 404,
+ providerCode: 'not_found_error',
+ })
+ )
+ })
+
it('should enter waiting_approval and call onApprovalNeeded', async () => {
;(runToolUseLoop as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
type: 'need_approval',
diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.ts
index f78308eac..31269d621 100644
--- a/mcp-host/src/agent/taskExecutor.ts
+++ b/mcp-host/src/agent/taskExecutor.ts
@@ -672,6 +672,8 @@ export class TaskExecutor {
message: error.message,
retryable: error.retryable,
provider: error.provider,
+ httpStatus: error.httpStatus,
+ providerCode: error.providerCode,
}
}
return {
diff --git a/mcp-host/src/core/adapters/llmPortAdapter.ts b/mcp-host/src/core/adapters/llmPortAdapter.ts
index 198e9a39c..f83173b6e 100644
--- a/mcp-host/src/core/adapters/llmPortAdapter.ts
+++ b/mcp-host/src/core/adapters/llmPortAdapter.ts
@@ -310,7 +310,9 @@ export class LlmPortAdapter implements LlmPort {
this.providerName,
classified.code,
classified.retryable,
- err as Error
+ err as Error,
+ classified.httpStatus,
+ classified.providerCode
)
}
diff --git a/mcp-host/src/core/errors.ts b/mcp-host/src/core/errors.ts
index 62b5a92b5..7e7f61e94 100644
--- a/mcp-host/src/core/errors.ts
+++ b/mcp-host/src/core/errors.ts
@@ -39,7 +39,15 @@ export class LlmError extends AgentError {
code: LlmErrorCode,
/** True when the caller may safely retry the entire request after a delay. */
public readonly retryable: boolean,
- cause?: Error
+ cause?: Error,
+ /**
+ * Additive diagnostics (spec 02, Pieza A). The provider HTTP status and the
+ * provider-native error code/type that produced `code`, threaded from
+ * `ClassifiedError` down to `TaskError`. Optional so existing call sites
+ * (positional, all args before these) remain unchanged.
+ */
+ public readonly httpStatus?: number,
+ public readonly providerCode?: string
) {
super(message, code, cause)
this.name = 'LlmError'
diff --git a/mcp-host/src/llm/__tests__/bailian.test.ts b/mcp-host/src/llm/__tests__/bailian.test.ts
index 98f2c65a5..c2c5364dc 100644
--- a/mcp-host/src/llm/__tests__/bailian.test.ts
+++ b/mcp-host/src/llm/__tests__/bailian.test.ts
@@ -16,11 +16,11 @@ function makeBailian(model?: string) {
}
describe('BailianProvider (OpenAICompatibleProvider)', () => {
- it('inherits classifyError from OpenAIProvider', () => {
+ it('delegates a plain rate-limit to the shared HTTP classifier', () => {
const bailian = makeBailian('bailian-model')
expect(bailian).toBeInstanceOf(OpenAIProvider)
const result = bailian.classifyError({ status: 429, message: 'rate limited' })
- expect(result).toEqual({
+ expect(result).toMatchObject({
code: LlmErrorCode.RateLimited,
retryable: true,
message: 'rate limited',
diff --git a/mcp-host/src/llm/__tests__/claude.classifyError.test.ts b/mcp-host/src/llm/__tests__/claude.classifyError.test.ts
index b9f4d06eb..9c4d0c105 100644
--- a/mcp-host/src/llm/__tests__/claude.classifyError.test.ts
+++ b/mcp-host/src/llm/__tests__/claude.classifyError.test.ts
@@ -1,12 +1,13 @@
import { describe, expect, it } from 'vitest'
import { LlmErrorCode } from '../../core/errors'
import { ClaudeProvider } from '../claude'
+import { anthropicApiError } from './sdkErrorFixtures'
describe('ClaudeProvider.classifyError', () => {
const provider = new ClaudeProvider('fake-key', 'claude-3-5-sonnet-20241022')
it('classifies 429 as RateLimited, retryable', () => {
- expect(provider.classifyError({ status: 429, message: 'rate limited' })).toEqual({
+ expect(provider.classifyError({ status: 429, message: 'rate limited' })).toMatchObject({
code: LlmErrorCode.RateLimited,
retryable: true,
message: 'rate limited',
@@ -20,13 +21,60 @@ describe('ClaudeProvider.classifyError', () => {
})
it('classifies 529 as ModelOverloaded, retryable', () => {
- expect(provider.classifyError({ status: 529, message: 'overloaded' })).toEqual({
+ expect(provider.classifyError({ status: 529, message: 'overloaded' })).toMatchObject({
code: LlmErrorCode.ModelOverloaded,
retryable: true,
message: 'overloaded',
})
})
+ // Fixtures derived from Anthropic.APIError.generate: the modeled type is
+ // nested at `.error.error.type`. A classifier reading the wrong level would
+ // (a) fall through to the HTTP-status branch — which coincidentally maps some
+ // of these right — and (b) surface providerCode='error' and the ugly
+ // enveloped `.message`. The providerCode + message assertions below are what
+ // catch that regression regardless of the status coincidence.
+ it('classifies error.type not_found_error as ModelNotAvailable, not retryable', () => {
+ const err = anthropicApiError(404, 'not_found_error', 'model: claude-x not found')
+ const c = provider.classifyError(err)
+ expect(c.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c.retryable).toBe(false)
+ expect(c.httpStatus).toBe(404)
+ expect(c.providerCode).toBe('not_found_error')
+ expect(c.message).toBe('model: claude-x not found')
+ })
+
+ it('classifies error.type overloaded_error as ModelOverloaded, retryable', () => {
+ const err = anthropicApiError(529, 'overloaded_error', 'overloaded')
+ const c = provider.classifyError(err)
+ expect(c.code).toBe(LlmErrorCode.ModelOverloaded)
+ expect(c.retryable).toBe(true)
+ expect(c.providerCode).toBe('overloaded_error')
+ expect(c.message).toBe('overloaded')
+ })
+
+ it('classifies error.type billing_error as InsufficientQuota, not retryable', () => {
+ // Anthropic surfaces billing as a 400 in practice (not the documented 402),
+ // so the HTTP-status branch would map this to ApiCallFailed — only the
+ // modeled type gets it to InsufficientQuota. This case fails on `code` too
+ // when the nesting is read wrong.
+ const err = anthropicApiError(400, 'billing_error', 'billing issue')
+ const c = provider.classifyError(err)
+ expect(c.code).toBe(LlmErrorCode.InsufficientQuota)
+ expect(c.retryable).toBe(false)
+ expect(c.providerCode).toBe('billing_error')
+ expect(c.message).toBe('billing issue')
+ })
+
+ it('classifies error.type permission_error as InsufficientQuota (account access), not retryable', () => {
+ const err = anthropicApiError(403, 'permission_error', 'no permission')
+ const c = provider.classifyError(err)
+ expect(c.code).toBe(LlmErrorCode.InsufficientQuota)
+ expect(c.retryable).toBe(false)
+ expect(c.providerCode).toBe('permission_error')
+ expect(c.message).toBe('no permission')
+ })
+
it("reclassifies 400 with 'credit balance is too low' as InsufficientQuota", () => {
const err = {
status: 400,
diff --git a/mcp-host/src/llm/__tests__/errorClassification.test.ts b/mcp-host/src/llm/__tests__/errorClassification.test.ts
index 85e6f5c07..5117b183b 100644
--- a/mcp-host/src/llm/__tests__/errorClassification.test.ts
+++ b/mcp-host/src/llm/__tests__/errorClassification.test.ts
@@ -11,21 +11,65 @@ describe('classifyByHttpStatus', () => {
expect(classifyByHttpStatus(42)).toBeNull()
})
- it('maps 401 and 403 to AuthenticationFailed, not retryable', () => {
- expect(classifyByHttpStatus({ status: 401, message: 'unauthorized' })).toEqual({
+ it('maps 401 to AuthenticationFailed, not retryable', () => {
+ expect(classifyByHttpStatus({ status: 401, message: 'unauthorized' })).toMatchObject({
code: LlmErrorCode.AuthenticationFailed,
retryable: false,
message: 'unauthorized',
})
- expect(classifyByHttpStatus({ status: 403, message: 'forbidden' })).toEqual({
- code: LlmErrorCode.AuthenticationFailed,
+ })
+
+ it('maps 403 to InsufficientQuota (account/billing access), NOT AuthenticationFailed', () => {
+ // 403 is separated from 401: a bad credential is 401 (a rotatable key); 403
+ // is account access / billing / permission and must not masquerade as a
+ // credential failure (which would silently divert traffic via the `auth`
+ // failover class).
+ const c = classifyByHttpStatus({ status: 403, message: 'forbidden' })
+ expect(c?.code).toBe(LlmErrorCode.InsufficientQuota)
+ expect(c?.retryable).toBe(false)
+ expect(c?.httpStatus).toBe(403)
+ })
+
+ it('maps 404 to ModelNotAvailable, NOT retryable', () => {
+ // Model retired OR not accessible to this account — indistinguishable by
+ // API. Non-retryable so the tool-use loop does not retry it, and NOT a
+ // failover trigger so it does not silently divert cross-provider.
+ const c = classifyByHttpStatus({ status: 404, message: 'model not found' })
+ expect(c?.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c?.retryable).toBe(false)
+ expect(c?.httpStatus).toBe(404)
+ })
+
+ it('maps body-level model_not_found (code or type) to ModelNotAvailable', () => {
+ expect(
+ classifyByHttpStatus({ status: 400, error: { code: 'model_not_found', message: 'gone' } })
+ ).toMatchObject({
+ code: LlmErrorCode.ModelNotAvailable,
retryable: false,
- message: 'forbidden',
+ providerCode: 'model_not_found',
+ })
+ expect(
+ classifyByHttpStatus({ status: 400, error: { type: 'model_not_found', message: 'gone' } })
+ ).toMatchObject({ code: LlmErrorCode.ModelNotAvailable, retryable: false })
+ })
+
+ it('maps body-level invalid_api_key to AuthenticationFailed', () => {
+ expect(
+ classifyByHttpStatus({ status: 401, error: { code: 'invalid_api_key', message: 'bad key' } })
+ ).toMatchObject({ code: LlmErrorCode.AuthenticationFailed, retryable: false })
+ })
+
+ it('propagates httpStatus and providerCode onto the ClassifiedError', () => {
+ const c = classifyByHttpStatus({
+ status: 429,
+ error: { code: 'rate_limit', message: 'slow down' },
})
+ expect(c?.httpStatus).toBe(429)
+ expect(c?.providerCode).toBe('rate_limit')
})
it('maps 402 to InsufficientQuota, not retryable', () => {
- expect(classifyByHttpStatus({ status: 402, message: 'payment required' })).toEqual({
+ expect(classifyByHttpStatus({ status: 402, message: 'payment required' })).toMatchObject({
code: LlmErrorCode.InsufficientQuota,
retryable: false,
message: 'payment required',
@@ -33,7 +77,7 @@ describe('classifyByHttpStatus', () => {
})
it('maps 429 to RateLimited, retryable', () => {
- expect(classifyByHttpStatus({ status: 429, message: 'rate limited' })).toEqual({
+ expect(classifyByHttpStatus({ status: 429, message: 'rate limited' })).toMatchObject({
code: LlmErrorCode.RateLimited,
retryable: true,
message: 'rate limited',
@@ -41,12 +85,12 @@ describe('classifyByHttpStatus', () => {
})
it('maps 503 and 529 to ModelOverloaded, retryable', () => {
- expect(classifyByHttpStatus({ status: 503, message: 'unavailable' })).toEqual({
+ expect(classifyByHttpStatus({ status: 503, message: 'unavailable' })).toMatchObject({
code: LlmErrorCode.ModelOverloaded,
retryable: true,
message: 'unavailable',
})
- expect(classifyByHttpStatus({ status: 529, message: 'overloaded' })).toEqual({
+ expect(classifyByHttpStatus({ status: 529, message: 'overloaded' })).toMatchObject({
code: LlmErrorCode.ModelOverloaded,
retryable: true,
message: 'overloaded',
@@ -63,7 +107,7 @@ describe('classifyByHttpStatus', () => {
})
it('maps 400 without quota signal to ApiCallFailed, NOT retryable', () => {
- expect(classifyByHttpStatus({ status: 400, message: 'bad request' })).toEqual({
+ expect(classifyByHttpStatus({ status: 400, message: 'bad request' })).toMatchObject({
code: LlmErrorCode.ApiCallFailed,
retryable: false,
message: 'bad request',
@@ -72,7 +116,7 @@ describe('classifyByHttpStatus', () => {
it('recognizes body-level insufficient_quota via error.code', () => {
const err = { status: 429, error: { code: 'insufficient_quota', message: 'out of credit' } }
- expect(classifyByHttpStatus(err)).toEqual({
+ expect(classifyByHttpStatus(err)).toMatchObject({
code: LlmErrorCode.InsufficientQuota,
retryable: false,
message: 'out of credit',
@@ -81,7 +125,7 @@ describe('classifyByHttpStatus', () => {
it('recognizes body-level insufficient_quota via error.type', () => {
const err = { status: 429, error: { type: 'insufficient_quota', message: 'out of credit' } }
- expect(classifyByHttpStatus(err)).toEqual({
+ expect(classifyByHttpStatus(err)).toMatchObject({
code: LlmErrorCode.InsufficientQuota,
retryable: false,
message: 'out of credit',
diff --git a/mcp-host/src/llm/__tests__/modelNotAvailable.observable.test.ts b/mcp-host/src/llm/__tests__/modelNotAvailable.observable.test.ts
new file mode 100644
index 000000000..53069ebf6
--- /dev/null
+++ b/mcp-host/src/llm/__tests__/modelNotAvailable.observable.test.ts
@@ -0,0 +1,147 @@
+/**
+ * Observable-behavior regression tests for the G2 gap (spec 02, Pieza A):
+ * a provider 404 (retired / inaccessible model) MUST classify as
+ * `ModelNotAvailable` (non-retryable) so that, observably:
+ *
+ * 1. the failover engine does NOT silently divert traffic to another
+ * provider (ModelNotAvailable → no failover class), and
+ * 2. the tool-use loop does NOT retry it as a transient transport error.
+ *
+ * These assert the OBSERVABLE outcome (T4) — did we failover? did we retry?
+ * what code surfaces? — not `classifyByHttpStatus` in isolation. The
+ * `ClassifiedError` / `LlmError` are DERIVED from the real provider classifiers
+ * (T1), never hand-built.
+ *
+ * Coverage spans all four classifier arms: OpenAI-compatible, Claude, Vertex
+ * (google driver), and Bedrock.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { LlmError, LlmErrorCode } from '../../core/errors'
+import {
+ buildTestConfig,
+ createMockReasoning,
+} from '../../core/orchestration/__tests__/toolUseLoopRetryableTestUtils'
+import { runToolUseLoop } from '../../core/orchestration/toolUseLoop'
+import { ClaudeProvider } from '../claude'
+import { classifyBedrockError } from '../drivers/bedrockConverse'
+import { classifyGoogleError } from '../drivers/googleGenerative'
+import { FailoverEngine } from '../failover/engine'
+import type { LlmPolicy, ModelPair } from '../failover/types'
+import { OpenAICompatibleProvider } from '../openaiCompatible'
+import type { ClassifiedError } from '../types'
+import { anthropicApiError, openaiApiError } from './sdkErrorFixtures'
+
+const PRIMARY: ModelPair = { provider: 'claude', model: 'claude-sonnet-4-6' }
+
+function policy(): LlmPolicy {
+ return {
+ cooldownSeconds: 300,
+ triggerOn: ['insufficient_quota', 'auth', 'provider_unavailable', 'rate_limited'],
+ fallbacks: [{ provider: 'openai', model: 'gpt-5.4' }],
+ }
+}
+
+type Classifier = (err: unknown) => ClassifiedError
+
+const zai = new OpenAICompatibleProvider(
+ { id: 'zai', baseURL: 'https://example.invalid', defaultModel: 'glm-4' },
+ 'fake-key'
+)
+const claude = new ClaudeProvider('fake-key', 'claude-sonnet-4-6')
+
+// Real SDK-shaped 404 payloads (the boundary these classifiers consume), one
+// per arm. The OpenAI/Anthropic arms derive from their SDK error constructors
+// (T1); Vertex/Bedrock use plain GCP/AWS-shaped errors (their producers are not
+// exposed SDK error classes). The ClassifiedError/LlmError below are produced
+// by the real classifiers, not hand-written.
+const CASES: ReadonlyArray<[string, Classifier, string, unknown]> = [
+ [
+ 'openai-compat (zai)',
+ (e: unknown) => zai.classifyError(e),
+ 'zai',
+ openaiApiError(404, { code: '1211', message: 'The model does not exist' }),
+ ],
+ [
+ 'claude',
+ (e: unknown) => claude.classifyError(e),
+ 'claude',
+ anthropicApiError(404, 'not_found_error', 'model: claude-x not found'),
+ ],
+ [
+ 'vertex (google)',
+ classifyGoogleError,
+ 'vertex',
+ { status: 404, message: 'Publisher Model `x` was not found' },
+ ],
+ [
+ 'bedrock',
+ classifyBedrockError,
+ 'bedrock',
+ {
+ name: 'ResourceNotFoundException',
+ message: 'The provided model identifier is invalid',
+ $metadata: { httpStatusCode: 404 },
+ },
+ ],
+]
+
+function toLlmError(classify: Classifier, provider: string, err: unknown): LlmError {
+ // Mirrors LlmPortAdapter.handleProviderError construction.
+ const c = classify(err)
+ return new LlmError(
+ c.message,
+ provider,
+ c.code,
+ c.retryable,
+ err as Error,
+ c.httpStatus,
+ c.providerCode
+ )
+}
+
+describe('404 → ModelNotAvailable: does NOT trigger cross-provider failover', () => {
+ it.each(CASES)('%s', async (_label, classify, _provider, err404) => {
+ // Sanity: the real classifier produces the ambiguous, non-retryable class.
+ expect(classify(err404).code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(classify(err404).retryable).toBe(false)
+
+ const engine = new FailoverEngine(policy())
+ const fallbackRun = vi.fn()
+ const run = engine.run(
+ PRIMARY,
+ target =>
+ target.kind === 'primary'
+ ? () => Promise.reject(err404)
+ : () => {
+ fallbackRun()
+ return Promise.resolve('fallback-served')
+ },
+ classify
+ )
+
+ // Propagates the original error — never masked by a fallback.
+ await expect(run).rejects.toBe(err404)
+ // The observable proof of "no silent failover": the fallback never ran.
+ expect(fallbackRun).not.toHaveBeenCalled()
+ })
+})
+
+describe('404 → ModelNotAvailable: is NOT retried by the tool-use loop', () => {
+ it.each(CASES)('%s', async (_label, classify, provider, err404) => {
+ const reasoning = createMockReasoning([
+ { type: 'error', error: toLlmError(classify, provider, err404) },
+ ])
+
+ const result = await runToolUseLoop(buildTestConfig(reasoning, []), [
+ { role: 'user', content: 'hi' },
+ ])
+
+ expect(result.type).toBe('error')
+ if (result.type === 'error') {
+ expect((result.error as LlmError).code).toBe(LlmErrorCode.ModelNotAvailable)
+ }
+ // A retryable transport error would call respondWithTools twice; a
+ // non-retryable ModelNotAvailable must be surfaced after a single call.
+ expect(reasoning.respondWithTools).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/mcp-host/src/llm/__tests__/openai.classifyError.test.ts b/mcp-host/src/llm/__tests__/openai.classifyError.test.ts
index cae5a489b..11a7c555e 100644
--- a/mcp-host/src/llm/__tests__/openai.classifyError.test.ts
+++ b/mcp-host/src/llm/__tests__/openai.classifyError.test.ts
@@ -7,7 +7,7 @@ describe('OpenAIProvider.classifyError', () => {
it('classifies 429 as RateLimited, retryable', () => {
const result = provider.classifyError({ status: 429, message: 'rate limit exceeded' })
- expect(result).toEqual({
+ expect(result).toMatchObject({
code: LlmErrorCode.RateLimited,
retryable: true,
message: 'rate limit exceeded',
@@ -19,7 +19,7 @@ describe('OpenAIProvider.classifyError', () => {
status: 429,
error: { code: 'insufficient_quota', message: 'You exceeded your current quota' },
}
- expect(provider.classifyError(err)).toEqual({
+ expect(provider.classifyError(err)).toMatchObject({
code: LlmErrorCode.InsufficientQuota,
retryable: false,
message: 'You exceeded your current quota',
diff --git a/mcp-host/src/llm/__tests__/openaiCompatible.classifyError.test.ts b/mcp-host/src/llm/__tests__/openaiCompatible.classifyError.test.ts
new file mode 100644
index 000000000..c2743bd72
--- /dev/null
+++ b/mcp-host/src/llm/__tests__/openaiCompatible.classifyError.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest'
+import { LlmErrorCode } from '../../core/errors'
+import { OpenAICompatibleProvider } from '../openaiCompatible'
+import { openaiApiError } from './sdkErrorFixtures'
+
+const zai = new OpenAICompatibleProvider(
+ { id: 'zai', baseURL: 'https://example.invalid', defaultModel: 'glm-4' },
+ 'fake-key'
+)
+const bailian = new OpenAICompatibleProvider(
+ { id: 'bailian', baseURL: 'https://example.invalid', defaultModel: 'qwen-max' },
+ 'fake-key'
+)
+
+// Fixtures derived from OpenAI.APIError.generate (T1): the provider-native code
+// lands at `err.error.code`, the level the override reads. Deriving guards
+// against the same nesting mismatch that broke the Claude arm.
+describe('OpenAICompatibleProvider.classifyError', () => {
+ it('maps z.ai model-not-available codes (1211/1220) to ModelNotAvailable', () => {
+ for (const code of ['1211', '1220']) {
+ const c = zai.classifyError(openaiApiError(404, { code, message: 'model not available' }))
+ expect(c.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c.retryable).toBe(false)
+ expect(c.providerCode).toBe(code)
+ }
+ })
+
+ it('maps z.ai billing code 1113 inside a 429 to InsufficientQuota (not a retryable rate-limit)', () => {
+ const c = zai.classifyError(
+ openaiApiError(429, { code: '1113', message: 'insufficient balance' })
+ )
+ expect(c.code).toBe(LlmErrorCode.InsufficientQuota)
+ expect(c.retryable).toBe(false)
+ })
+
+ it('maps Bailian ModelNotFound / Model.AccessDenied to ModelNotAvailable', () => {
+ for (const code of ['ModelNotFound', 'Model.AccessDenied']) {
+ const c = bailian.classifyError(openaiApiError(404, { code, message: 'no access to model' }))
+ expect(c.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c.retryable).toBe(false)
+ }
+ })
+
+ it('maps Bailian Arrearage (billing) to InsufficientQuota, not retryable', () => {
+ const c = bailian.classifyError(openaiApiError(429, { code: 'Arrearage', message: 'arrears' }))
+ expect(c.code).toBe(LlmErrorCode.InsufficientQuota)
+ expect(c.retryable).toBe(false)
+ })
+
+ it('falls through to the shared HTTP classifier for generic 404', () => {
+ const c = zai.classifyError(openaiApiError(404, { message: 'not found' }))
+ expect(c.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c.retryable).toBe(false)
+ })
+
+ it('falls through to the shared HTTP classifier for a plain rate-limit 429', () => {
+ const c = zai.classifyError(openaiApiError(429, { message: 'rate limited' }))
+ expect(c.code).toBe(LlmErrorCode.RateLimited)
+ expect(c.retryable).toBe(true)
+ })
+
+ it('falls back to unknown classification for a plain Error (does not throw)', () => {
+ const c = zai.classifyError(new Error('ECONNRESET'))
+ expect(c.code).toBe(LlmErrorCode.ApiCallFailed)
+ expect(c.retryable).toBe(true)
+ })
+})
diff --git a/mcp-host/src/llm/__tests__/sdkErrorFixtures.ts b/mcp-host/src/llm/__tests__/sdkErrorFixtures.ts
new file mode 100644
index 000000000..57c27adb5
--- /dev/null
+++ b/mcp-host/src/llm/__tests__/sdkErrorFixtures.ts
@@ -0,0 +1,49 @@
+/**
+ * Test fixtures DERIVED from the real provider SDK error constructors (T1) —
+ * never hand-built object literals. This matters because the two SDKs nest the
+ * error body differently, and hand-writing the shape encodes a belief about
+ * that nesting rather than the truth:
+ *
+ * - `Anthropic.APIError.generate(...)` stores the FULL response envelope on
+ * `.error` → `{ type:'error', error:{ type, message } }` (modeled type at
+ * `.error.error.type`).
+ * - `OpenAI.APIError.generate(...)` stores only the INNER error object on
+ * `.error` → `{ code, message, type }` (code at `.error.code`).
+ *
+ * Deriving from the producers guarantees the classifiers under test consume the
+ * exact shape the SDKs emit.
+ */
+import Anthropic from '@anthropic-ai/sdk'
+import OpenAI from 'openai'
+
+/**
+ * A real `Anthropic.APIError` (e.g. `NotFoundError`) carrying the modeled
+ * `error.type` nested inside the response envelope, exactly as the SDK builds
+ * it from an HTTP response.
+ */
+export function anthropicApiError(status: number, type: string, message: string): unknown {
+ return Anthropic.APIError.generate(
+ status,
+ { type: 'error', error: { type, message } },
+ undefined,
+ {}
+ )
+}
+
+/**
+ * A real `OpenAI.APIError` carrying the provider-native `error.code` (used by
+ * OpenAI-compatible providers such as z.ai / Bailian). `OpenAI.APIError.generate`
+ * returns an `APIConnectionError` unless `headers` is truthy, so a truthy
+ * headers object (the SDK types it as `Record<string, string>`) is always passed.
+ */
+export function openaiApiError(
+ status: number,
+ body: { code?: string; message: string; type?: string }
+): unknown {
+ return OpenAI.APIError.generate(
+ status,
+ { error: { code: body.code, message: body.message, type: body.type } },
+ undefined,
+ {}
+ )
+}
diff --git a/mcp-host/src/llm/__tests__/zai.test.ts b/mcp-host/src/llm/__tests__/zai.test.ts
index 28289a249..cf2f9c71f 100644
--- a/mcp-host/src/llm/__tests__/zai.test.ts
+++ b/mcp-host/src/llm/__tests__/zai.test.ts
@@ -12,11 +12,11 @@ function makeZai(model?: string) {
}
describe('ZaiProvider (OpenAICompatibleProvider)', () => {
- it('inherits classifyError from OpenAIProvider', () => {
+ it('delegates a plain rate-limit to the shared HTTP classifier', () => {
const zai = makeZai('zai-model')
expect(zai).toBeInstanceOf(OpenAIProvider)
const result = zai.classifyError({ status: 429, message: 'rate limited' })
- expect(result).toEqual({
+ expect(result).toMatchObject({
code: LlmErrorCode.RateLimited,
retryable: true,
message: 'rate limited',
diff --git a/mcp-host/src/llm/claude.ts b/mcp-host/src/llm/claude.ts
index 4385cd200..8162501b9 100644
--- a/mcp-host/src/llm/claude.ts
+++ b/mcp-host/src/llm/claude.ts
@@ -53,6 +53,49 @@ export class ClaudeProvider implements SingleTurnProvider {
}
classifyError(err: unknown): ClassifiedError {
+ // Anthropic surfaces a modeled `error.type` that is more precise than the
+ // HTTP status (a live model can still 404 with `not_found_error`). Classify
+ // by type FIRST; the set is open by contract, so unmatched types fall
+ // through to the status-based classifier below. (spec 02 §3.1)
+ //
+ // Nesting note: on `Anthropic.APIError`, `.error` is the FULL response
+ // envelope `{ type:'error', error:{ type, message } }`, so the modeled type
+ // lives at `.error.error.type` (`.error.type` is the constant 'error'). Read
+ // the inner level first, with the outer level as a defensive fallback for
+ // any non-enveloped shape.
+ const anthropicErr = err as {
+ status?: unknown
+ message?: string
+ error?: { type?: string; message?: string; error?: { type?: string; message?: string } }
+ }
+ const bodyType = anthropicErr?.error?.error?.type ?? anthropicErr?.error?.type
+ const httpStatus = typeof anthropicErr?.status === 'number' ? anthropicErr.status : undefined
+ const rawMsg =
+ anthropicErr?.error?.error?.message ??
+ anthropicErr?.error?.message ??
+ anthropicErr?.message ??
+ 'Unknown Claude error'
+ if (bodyType) {
+ const byType = ((): ClassifiedError | null => {
+ switch (bodyType) {
+ case 'not_found_error':
+ // Retired or inaccessible model — ambiguous by design; non-retryable
+ // and NOT a failover trigger.
+ return { code: LlmErrorCode.ModelNotAvailable, retryable: false, message: rawMsg }
+ case 'overloaded_error':
+ return { code: LlmErrorCode.ModelOverloaded, retryable: true, message: rawMsg }
+ case 'billing_error':
+ case 'permission_error':
+ // Account access / billing, not a rotatable credential (kept off
+ // AuthenticationFailed — see the 403 split in errorClassification).
+ return { code: LlmErrorCode.InsufficientQuota, retryable: false, message: rawMsg }
+ default:
+ return null
+ }
+ })()
+ if (byType) return { ...byType, httpStatus, providerCode: bodyType }
+ }
+
const httpClassification = classifyByHttpStatus(err)
if (httpClassification) {
// Anthropic quirk: insufficient credit is reported as HTTP 400
@@ -65,6 +108,9 @@ export class ClaudeProvider implements SingleTurnProvider {
...httpClassification,
code: LlmErrorCode.InsufficientQuota,
retryable: false,
+ // Prefer the inner-level message: on a real Anthropic envelope the
+ // shared classifier only sees the outer `${status} {json}` string.
+ message: rawMsg,
}
}
return httpClassification
diff --git a/mcp-host/src/llm/drivers/__tests__/bedrockConverse.test.ts b/mcp-host/src/llm/drivers/__tests__/bedrockConverse.test.ts
index c72e1c7da..65c177bb4 100644
--- a/mcp-host/src/llm/drivers/__tests__/bedrockConverse.test.ts
+++ b/mcp-host/src/llm/drivers/__tests__/bedrockConverse.test.ts
@@ -224,6 +224,7 @@ describe('classifyBedrockError', () => {
['AccessDeniedException', LlmErrorCode.AuthenticationFailed, false],
['UnrecognizedClientException', LlmErrorCode.AuthenticationFailed, false],
['ServiceQuotaExceededException', LlmErrorCode.InsufficientQuota, false],
+ ['ResourceNotFoundException', LlmErrorCode.ModelNotAvailable, false],
['ValidationException', LlmErrorCode.ApiCallFailed, false],
['ServiceUnavailableException', LlmErrorCode.ModelOverloaded, true],
['InternalServerException', LlmErrorCode.ModelOverloaded, true],
@@ -245,6 +246,30 @@ describe('classifyBedrockError', () => {
expect(c.retryable).toBe(true)
})
+ it('maps an unmodeled name with a 404 $metadata status to ModelNotAvailable', () => {
+ const c = classifyBedrockError({
+ name: 'SomeNewException',
+ message: 'model gone',
+ $metadata: { httpStatusCode: 404 },
+ })
+ expect(c.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c.retryable).toBe(false)
+ // Diagnostics still propagate on the $metadata fallback path.
+ expect(c.httpStatus).toBe(404)
+ expect(c.providerCode).toBe('SomeNewException')
+ })
+
+ it('propagates httpStatus + providerCode (exception name) on a modeled error', () => {
+ const c = classifyBedrockError({
+ name: 'ResourceNotFoundException',
+ message: 'model gone',
+ $metadata: { httpStatusCode: 404 },
+ })
+ expect(c.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c.httpStatus).toBe(404)
+ expect(c.providerCode).toBe('ResourceNotFoundException')
+ })
+
it('falls back to ApiCallFailed(retryable) for an unrecognized shape', () => {
const c = classifyBedrockError(new Error('socket hang up'))
expect(c.code).toBe(LlmErrorCode.ApiCallFailed)
diff --git a/mcp-host/src/llm/drivers/__tests__/googleGenerative.test.ts b/mcp-host/src/llm/drivers/__tests__/googleGenerative.test.ts
index 0e8d4907c..c867226f0 100644
--- a/mcp-host/src/llm/drivers/__tests__/googleGenerative.test.ts
+++ b/mcp-host/src/llm/drivers/__tests__/googleGenerative.test.ts
@@ -158,6 +158,7 @@ describe('classifyGoogleError', () => {
[{ status: 429 }, LlmErrorCode.RateLimited, true],
[{ status: 403 }, LlmErrorCode.AuthenticationFailed, false],
[{ status: 401 }, LlmErrorCode.AuthenticationFailed, false],
+ [{ status: 404 }, LlmErrorCode.ModelNotAvailable, false],
[{ status: 503 }, LlmErrorCode.ModelOverloaded, true],
[{ status: 400 }, LlmErrorCode.ApiCallFailed, false],
] as const)('maps http status %o', (err, code, retryable) => {
@@ -170,6 +171,7 @@ describe('classifyGoogleError', () => {
['RESOURCE_EXHAUSTED', LlmErrorCode.RateLimited, true],
['PERMISSION_DENIED', LlmErrorCode.AuthenticationFailed, false],
['UNAUTHENTICATED', LlmErrorCode.AuthenticationFailed, false],
+ ['NOT_FOUND', LlmErrorCode.ModelNotAvailable, false],
['UNAVAILABLE', LlmErrorCode.ModelOverloaded, true],
['INVALID_ARGUMENT', LlmErrorCode.ApiCallFailed, false],
] as const)('maps gRPC status string %s', (status, code, retryable) => {
@@ -178,6 +180,18 @@ describe('classifyGoogleError', () => {
expect(c.retryable).toBe(retryable)
})
+ it('propagates httpStatus for a numeric-status error', () => {
+ const c = classifyGoogleError({ status: 404, message: 'model gone' })
+ expect(c.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c.httpStatus).toBe(404)
+ })
+
+ it('propagates the gRPC status string as providerCode', () => {
+ const c = classifyGoogleError({ status: 'NOT_FOUND', message: 'model gone' })
+ expect(c.code).toBe(LlmErrorCode.ModelNotAvailable)
+ expect(c.providerCode).toBe('NOT_FOUND')
+ })
+
it('falls back to ApiCallFailed(retryable) for an unrecognized shape', () => {
const c = classifyGoogleError(new Error('socket hang up'))
expect(c.code).toBe(LlmErrorCode.ApiCallFailed)
diff --git a/mcp-host/src/llm/drivers/bedrockConverse.ts b/mcp-host/src/llm/drivers/bedrockConverse.ts
index 581948cf7..6c6e0c593 100644
--- a/mcp-host/src/llm/drivers/bedrockConverse.ts
+++ b/mcp-host/src/llm/drivers/bedrockConverse.ts
@@ -311,31 +311,44 @@ export function classifyBedrockError(err: unknown): ClassifiedError {
$metadata?: { httpStatusCode?: number }
}
const message = e.message ?? 'Unknown Bedrock error'
+ // Additive diagnostics threaded to TaskError (spec 02, Pieza A): the HTTP
+ // status from $metadata and the modeled exception name as the provider code.
+ const diag: Pick<ClassifiedError, 'httpStatus' | 'providerCode'> = {
+ httpStatus: e.$metadata?.httpStatusCode,
+ providerCode: e.name,
+ }
switch (e.name) {
case 'ThrottlingException':
case 'TooManyRequestsException':
- return { code: LlmErrorCode.RateLimited, retryable: true, message }
+ return { code: LlmErrorCode.RateLimited, retryable: true, message, ...diag }
case 'AccessDeniedException':
case 'UnrecognizedClientException':
case 'IncompleteSignatureException':
case 'InvalidSignatureException':
- return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message }
+ return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message, ...diag }
case 'ServiceQuotaExceededException':
- return { code: LlmErrorCode.InsufficientQuota, retryable: false, message }
+ return { code: LlmErrorCode.InsufficientQuota, retryable: false, message, ...diag }
+ case 'ResourceNotFoundException':
+ // Invalid / retired model identifier — non-retryable, NOT a failover
+ // trigger (spec 02 §3.1). The $metadata 404 fallback below covers the
+ // same case when the modeled name is absent.
+ return { code: LlmErrorCode.ModelNotAvailable, retryable: false, message, ...diag }
case 'ValidationException':
- return { code: LlmErrorCode.ApiCallFailed, retryable: false, message }
+ return { code: LlmErrorCode.ApiCallFailed, retryable: false, message, ...diag }
case 'ModelTimeoutException':
case 'ModelNotReadyException':
case 'ServiceUnavailableException':
case 'InternalServerException':
- return { code: LlmErrorCode.ModelOverloaded, retryable: true, message }
+ return { code: LlmErrorCode.ModelOverloaded, retryable: true, message, ...diag }
}
const status = e.$metadata?.httpStatusCode
if (status !== undefined) {
+ // Attach the modeled name as providerCode; classifyByHttpStatus already
+ // fills httpStatus from the status we pass.
const byStatus = classifyByHttpStatus({ status, message })
- if (byStatus) return byStatus
+ if (byStatus) return { ...byStatus, providerCode: e.name ?? byStatus.providerCode }
}
return classifyUnknown(err)
}
diff --git a/mcp-host/src/llm/drivers/googleGenerative.ts b/mcp-host/src/llm/drivers/googleGenerative.ts
index 943422b09..9783cf942 100644
--- a/mcp-host/src/llm/drivers/googleGenerative.ts
+++ b/mcp-host/src/llm/drivers/googleGenerative.ts
@@ -296,30 +296,45 @@ export function classifyGoogleError(err: unknown): ClassifiedError {
(typeof e.code === 'string' && e.code) ||
e.error?.status ||
undefined
+ // Additive diagnostics threaded to TaskError (spec 02, Pieza A): the numeric
+ // HTTP status and the provider-native code (the gRPC status string, e.g.
+ // NOT_FOUND / PERMISSION_DENIED, when GCP surfaced one).
+ const diag: Pick<ClassifiedError, 'httpStatus' | 'providerCode'> = {
+ httpStatus,
+ providerCode: statusString || undefined,
+ }
if (httpStatus !== undefined) {
- if (httpStatus === 429) return { code: LlmErrorCode.RateLimited, retryable: true, message }
+ if (httpStatus === 429)
+ return { code: LlmErrorCode.RateLimited, retryable: true, message, ...diag }
if (httpStatus === 401 || httpStatus === 403)
- return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message }
+ return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message, ...diag }
+ // Retired or inaccessible model — non-retryable, NOT a failover trigger
+ // (spec 02 §3.1). Same gap the shared classifier closes for the other arms.
+ if (httpStatus === 404)
+ return { code: LlmErrorCode.ModelNotAvailable, retryable: false, message, ...diag }
if (httpStatus >= 500 && httpStatus < 600)
- return { code: LlmErrorCode.ModelOverloaded, retryable: true, message }
- if (httpStatus === 400) return { code: LlmErrorCode.ApiCallFailed, retryable: false, message }
+ return { code: LlmErrorCode.ModelOverloaded, retryable: true, message, ...diag }
+ if (httpStatus === 400)
+ return { code: LlmErrorCode.ApiCallFailed, retryable: false, message, ...diag }
}
switch (statusString) {
case 'RESOURCE_EXHAUSTED':
- return { code: LlmErrorCode.RateLimited, retryable: true, message }
+ return { code: LlmErrorCode.RateLimited, retryable: true, message, ...diag }
case 'PERMISSION_DENIED':
case 'UNAUTHENTICATED':
- return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message }
+ return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message, ...diag }
case 'UNAVAILABLE':
case 'INTERNAL':
case 'DEADLINE_EXCEEDED':
- return { code: LlmErrorCode.ModelOverloaded, retryable: true, message }
+ return { code: LlmErrorCode.ModelOverloaded, retryable: true, message, ...diag }
+ case 'NOT_FOUND':
+ // gRPC equivalent of a 404 — retired/inaccessible model.
+ return { code: LlmErrorCode.ModelNotAvailable, retryable: false, message, ...diag }
case 'INVALID_ARGUMENT':
case 'FAILED_PRECONDITION':
- case 'NOT_FOUND':
- return { code: LlmErrorCode.ApiCallFailed, retryable: false, message }
+ return { code: LlmErrorCode.ApiCallFailed, retryable: false, message, ...diag }
}
return classifyUnknown(err)
diff --git a/mcp-host/src/llm/errorClassification.ts b/mcp-host/src/llm/errorClassification.ts
index 734476384..9f5a59ba9 100644
--- a/mcp-host/src/llm/errorClassification.ts
+++ b/mcp-host/src/llm/errorClassification.ts
@@ -24,33 +24,59 @@ export function classifyByHttpStatus(err: unknown): ClassifiedError | null {
const rawMsg = e.error?.message ?? e.message ?? 'Unknown LLM error'
const bodyCode = e.error?.code
const bodyType = e.error?.type
+ // Additive diagnostics threaded onto every classification (spec 02, Pieza A).
+ const diag: Pick<ClassifiedError, 'httpStatus' | 'providerCode'> = {
+ httpStatus: typeof e.status === 'number' ? e.status : undefined,
+ providerCode: bodyCode ?? bodyType,
+ }
// Body-level signals take precedence over raw HTTP status. To add new
// body-code mappings (e.g., "rate_limit_exceeded", "context_length_exceeded"),
// extend this if-block — do NOT add them to the switch below, which only
// considers HTTP status.
if (bodyCode === 'insufficient_quota' || bodyType === 'insufficient_quota') {
- return { code: LlmErrorCode.InsufficientQuota, retryable: false, message: rawMsg }
+ return { code: LlmErrorCode.InsufficientQuota, retryable: false, message: rawMsg, ...diag }
+ }
+ // Model retired OR not accessible to this account — providers surface it as a
+ // body code even on a non-404 status. Ambiguous by design (the runtime never
+ // concludes the catalog is stale — see spec 02 §3.1); it only reports "not
+ // available". Non-retryable and NOT a failover trigger.
+ if (bodyCode === 'model_not_found' || bodyType === 'model_not_found') {
+ return { code: LlmErrorCode.ModelNotAvailable, retryable: false, message: rawMsg, ...diag }
+ }
+ // A genuinely invalid credential (distinct from a 403 access/billing denial).
+ if (bodyCode === 'invalid_api_key' || bodyType === 'invalid_api_key') {
+ return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message: rawMsg, ...diag }
}
switch (e.status) {
case 401:
+ // A rotatable bad credential — kept on `auth` failover class.
+ return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message: rawMsg, ...diag }
case 403:
- return { code: LlmErrorCode.AuthenticationFailed, retryable: false, message: rawMsg }
+ // 403 ≠ 401: not a bad key value but account access / billing / permission.
+ // Split off AuthenticationFailed so a forbidden model/account does not
+ // masquerade as a rotatable-credential failure (spec 02 §3.1).
+ return { code: LlmErrorCode.InsufficientQuota, retryable: false, message: rawMsg, ...diag }
case 402:
- return { code: LlmErrorCode.InsufficientQuota, retryable: false, message: rawMsg }
+ return { code: LlmErrorCode.InsufficientQuota, retryable: false, message: rawMsg, ...diag }
+ case 404:
+ // Retired or inaccessible model — indistinguishable by API (spec 02 §3.1).
+ // Non-retryable so the loop does not retry, and mapped to `null` failover
+ // class so it does not silently divert cross-provider.
+ return { code: LlmErrorCode.ModelNotAvailable, retryable: false, message: rawMsg, ...diag }
case 429:
- return { code: LlmErrorCode.RateLimited, retryable: true, message: rawMsg }
+ return { code: LlmErrorCode.RateLimited, retryable: true, message: rawMsg, ...diag }
case 503:
case 529:
- return { code: LlmErrorCode.ModelOverloaded, retryable: true, message: rawMsg }
+ return { code: LlmErrorCode.ModelOverloaded, retryable: true, message: rawMsg, ...diag }
}
if (typeof e.status === 'number' && e.status >= 500 && e.status < 600) {
- return { code: LlmErrorCode.ModelOverloaded, retryable: true, message: rawMsg }
+ return { code: LlmErrorCode.ModelOverloaded, retryable: true, message: rawMsg, ...diag }
}
if (e.status === 400) {
- return { code: LlmErrorCode.ApiCallFailed, retryable: false, message: rawMsg }
+ return { code: LlmErrorCode.ApiCallFailed, retryable: false, message: rawMsg, ...diag }
}
return null
}
diff --git a/mcp-host/src/llm/openaiCompatible.ts b/mcp-host/src/llm/openaiCompatible.ts
index d7a9609d5..41256f6d8 100644
--- a/mcp-host/src/llm/openaiCompatible.ts
+++ b/mcp-host/src/llm/openaiCompatible.ts
@@ -31,6 +31,7 @@
* third-party arm is conservative.
*/
import OpenAI from 'openai'
+import { LlmErrorCode } from '../core/errors'
import type {
CompletionResponse,
ChatMessage as CoreChatMessage,
@@ -39,6 +40,7 @@ import type {
} from '../core/types'
import { OpenAIProvider } from './openai'
import type { LlmProvider } from './registryCore'
+import type { ClassifiedError } from './types'
/**
* Clamp/normalize call options to the portable subset every OpenAI-compatible
@@ -65,6 +67,17 @@ function toPortableOptions<T extends { temperature?: number; tool_choice?: strin
return next
}
+/**
+ * Provider-native error codes that mean "this model does not work for you right
+ * now" (retired or inaccessible — ambiguous by design, spec 02 §3.1). z.ai uses
+ * numeric codes; Bailian native slugs. Both compat-mode APIs surface them in
+ * `error.code`.
+ */
+const MODEL_NOT_AVAILABLE_CODES = new Set(['1211', '1220', 'ModelNotFound', 'Model.AccessDenied'])
+
+/** Provider-native billing/quota codes (z.ai 1113, Bailian Arrearage). */
+const BILLING_CODES = new Set(['1113', 'Arrearage'])
+
export class OpenAICompatibleProvider extends OpenAIProvider {
/** Provider temperature upper bound — 1 for Moonshot, else the [0,2] default. */
private readonly temperatureCeiling: number
@@ -96,6 +109,43 @@ export class OpenAICompatibleProvider extends OpenAIProvider {
return this.cfg.id as LlmProvider
}
+ /**
+ * The OpenAI-compatible arm inherits the shared HTTP classifier from the base
+ * class, but several third parties encode model-availability and billing in a
+ * PROVIDER-NATIVE `error.code` that the raw HTTP status hides — most notably
+ * billing arriving inside a 429 (which the base class would treat as a
+ * retryable rate-limit and loop on). Intercept those codes first, then fall
+ * through to the shared HTTP/unknown classification. (spec 02 §3.1)
+ *
+ * Recognised codes (open sets — unmatched codes fall through):
+ * - z.ai: 1211 / 1220 → model not available; 1113 → billing/quota.
+ * - Bailian: ModelNotFound / Model.AccessDenied → model not available;
+ * Arrearage → billing/quota.
+ */
+ override classifyError(err: unknown): ClassifiedError {
+ const rawCode =
+ (err as { error?: { code?: unknown }; code?: unknown })?.error?.code ??
+ (err as { code?: unknown })?.code
+ const providerCode = rawCode == null ? undefined : String(rawCode)
+ if (providerCode) {
+ const message =
+ (err as { error?: { message?: string }; message?: string })?.error?.message ??
+ (err as { message?: string })?.message ??
+ 'Unknown LLM error'
+ const httpStatus =
+ typeof (err as { status?: unknown })?.status === 'number'
+ ? (err as { status: number }).status
+ : undefined
+ const mapped = MODEL_NOT_AVAILABLE_CODES.has(providerCode)
+ ? LlmErrorCode.ModelNotAvailable
+ : BILLING_CODES.has(providerCode)
+ ? LlmErrorCode.InsufficientQuota
+ : null
+ if (mapped) return { code: mapped, retryable: false, message, httpStatus, providerCode }
+ }
+ return super.classifyError(err)
+ }
+
// Third-party OpenAI-compatible APIs use the portable legacy field. The
// native OpenAI translation is intentionally not inherited for this arm.
protected override usesMaxCompletionTokens(): boolean {
diff --git a/mcp-host/src/llm/types.ts b/mcp-host/src/llm/types.ts
index 7c49ebbd4..1766381b4 100644
--- a/mcp-host/src/llm/types.ts
+++ b/mcp-host/src/llm/types.ts
@@ -35,6 +35,16 @@ export interface ClassifiedError {
code: LlmErrorCode
retryable: boolean
message: string
+ /**
+ * Additive diagnostics (spec 02, Pieza A). The provider's HTTP status and the
+ * provider-native error code/type (e.g. `not_found_error`, `1211`,
+ * `Model.AccessDenied`) when the classifier recovered them. Threaded verbatim
+ * through `LlmError` → `TaskError` so downstream (desktop) can distinguish a
+ * retired-model 404 from an ambiguous failure without re-parsing the raw SDK
+ * error. Optional: transport/unknown errors leave them undefined.
+ */
+ httpStatus?: number
+ providerCode?: string
}
/**
diff --git a/mcp-host/src/queue/types.ts b/mcp-host/src/queue/types.ts
index abba39bce..52c20d42b 100644
--- a/mcp-host/src/queue/types.ts
+++ b/mcp-host/src/queue/types.ts
@@ -21,6 +21,15 @@ export interface TaskError {
*/
retryable: boolean
provider: string // a registered LlmProvider id (llm/registryCore.ts) or "unknown"
+ /**
+ * Additive diagnostics (spec 02, Pieza A). Provider HTTP status and native
+ * error code/type behind `code`, when the classifier recovered them. Optional
+ * and purely additive — this interface is the serialized contract across all
+ * four user-delivery channels, so existing desktop consumers ignore unknown
+ * fields and keep working.
+ */
+ httpStatus?: number
+ providerCode?: string
}
export interface TaskResponsePayload {