Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(mcp-host): require a refused control-plane connection to read as control_plane_unavailable
Alfredo Lopez91685e457273
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex cf4ea675d..5a8e071e0 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.442",+ "version": "0.1.443","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.442",+ "version": "0.1.443","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 7c2897178..15efdd75c 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.442",+ "version": "0.1.443","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__/codexLlmProxyClient.test.ts b/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.tsindex 663023353..0c86a6d5e 100644--- a/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts+++ b/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts@@ -12,6 +12,7 @@ import {} from '../codexLlmProxyClient'import { CodexSubscriptionProvider } from '../codexSubscription'import { classifyFailoverClass } from '../failover/classify'+import { closedPortUrl, fetchFailure, silentServer } from './connectFailureFixtures'function sse(frames: unknown[]): ReadableStream<Uint8Array> {const encoder = new TextEncoder()@@ -696,3 +697,105 @@ describe('CodexLlmProxyClient rate limits', () => {expect((err as CodexProxyError).retryAfterMs).toBeUndefined()})})++// G1-7 (#720): a proxy that no live process answered is control_plane_unavailable;+// a failure that may have reached one keeps its current shape.+describe('CodexLlmProxyClient control-plane reachability', () => {+ const INPUT = {+ executionTicket: 'ticket-123456',+ requestHash: 'a'.repeat(64),+ request: {},+ }++ function clientAt(runtimeUrl: string, fetchFn?: typeof fetch): CodexLlmProxyClient {+ return new CodexLlmProxyClient({+ runtimeUrl: resolveCodexProxyRuntimeUrl(runtimeUrl),+ readPlatformJwt: () => 'platform-jwt',+ ...(fetchFn ? { fetchFn } : {}),+ })+ }++ it('G1-7a reads a refused connection as control_plane_unavailable', async () => {+ const url = await closedPortUrl()+ // Witness: the platform fetch fails this way against the closed port.+ const raw = await fetch(`${url}/probe`).catch((caught: unknown) => caught)+ expect(raw).toBeInstanceOf(TypeError)+ expect((raw as { cause?: { code?: unknown } }).cause?.code).toBe('ECONNREFUSED')+ const err = await clientAt(url)+ .stream(INPUT)+ .catch((caught: unknown) => caught)+ expect(err).toBeInstanceOf(CodexProxyError)+ expect(err).toMatchObject({ code: 'control_plane_unavailable' })+ expect((err as Error).message).toContain('ECONNREFUSED')+ })++ it.each(['ENOTFOUND', 'EAI_AGAIN', 'EHOSTUNREACH', 'ENETUNREACH', 'UND_ERR_CONNECT_TIMEOUT'])(+ 'G1-7b reads a %s fetch failure as control_plane_unavailable',+ async code => {+ const fetchFn = vi.fn<typeof fetch>(async () => {+ throw fetchFailure(code)+ })+ await expect(clientAt('http://proxy.invalid', fetchFn).stream(INPUT)).rejects.toMatchObject({+ name: 'CodexProxyError',+ code: 'control_plane_unavailable',+ })+ expect(fetchFn).toHaveBeenCalledTimes(1)+ }+ )++ it('G1-7c rethrows a reset connection unchanged', async () => {+ const failure = fetchFailure('ECONNRESET')+ const fetchFn = vi.fn<typeof fetch>(async () => {+ throw failure+ })+ await expect(clientAt('http://proxy.invalid', fetchFn).stream(INPUT)).rejects.toBe(failure)+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })++ it('G1-7d rejects with the abort reason when the caller aborts a request in flight', async () => {+ const server = await silentServer()+ try {+ const controller = new AbortController()+ const reason = new Error('caller gave up')+ const pending = clientAt(server.url)+ .stream({ ...INPUT, signal: controller.signal })+ .catch((caught: unknown) => caught)+ // Witness: the request reached a live process before the abort.+ await server.received+ controller.abort(reason)+ expect(await pending).toBe(reason)+ } finally {+ await server.close()+ }+ })++ it('G1-7d rethrows a connect-phase code unchanged once the caller aborted', async () => {+ const controller = new AbortController()+ const failure = fetchFailure('ECONNREFUSED')+ const fetchFn = vi.fn<typeof fetch>(async () => {+ controller.abort(new Error('caller gave up'))+ throw failure+ })+ await expect(+ clientAt('http://proxy.invalid', fetchFn).stream({ ...INPUT, signal: controller.signal })+ ).rejects.toBe(failure)+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })++ it('G1-7e leaves an error raised after the response started unchanged', async () => {+ const failure = fetchFailure('ECONNREFUSED')+ const fetchFn = vi.fn<typeof fetch>(+ async () =>+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.error(failure)+ },+ }),+ { status: 200, headers: { 'content-type': 'text/event-stream' } }+ )+ )+ await expect(clientAt('http://proxy.invalid', fetchFn).stream(INPUT)).rejects.toBe(failure)+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })+})diff --git a/mcp-host/src/llm/__tests__/connectFailureFixtures.ts b/mcp-host/src/llm/__tests__/connectFailureFixtures.tsnew file mode 100644index 000000000..5d9d76d16--- /dev/null+++ b/mcp-host/src/llm/__tests__/connectFailureFixtures.ts@@ -0,0 +1,58 @@+/**+ * G1-7 (#720): fetch failures in the shape undici produces. A refused+ * connection comes from a real closed port; the codes a local socket cannot+ * produce (DNS, unreachable network, connect timeout) are built in the same+ * shape as the one the closed-port witness captures: a `TypeError` whose+ * `cause` carries the system or undici error code.+ */+import { type ServerResponse, createServer } from 'node:http'++const LOOPBACK_V4 = '127.0.0.1'++/** The origin of a port that was bound and then released, so nothing listens. */+export async function closedPortUrl(): Promise<string> {+ const server = createServer()+ await new Promise<void>(resolve => server.listen(0, LOOPBACK_V4, () => resolve()))+ const addr = server.address()+ if (typeof addr !== 'object' || addr === null) throw new Error('closedPortUrl: no bound address')+ await new Promise<void>(resolve => server.close(() => resolve()))+ return `http://${LOOPBACK_V4}:${addr.port}`+}++export function fetchFailure(code: string): TypeError {+ return Object.assign(new TypeError('fetch failed'), {+ cause: Object.assign(new Error(code), { code }),+ })+}++/**+ * A server that accepts a request and never answers. `received` resolves once+ * a request arrived, which proves the caller got past the connect phase.+ */+export async function silentServer(): Promise<{+ url: string+ received: Promise<void>+ close: () => Promise<void>+}> {+ const pending: ServerResponse[] = []+ let markReceived: () => void = () => undefined+ const received = new Promise<void>(resolve => {+ markReceived = resolve+ })+ const server = createServer((_req, res) => {+ pending.push(res)+ markReceived()+ })+ await new Promise<void>(resolve => server.listen(0, LOOPBACK_V4, () => resolve()))+ const addr = server.address()+ if (typeof addr !== 'object' || addr === null) throw new Error('silentServer: no bound address')+ return {+ url: `http://${LOOPBACK_V4}:${addr.port}`,+ received,+ close: async () => {+ for (const res of pending) res.destroy()+ server.closeAllConnections()+ await new Promise<void>(resolve => server.close(() => resolve()))+ },+ }+}diff --git a/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts b/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.tsindex fda835189..4920c4d79 100644--- a/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts+++ b/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts@@ -8,6 +8,7 @@ import {resolveGrokProxyRuntimeUrl,} from '../grokLlmProxyClient'import { GrokSubscriptionProvider } from '../grokSubscription'+import { closedPortUrl, fetchFailure, silentServer } from './connectFailureFixtures'const RUNTIME_BASE = 'http://grok-llm-proxy.control-plane.svc.cluster.local:8080'const RUNTIME_URL = `${RUNTIME_BASE}/internal/runtime/v1/grok/completions`@@ -596,3 +597,105 @@ describe('GrokLlmProxyClient rate limits', () => {expect((err as GrokProxyError).retryAfterMs).toBeUndefined()})})++// G1-7 (#720): a proxy that no live process answered is control_plane_unavailable;+// a failure that may have reached one keeps its current shape.+describe('GrokLlmProxyClient control-plane reachability', () => {+ const INPUT = {+ executionTicket: 'ticket-123456',+ requestHash: 'a'.repeat(64),+ request: {},+ }++ function clientAt(runtimeUrl: string, fetchFn?: typeof fetch): GrokLlmProxyClient {+ return new GrokLlmProxyClient({+ runtimeUrl: resolveGrokProxyRuntimeUrl(runtimeUrl),+ readPlatformJwt: () => 'platform-jwt',+ ...(fetchFn ? { fetchFn } : {}),+ })+ }++ it('G1-7a reads a refused connection as control_plane_unavailable', async () => {+ const url = await closedPortUrl()+ // Witness: the platform fetch fails this way against the closed port.+ const raw = await fetch(`${url}/probe`).catch((caught: unknown) => caught)+ expect(raw).toBeInstanceOf(TypeError)+ expect((raw as { cause?: { code?: unknown } }).cause?.code).toBe('ECONNREFUSED')+ const err = await clientAt(url)+ .stream(INPUT)+ .catch((caught: unknown) => caught)+ expect(err).toBeInstanceOf(GrokProxyError)+ expect(err).toMatchObject({ code: 'control_plane_unavailable' })+ expect((err as Error).message).toContain('ECONNREFUSED')+ })++ it.each(['ENOTFOUND', 'EAI_AGAIN', 'EHOSTUNREACH', 'ENETUNREACH', 'UND_ERR_CONNECT_TIMEOUT'])(+ 'G1-7b reads a %s fetch failure as control_plane_unavailable',+ async code => {+ const fetchFn = vi.fn<typeof fetch>(async () => {+ throw fetchFailure(code)+ })+ await expect(clientAt('http://proxy.invalid', fetchFn).stream(INPUT)).rejects.toMatchObject({+ name: 'GrokProxyError',+ code: 'control_plane_unavailable',+ })+ expect(fetchFn).toHaveBeenCalledTimes(1)+ }+ )++ it('G1-7c rethrows a reset connection unchanged', async () => {+ const failure = fetchFailure('ECONNRESET')+ const fetchFn = vi.fn<typeof fetch>(async () => {+ throw failure+ })+ await expect(clientAt('http://proxy.invalid', fetchFn).stream(INPUT)).rejects.toBe(failure)+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })++ it('G1-7d rejects with the abort reason when the caller aborts a request in flight', async () => {+ const server = await silentServer()+ try {+ const controller = new AbortController()+ const reason = new Error('caller gave up')+ const pending = clientAt(server.url)+ .stream({ ...INPUT, signal: controller.signal })+ .catch((caught: unknown) => caught)+ // Witness: the request reached a live process before the abort.+ await server.received+ controller.abort(reason)+ expect(await pending).toBe(reason)+ } finally {+ await server.close()+ }+ })++ it('G1-7d rethrows a connect-phase code unchanged once the caller aborted', async () => {+ const controller = new AbortController()+ const failure = fetchFailure('ECONNREFUSED')+ const fetchFn = vi.fn<typeof fetch>(async () => {+ controller.abort(new Error('caller gave up'))+ throw failure+ })+ await expect(+ clientAt('http://proxy.invalid', fetchFn).stream({ ...INPUT, signal: controller.signal })+ ).rejects.toBe(failure)+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })++ it('G1-7e leaves an error raised after the response started unchanged', async () => {+ const failure = fetchFailure('ECONNREFUSED')+ const fetchFn = vi.fn<typeof fetch>(+ async () =>+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.error(failure)+ },+ }),+ { status: 200, headers: { 'content-type': 'text/event-stream' } }+ )+ )+ await expect(clientAt('http://proxy.invalid', fetchFn).stream(INPUT)).rejects.toBe(failure)+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })+})diff --git a/mcp-host/src/llm/__tests__/providerAttemptAuthorizer.test.ts b/mcp-host/src/llm/__tests__/providerAttemptAuthorizer.test.tsindex b650be12f..51208c31c 100644--- a/mcp-host/src/llm/__tests__/providerAttemptAuthorizer.test.ts+++ b/mcp-host/src/llm/__tests__/providerAttemptAuthorizer.test.ts@@ -15,6 +15,7 @@ import {ProviderAttemptAuthorizer,resolveCodexAuthorizeUrl,} from '../providerAttemptAuthorizer'+import { closedPortUrl, fetchFailure, silentServer } from './connectFailureFixtures'const validAuthorize = {providerAttemptId: 'attempt-1',@@ -445,3 +446,95 @@ describe('ProviderAttemptAuthorizer', () => {expect(refreshOnUnauthorized).not.toHaveBeenCalled()})})++// G1-7 (#720): an authorize that no live gateway process answered is+// control_plane_unavailable; a failure that may have reached one is not.+describe('ProviderAttemptAuthorizer control-plane reachability', () => {+ const BODY: AuthorizeAttemptBody = {+ request: {},+ invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptIndex: 1,+ policyRevision: 1,+ policyHash: 'b'.repeat(64),+ }++ function authorizerAt(gatewayBase: string, fetchFn?: typeof fetch): ProviderAttemptAuthorizer {+ return new ProviderAttemptAuthorizer({+ authorizeUrl: resolveCodexAuthorizeUrl(gatewayBase),+ readPlatformJwt: () => 'platform-jwt',+ ...(fetchFn ? { fetchFn } : {}),+ })+ }++ it('G1-7a reads a refused connection as control_plane_unavailable', async () => {+ const url = await closedPortUrl()+ // Witness: the platform fetch fails this way against the closed port.+ const raw = await fetch(`${url}/probe`).catch((caught: unknown) => caught)+ expect(raw).toBeInstanceOf(TypeError)+ expect((raw as { cause?: { code?: unknown } }).cause?.code).toBe('ECONNREFUSED')+ const err = await authorizerAt(url)+ .authorize(BODY)+ .catch((caught: unknown) => caught)+ expect(err).toBeInstanceOf(CodexAuthorizeError)+ expect(err).toMatchObject({ code: 'control_plane_unavailable' })+ expect((err as Error).message).toContain('ECONNREFUSED')+ })++ it.each(['ENOTFOUND', 'EAI_AGAIN', 'EHOSTUNREACH', 'ENETUNREACH', 'UND_ERR_CONNECT_TIMEOUT'])(+ 'G1-7b reads a %s fetch failure as control_plane_unavailable',+ async code => {+ const fetchFn = vi.fn<typeof fetch>(async () => {+ throw fetchFailure(code)+ })+ await expect(+ authorizerAt('http://gateway.invalid', fetchFn).authorize(BODY)+ ).rejects.toMatchObject({+ name: 'CodexAuthorizeError',+ code: 'control_plane_unavailable',+ })+ expect(fetchFn).toHaveBeenCalledTimes(1)+ }+ )++ it('G1-7c rethrows a reset connection unchanged', async () => {+ const failure = fetchFailure('ECONNRESET')+ const fetchFn = vi.fn<typeof fetch>(async () => {+ throw failure+ })+ await expect(authorizerAt('http://gateway.invalid', fetchFn).authorize(BODY)).rejects.toBe(+ failure+ )+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })++ it('G1-7d rejects with the abort reason when the caller aborts a request in flight', async () => {+ const server = await silentServer()+ try {+ const controller = new AbortController()+ const reason = new Error('caller gave up')+ const pending = authorizerAt(server.url)+ .authorize(BODY, { signal: controller.signal })+ .catch((caught: unknown) => caught)+ // Witness: the request reached a live process before the abort.+ await server.received+ controller.abort(reason)+ expect(await pending).toBe(reason)+ } finally {+ await server.close()+ }+ })++ it('G1-7d rethrows a connect-phase code unchanged once the caller aborted', async () => {+ const controller = new AbortController()+ const failure = fetchFailure('ECONNREFUSED')+ const fetchFn = vi.fn<typeof fetch>(async () => {+ controller.abort(new Error('caller gave up'))+ throw failure+ })+ await expect(+ authorizerAt('http://gateway.invalid', fetchFn).authorize(BODY, { signal: controller.signal })+ ).rejects.toBe(failure)+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })+})