Skip to content

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

TypeScript

fix(host): drop dead attachment retention config and log without payloads

Alfredo Lopez803709ba33ec
diff --git a/mcp-host/README.md b/mcp-host/README.md
index 02d517c1a..077bad314 100644
--- a/mcp-host/README.md
+++ b/mcp-host/README.md
@@ -55,7 +55,7 @@ MCP Host is a Kubernetes-native service that reads Host CRD configuration and pr
| `CLERUM_ENABLE_RESPONSE_ATTACHMENTS` | Enables attachment passthrough in runtime responses when tools return supported media. | `CLERUM_ENABLE_RESPONSE_ATTACHMENTS=true` |
| `CLERUM_ATTACHMENT_MAX_COUNT` | Maximum number of attachments returned per response. | `CLERUM_ATTACHMENT_MAX_COUNT=3` |
| `CLERUM_ATTACHMENT_MAX_BYTES` | Maximum decoded size per attachment in bytes (oversized payloads are dropped). | `CLERUM_ATTACHMENT_MAX_BYTES=52428800` |
-| `CLERUM_ATTACHMENT_FILE_MAX_BYTES` | Maximum decoded bytes per incoming `kind:'file'` attachment, default and ceiling 11 MiB (11,534,336 bytes). A larger file rejects the message with `FILE_ATTACHMENT_TOO_LARGE`. File base64 has its own 16 MiB quota; the non-credited message share remains 6 MiB and the total body remains 24 MiB. A lower file limit does not change those body quotas. An invalid or above-ceiling setting stops the Host at startup. | `CLERUM_ATTACHMENT_FILE_MAX_BYTES=11534336` |
+| `CLERUM_ATTACHMENT_FILE_MAX_BYTES` | Maximum decoded bytes per incoming `kind:'file'` attachment, default and ceiling 11 MiB (11,534,336 bytes). The chat body parser answers HTTP 413 for any larger file before admission; above a lower limit, up to 11 MiB, admission answers `FILE_ATTACHMENT_TOO_LARGE`. Files have a 16 MiB base64 quota; the message share is 6 MiB and the body 24 MiB. An invalid or above-ceiling setting stops the Host at startup. | `CLERUM_ATTACHMENT_FILE_MAX_BYTES=11534336` |
| `CLERUM_ATTACHMENT_TEXT_READ_MAX_BYTES` | Maximum bytes per native attachment text page, default 64 KiB (65,536 bytes), configurable up to 1 MiB (1,048,576 bytes). Truncated text continues from its byte offset. Native attachment pages remain inline and exempt from spillover. Byte size is independent of token cost; do not infer a fixed bytes-per-token ratio. An invalid or above-ceiling setting stops the Host at startup. | `CLERUM_ATTACHMENT_TEXT_READ_MAX_BYTES=65536` |
| `CLERUM_MEMORY_ENABLED` | Enables workspace memory persistence features. | `CLERUM_MEMORY_ENABLED=true` |
| `CLERUM_MEMORY_WORKSPACE_PATH` | Sets workspace directory path used when memory mode is enabled. | `CLERUM_MEMORY_WORKSPACE_PATH=/workspace` |
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 1a3db01f1..5084bf3fe 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.490",
+ "version": "0.1.491",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.490",
+ "version": "0.1.491",
"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 5f1ace456..b4e1ff97d 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.490",
+ "version": "0.1.491",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/server.lifecycleLogging.test.ts b/mcp-host/src/__tests__/server.lifecycleLogging.test.ts
new file mode 100644
index 000000000..b8f9600aa
--- /dev/null
+++ b/mcp-host/src/__tests__/server.lifecycleLogging.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import * as net from 'node:net'
+import type { AddressInfo } from 'node:net'
+import { RPCServer } from '../server'
+
+// The RPC server reports its lifecycle through the service logger (repository
+// logging standard), with the error reduced by the logger to name and code.
+const logger = vi.hoisted(() => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+}))
+vi.mock('../logger', async importOriginal => ({
+ ...(await importOriginal<typeof import('../logger')>()),
+ logger,
+}))
+
+afterEach(() => {
+ vi.clearAllMocks()
+})
+
+function boundPort(server: RPCServer): number {
+ return (server as unknown as { server: { address(): AddressInfo } }).server.address().port
+}
+
+describe('RPCServer lifecycle logging', () => {
+ it('logs listening and stopped through the service logger', async () => {
+ const server = new RPCServer(0)
+ await server.start()
+ try {
+ expect(logger.info).toHaveBeenCalledWith(
+ { component: 'Server', port: 0 },
+ 'RPC server listening'
+ )
+ // Witness: the logged start is a real bind.
+ expect(boundPort(server)).toBeGreaterThan(0)
+ } finally {
+ await server.stop()
+ }
+ expect(logger.info).toHaveBeenCalledWith({ component: 'Server' }, 'RPC server stopped')
+ })
+
+ it('logs a listen failure through the service logger and rejects with it', async () => {
+ // Hold the wildcard address the server binds when given an explicit port.
+ const blocker = net.createServer()
+ await new Promise<void>(resolve => blocker.listen(0, '::', resolve))
+ const { port } = blocker.address() as AddressInfo
+ try {
+ await expect(new RPCServer(port).start()).rejects.toMatchObject({ code: 'EADDRINUSE' })
+ expect(logger.error).toHaveBeenCalledTimes(1)
+ const [fields, message] = logger.error.mock.calls[0]
+ expect(message).toBe('RPC server error')
+ expect(fields).toMatchObject({ component: 'Server', err: { code: 'EADDRINUSE' } })
+ } finally {
+ await new Promise(resolve => blocker.close(resolve))
+ }
+ })
+})
diff --git a/mcp-host/src/agent/incomingAttachments.ts b/mcp-host/src/agent/incomingAttachments.ts
index 51ead410b..978b9428f 100644
--- a/mcp-host/src/agent/incomingAttachments.ts
+++ b/mcp-host/src/agent/incomingAttachments.ts
@@ -21,9 +21,10 @@ import type { TaskError } from '../queue/types'
* Per-image bytes stay on the channel `attachmentMaxBytes` (issue #654 / PR
* #669) — this module must not clamp general inbound traffic to the Codex
* `VISUAL_LIMITS`. The Codex chat hop is a separate 24 MiB parser with a
- * 16 MiB credited image budget and a 16 MiB credited file budget. Per-file
- * bytes use `attachmentFileMaxBytes` (issue #666, 11 MiB by default per issue
- * #678). This count is the fail-loud admission cap.
+ * credited budget of 16 MiB of decoded image bytes and another of 16 MiB of
+ * file base64 (about 12 MiB decoded). Per-file bytes use
+ * `attachmentFileMaxBytes` (issue #666, 11 MiB by default per issue #678).
+ * This count is the fail-loud admission cap.
*/
export const INCOMING_ATTACHMENT_MAX_COUNT = 20
diff --git a/mcp-host/src/config.attachmentStore.test.ts b/mcp-host/src/config.attachmentStore.test.ts
deleted file mode 100644
index 771dae488..000000000
--- a/mcp-host/src/config.attachmentStore.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-
-const TTL = 'CLERUM_ATTACHMENT_STORE_TTL_HOURS'
-const SESSION = 'CLERUM_ATTACHMENT_STORE_SESSION_MAX_BYTES'
-const HOST = 'CLERUM_ATTACHMENT_STORE_HOST_MAX_BYTES'
-
-afterEach(() => {
- vi.unstubAllEnvs()
- vi.resetModules()
-})
-
-async function load() {
- vi.resetModules()
- return (await import('./config')).config
-}
-
-describe('attachment retention configuration', () => {
- it('defaults to seven days, 64 MiB per session and 1 GiB per Host', async () => {
- vi.stubEnv(TTL, undefined)
- vi.stubEnv(SESSION, undefined)
- vi.stubEnv(HOST, undefined)
- const config = await load()
- expect(config).toMatchObject({
- attachmentStoreTtlMs: 604_800_000,
- attachmentStoreSessionMaxBytes: 67_108_864,
- attachmentStoreHostMaxBytes: 1_073_741_824,
- })
- })
-
- it.each([TTL, SESSION, HOST])('rejects invalid %s instead of using its default', async key => {
- for (const value of ['', '0', '-1', '1.5', '1e6', '12hours', 'Infinity', '9007199254740992']) {
- vi.stubEnv(key, value)
- await expect(load()).rejects.toThrow(key)
- }
- })
-
- it('accepts explicitly configured limits without changing the upload limit', async () => {
- vi.stubEnv(TTL, '24')
- vi.stubEnv(SESSION, '12582912')
- vi.stubEnv(HOST, '33554432')
- const config = await load()
- expect(config).toMatchObject({
- attachmentStoreTtlMs: 86_400_000,
- attachmentStoreSessionMaxBytes: 12_582_912,
- attachmentStoreHostMaxBytes: 33_554_432,
- attachmentFileMaxBytes: 11_534_336,
- })
- })
-
- it('rejects a session cap greater than the Host cap', async () => {
- vi.stubEnv(SESSION, '67108864')
- vi.stubEnv(HOST, '33554432')
- await expect(load()).rejects.toThrow(SESSION)
- })
-
- it('requires space for one admitted file and honors a smaller configured file limit', async () => {
- vi.stubEnv(SESSION, '11534335')
- await expect(load()).rejects.toThrow(SESSION)
- vi.stubEnv('CLERUM_ATTACHMENT_FILE_MAX_BYTES', '3145728')
- vi.stubEnv(SESSION, '3145728')
- vi.stubEnv(HOST, '3145728')
- expect(await load()).toMatchObject({
- attachmentStoreSessionMaxBytes: 3_145_728,
- attachmentStoreHostMaxBytes: 3_145_728,
- })
- })
-
- it('rejects a TTL that cannot produce a valid absolute JavaScript date', async () => {
- vi.stubEnv(TTL, '2400000000')
- await expect(load()).rejects.toThrow(TTL)
- })
-})
diff --git a/mcp-host/src/config.fileIngress.test.ts b/mcp-host/src/config.fileIngress.test.ts
index 4bca85c7c..12e56206b 100644
--- a/mcp-host/src/config.fileIngress.test.ts
+++ b/mcp-host/src/config.fileIngress.test.ts
@@ -108,6 +108,19 @@ describe('#666 file ingress configuration', () => {
expect(config.attachmentFileMaxBytes).toBe(3_145_728)
})
+ it('ignores the attachment retention variables, which have no store to configure', async () => {
+ vi.resetModules()
+ // Each value stopped the Host at load while the retention limits were parsed.
+ vi.stubEnv('CLERUM_ATTACHMENT_STORE_TTL_HOURS', '0')
+ vi.stubEnv('CLERUM_ATTACHMENT_STORE_SESSION_MAX_BYTES', '11534335')
+ vi.stubEnv('CLERUM_ATTACHMENT_STORE_HOST_MAX_BYTES', '1')
+ vi.stubEnv('CLERUM_ATTACHMENT_FILE_MAX_BYTES', '3145728')
+ const loaded = import('./config').then(({ config }) => config)
+ // Witness: the per-file limit is still read from its own variable.
+ await expect(loaded).resolves.toMatchObject({ attachmentFileMaxBytes: 3_145_728 })
+ expect(Object.keys(await loaded).filter(key => key.startsWith('attachmentStore'))).toEqual([])
+ })
+
it('loads an explicit spillover threshold', async () => {
vi.resetModules()
vi.stubEnv(SPILLOVER, '16384')
diff --git a/mcp-host/src/config.jsonParseLogging.test.ts b/mcp-host/src/config.jsonParseLogging.test.ts
new file mode 100644
index 000000000..cc0684784
--- /dev/null
+++ b/mcp-host/src/config.jsonParseLogging.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+// A JSON.parse SyntaxError quotes a slice of its input, so logging the error
+// object from a config parse failure can publish part of a secret held in that
+// variable. The parse sites log the error name only.
+// The random token comes first because the parser quotes only the characters
+// around the error position; the trailing marker keeps the public-boundary
+// scanner from reading the synthetic value as a credential.
+const LEAK_PROBE = 'zq7Xv9Lp2Wm4Rk8T'
+const SECRET = `${LEAK_PROBE}-synthetic`
+const INVALID_JSON = `{"apiKey": ${SECRET}}`
+
+const PARSE_FAILURES = [
+ ['CLERUM_HOST_CONFIG', 'Failed to parse dev Host configuration'],
+ ['CLERUM_MCP_SERVERS', 'Failed to parse dev MCP servers'],
+ ['CLERUM_GUARDRAILS_CONFIG', 'Failed to parse guardrails configuration'],
+ ['CLERUM_APPROVAL_CONFIG', 'Failed to parse approval configuration'],
+] as const
+
+afterEach(() => {
+ vi.unstubAllEnvs()
+ vi.doUnmock('./logger')
+ vi.resetModules()
+})
+
+function serialize(args: unknown[]): string {
+ return JSON.stringify(args, (_key, value: unknown) =>
+ value instanceof Error
+ ? { name: value.name, message: value.message, stack: value.stack }
+ : value
+ )
+}
+
+describe('config JSON parse failure logging', () => {
+ it('logs only the error name when a JSON variable carrying a secret is invalid', async () => {
+ vi.resetModules()
+ const calls: unknown[][] = []
+ const record =
+ (level: string) =>
+ (...args: unknown[]) => {
+ calls.push([level, ...args])
+ }
+ vi.doMock('./logger', () => ({
+ logger: {
+ debug: record('debug'),
+ info: record('info'),
+ warn: record('warn'),
+ error: record('error'),
+ },
+ redactUnknown: (value: unknown) => value,
+ }))
+ vi.stubEnv('CLERUM_DEV_MODE', 'true')
+ for (const [name] of PARSE_FAILURES) vi.stubEnv(name, INVALID_JSON)
+
+ // Precondition: the parser itself quotes the secret, so the leak is real.
+ expect(() => JSON.parse(INVALID_JSON)).toThrow(LEAK_PROBE.slice(0, 4))
+
+ await import('./config')
+
+ // Witness: every parse site reached its failure log.
+ const failureLogs = calls.filter(([level]) => level === 'error')
+ expect(failureLogs.map(call => call[2]).sort()).toEqual(
+ PARSE_FAILURES.map(([, message]) => message).sort()
+ )
+
+ const logged = serialize(calls)
+ for (let start = 0; start + 4 <= LEAK_PROBE.length; start++) {
+ expect(logged).not.toContain(LEAK_PROBE.slice(start, start + 4))
+ }
+ for (const call of failureLogs) {
+ expect(call[1]).toEqual({ component: 'Config', errorName: 'SyntaxError' })
+ }
+ })
+})
diff --git a/mcp-host/src/config.ts b/mcp-host/src/config.ts
index aff9a80fc..b5ac75dff 100644
--- a/mcp-host/src/config.ts
+++ b/mcp-host/src/config.ts
@@ -249,11 +249,6 @@ export interface Config {
attachmentFileMaxBytes: number
/** Bytes one `clerum__attachment_read` call may return (issue #666). */
attachmentTextReadMaxBytes: number
- /** Absolute retention duration; reads never extend it. */
- attachmentStoreTtlMs: number
- /** Committed, reserved and pending-cleanup bytes share these quotas. */
- attachmentStoreSessionMaxBytes: number
- attachmentStoreHostMaxBytes: number
/**
* Structured file references one incoming message may carry (issue #666).
* The shared contract constant the Desktop composer also enforces; not
@@ -470,7 +465,11 @@ function parseDevHostConfig(): HostSpec | undefined {
)
return parsed
} catch (error) {
- logger.error({ component: 'Config', err: error }, 'Failed to parse dev Host configuration')
+ // A JSON.parse SyntaxError quotes a slice of the input; log its name only.
+ logger.error(
+ { component: 'Config', errorName: (error as SyntaxError).name },
+ 'Failed to parse dev Host configuration'
+ )
return undefined
}
}
@@ -525,34 +524,6 @@ const attachmentFileMaxBytes = getExecutionLimit(
false,
11_534_336
)
-const attachmentStoreTtlHours = getExecutionLimit(
- 'CLERUM_ATTACHMENT_STORE_TTL_HOURS',
- 168,
- false,
- // Date's absolute limit is stricter than the safe-integer limit. Admission
- // must also check its trusted timestamp before adding this duration.
- Math.floor((8_640_000_000_000_000 - Date.now()) / 3_600_000)
-)
-const attachmentStoreSessionMaxBytes = getExecutionLimit(
- 'CLERUM_ATTACHMENT_STORE_SESSION_MAX_BYTES',
- 67_108_864,
- false,
- Number.MAX_SAFE_INTEGER
-)
-const attachmentStoreHostMaxBytes = getExecutionLimit(
- 'CLERUM_ATTACHMENT_STORE_HOST_MAX_BYTES',
- 1_073_741_824,
- false,
- Number.MAX_SAFE_INTEGER
-)
-if (
- attachmentStoreSessionMaxBytes < attachmentFileMaxBytes ||
- attachmentStoreSessionMaxBytes > attachmentStoreHostMaxBytes
-) {
- throw new Error(
- 'CLERUM_ATTACHMENT_STORE_SESSION_MAX_BYTES must accommodate one admitted file and not exceed CLERUM_ATTACHMENT_STORE_HOST_MAX_BYTES'
- )
-}
const configuredWorkflowEnabled = getEnvBool('CLERUM_WORKFLOW_ENABLED', false)
const configuredRuntimeKind = resolveMcpHostRuntimeKind({
workflowEnabled: configuredWorkflowEnabled,
@@ -687,7 +658,10 @@ function parseDevMcpServers(): McpServerInfo[] | undefined {
logger.info({ component: 'Config', serverCount: parsed.length }, 'Parsed dev MCP servers')
return parsed
} catch (error) {
- logger.error({ component: 'Config', err: error }, 'Failed to parse dev MCP servers')
+ logger.error(
+ { component: 'Config', errorName: (error as SyntaxError).name },
+ 'Failed to parse dev MCP servers'
+ )
return undefined
}
}
@@ -708,7 +682,10 @@ function parseGuardrailsConfig(): GuardrailsConfig | undefined {
)
return parsed
} catch (error) {
- logger.error({ component: 'Config', err: error }, 'Failed to parse guardrails configuration')
+ logger.error(
+ { component: 'Config', errorName: (error as SyntaxError).name },
+ 'Failed to parse guardrails configuration'
+ )
return undefined
}
}
@@ -727,7 +704,10 @@ function parseApprovalConfig(): ApprovalConfig | undefined {
)
return parsed
} catch (error) {
- logger.error({ component: 'Config', err: error }, 'Failed to parse approval configuration')
+ logger.error(
+ { component: 'Config', errorName: (error as SyntaxError).name },
+ 'Failed to parse approval configuration'
+ )
return undefined
}
}
@@ -1086,9 +1066,6 @@ export const config: Config = {
attachmentMaxBytes: parseInt(getEnv('CLERUM_ATTACHMENT_MAX_BYTES', '52428800')!, 10),
attachmentFileMaxBytes,
attachmentTextReadMaxBytes,
- attachmentStoreTtlMs: attachmentStoreTtlHours * 3_600_000,
- attachmentStoreSessionMaxBytes,
- attachmentStoreHostMaxBytes,
fileReferenceMaxCount: FILE_REFERENCE_MAX_COUNT,
activityBufferSize: parseInt(getEnv('MCP_HOST_ACTIVITY_BUFFER_SIZE', '1000')!, 10),
activityMaxEventBytes: parseInt(getEnv('MCP_HOST_ACTIVITY_MAX_EVENT_BYTES', '2048')!, 10),
diff --git a/mcp-host/src/core/adapters/__tests__/failoverLlmPort.test.ts b/mcp-host/src/core/adapters/__tests__/failoverLlmPort.test.ts
index 97402c69e..f9925f8e9 100644
--- a/mcp-host/src/core/adapters/__tests__/failoverLlmPort.test.ts
+++ b/mcp-host/src/core/adapters/__tests__/failoverLlmPort.test.ts
@@ -5,6 +5,8 @@ import type { LlmPolicy } from '../../../llm/failover/types'
import type { LlmUsageEvent } from '../../../usage/usageReporter'
import type { ImageInputCapability } from '../../../visualInput/policy'
import { LlmError, LlmErrorCode } from '../../errors'
+import type { LlmPort } from '../../interfaces'
+import type { TokenCounter } from '../../tokenizer/tokenCounter'
import { type ChatMessage, FinishReason, type ToolCompletionRequest } from '../../types'
import { maybeWrapFailover } from '../failoverLlmPort'
import { AdapterStaticContext, LlmPortAdapter } from '../llmPortAdapter'
@@ -423,3 +425,74 @@ describe('FailoverLlmPort — visual destination failover', () => {
}
)
})
+
+/**
+ * Attachment pages are measured against every destination that may receive
+ * them, so each constructible fallback must contribute its own counter. A
+ * constructible port without one is a wiring bug and must not shrink the set.
+ */
+describe('FailoverLlmPort — tool token counters', () => {
+ const threeEntry: LlmPolicy = {
+ ...policy,
+ fallbacks: [
+ { provider: 'openai', model: 'gpt-5.4' }, // index 0
+ { provider: 'zai', model: 'glm-5.1' }, // index 1
+ { provider: 'openrouter', model: 'example/model' }, // index 2
+ ],
+ }
+
+ function counter(label: string): TokenCounter {
+ return { label } as unknown as TokenCounter
+ }
+
+ function port(model: string, tokenCounter?: TokenCounter): LlmPort {
+ return {
+ complete: vi.fn(),
+ completeWithTools: vi.fn(),
+ modelName: () => model,
+ ...(tokenCounter ? { getTokenCounter: () => tokenCounter } : {}),
+ }
+ }
+
+ function wrap(buildFallbackPort: (index: number) => LlmPort | null): LlmPort {
+ return maybeWrapFailover({
+ primaryPort: port('claude-sonnet-4-6', counter('primary')),
+ primaryPair: { provider: 'claude', model: 'claude-sonnet-4-6' },
+ engine: new FailoverEngine(threeEntry, { metricInc: () => {} }),
+ policy: threeEntry,
+ buildFallbackPort,
+ })
+ }
+
+ it('returns the primary counter and the counter of every constructible fallback', () => {
+ const builtIndexes: number[] = []
+ const wrapped = wrap(index => {
+ builtIndexes.push(index)
+ // Index 1 is unconstructible: the engine never routes to it either.
+ if (index === 1) return null
+ return port(threeEntry.fallbacks[index].model, counter(`fallback-${index}`))
+ })
+
+ expect(wrapped.getToolTokenCounters!()).toEqual([
+ counter('primary'),
+ counter('fallback-0'),
+ counter('fallback-2'),
+ ])
+ expect(builtIndexes).toEqual([0, 1, 2])
+ })
+
+ it('throws, naming the destination, when a constructible fallback has no token counter', () => {
+ const builtIndexes: number[] = []
+ const wrapped = wrap(index => {
+ builtIndexes.push(index)
+ const { model } = threeEntry.fallbacks[index]
+ return index === 1 ? port(model) : port(model, counter(`fallback-${index}`))
+ })
+
+ expect(() => wrapped.getToolTokenCounters!()).toThrow(
+ '[FailoverLlmPort] fallback 1 (zai/glm-5.1) has no token counter — wiring bug'
+ )
+ // Witness: the measurement walked the fallback list up to the faulty entry.
+ expect(builtIndexes).toEqual([0, 1])
+ })
+})
diff --git a/mcp-host/src/core/adapters/failoverLlmPort.ts b/mcp-host/src/core/adapters/failoverLlmPort.ts
index 23904260b..e6f95b084 100644
--- a/mcp-host/src/core/adapters/failoverLlmPort.ts
+++ b/mcp-host/src/core/adapters/failoverLlmPort.ts
@@ -95,7 +95,9 @@ class FailoverLlmPort implements LlmPort {
const counters = [this.getTokenCounter()]
// File pages remain in the request when a later round changes provider.
// Construct each configured adapter once so measurement uses its actual
- // model counter, without making a completion or countTokens request.
+ // model counter, without making a completion or countTokens request. An
+ // unconstructible entry (null port) is never dispatched to, so it has
+ // nothing to measure; a constructible one without a counter is a wiring bug.
for (const [index, entry] of this.o.policy.fallbacks.entries()) {
const port = this.portFor({
kind: 'fallback',
@@ -103,8 +105,14 @@ class FailoverLlmPort implements LlmPort {
provider: entry.provider,
model: entry.model,
})
- const counter = port?.getTokenCounter?.()
- if (counter) counters.push(counter)
+ if (!port) continue
+ const counter = port.getTokenCounter?.()
+ if (!counter) {
+ throw new Error(
+ `[FailoverLlmPort] fallback ${index} (${entry.provider}/${entry.model}) has no token counter — wiring bug`
+ )
+ }
+ counters.push(counter)
}
return counters
}
diff --git a/mcp-host/src/core/spillover/__tests__/storage.gcLogging.test.ts b/mcp-host/src/core/spillover/__tests__/storage.gcLogging.test.ts
new file mode 100644
index 000000000..127ea41e7
--- /dev/null
+++ b/mcp-host/src/core/spillover/__tests__/storage.gcLogging.test.ts
@@ -0,0 +1,48 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { SpilloverStorage } from '../storage'
+
+// A failed periodic sweep is reported through the service logger (repository
+// logging standard), which keeps the error's name and code but not its message.
+const logger = vi.hoisted(() => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+}))
+vi.mock('../../../logger', async importOriginal => ({
+ ...(await importOriginal<typeof import('../../../logger')>()),
+ logger,
+}))
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.clearAllMocks()
+})
+
+describe('SpilloverStorage GC failure logging', () => {
+ it('logs a failed sweep through the service logger', async () => {
+ vi.useFakeTimers()
+ const storage = new SpilloverStorage({
+ workspacePath: '/nonexistent-spillover-workspace',
+ thresholdBytes: 8,
+ ttlMs: 60_000,
+ gcIntervalMs: 1_000,
+ })
+ const failure = Object.assign(new Error('EACCES: /private/path'), { code: 'EACCES' })
+ const sweep = vi.spyOn(storage, 'sweep').mockRejectedValue(failure)
+
+ storage.startGc()
+ try {
+ await vi.advanceTimersByTimeAsync(1_000)
+ } finally {
+ storage.stopGc()
+ }
+
+ // Witness: the timer fired the sweep.
+ expect(sweep).toHaveBeenCalledTimes(1)
+ expect(logger.error).toHaveBeenCalledWith(
+ { component: 'SpilloverStorage', err: failure },
+ 'GC sweep failed'
+ )
+ })
+})
diff --git a/mcp-host/src/core/spillover/storage.ts b/mcp-host/src/core/spillover/storage.ts
index 9559d7649..bf7177432 100644
--- a/mcp-host/src/core/spillover/storage.ts
+++ b/mcp-host/src/core/spillover/storage.ts
@@ -21,6 +21,7 @@ import { createHash } from 'crypto'
import * as fs from 'fs/promises'
import * as path from 'path'
import { Counter, Gauge, Histogram } from 'prom-client'
+import { logger } from '../../logger'
import { buildSpilloverRef, parseSpilloverRef } from './refResolver'
import { generateStructureHint, inferContentType } from './structureHints'
import type {
@@ -366,7 +367,7 @@ export class SpilloverStorage {
if (this.gcTimer) return
this.gcTimer = setInterval(() => {
this.sweep().catch(err => {
- console.error('[SpilloverStorage] GC sweep failed:', err)
+ logger.error({ component: 'SpilloverStorage', err }, 'GC sweep failed')
})
}, this.opts.gcIntervalMs)
// Don't keep the process alive just for the sweep.
diff --git a/mcp-host/src/server.ts b/mcp-host/src/server.ts
index c57759059..7d78be919 100644
--- a/mcp-host/src/server.ts
+++ b/mcp-host/src/server.ts
@@ -11,6 +11,7 @@ import { register } from 'prom-client'
import { readOpenedArtifactBuffer, redactArtifactForDelivery } from './artifacts/artifactBytes'
import type { ArtifactSecretEntry } from './artifacts/artifactRedaction'
import type { RuntimeLifecycleGate } from './lifecycle/statelessHeartbeat'
+import { logger } from './logger'
import './mcp/catalogBootstrapMetrics'
import './mcp/statusHeartbeatMetrics'
import './observability/processMetrics'
@@ -137,7 +138,8 @@ export type {
* one source without a new package. Both copies must change together.
*
* - MAX_CHAT_BODY_BYTES stays 24MiB so one exceptional 16MiB 2048 PNG
- * (~21.3MiB base64) plus the 1MiB non-image share still fits. Every other
+ * (~21.3MiB base64) still fits with ~2.7MiB left for the rest of the body;
+ * that remainder also counts against the 6MiB non-image share. Every other
* route keeps the 10mb ordinary JSON cap (see the parsers below).
* - MAX_NON_IMAGE_BODY_BYTES bounds that same body MINUS credited image
* base64 (16MiB per image, at most 20 images / 16MiB total) and MINUS
@@ -978,12 +980,12 @@ export class RPCServer {
this.server = this.app.listen(this.port)
this.server.on('error', err => {
- console.error('[Server] Error:', err)
+ logger.error({ component: 'Server', err }, 'RPC server error')
reject(err)
})
this.server.on('listening', () => {
- console.log(`[Server] RPC server listening on port ${this.port}`)
+ logger.info({ component: 'Server', port: this.port }, 'RPC server listening')
resolve()
})
})
@@ -996,7 +998,7 @@ export class RPCServer {
return
}
this.server.close(() => {
- console.log('[Server] RPC server stopped')
+ logger.info({ component: 'Server' }, 'RPC server stopped')
resolve()
})
})