Skip to content

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

TypeScript

test(mcp-host): require context pressure to count only the presented tools

Alfredo Lopez22b821edf134
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 661c329b3..1c982b5aa 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.436",
+ "version": "0.1.437",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.436",
+ "version": "0.1.437",
"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 6333755e4..1462f23fd 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.436",
+ "version": "0.1.437",
"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 dcca41f40..f5da8ec55 100644
--- a/mcp-host/src/agent/__tests__/taskExecutor.test.ts
+++ b/mcp-host/src/agent/__tests__/taskExecutor.test.ts
@@ -2656,30 +2656,51 @@ describe('TaskExecutor history compaction threshold follows the context window (
})
// The loop's context manager counts the system prompt the next request carries
-// (R9-14, L-6). It reaches the manager through `LoopConfig.systemPrompt`; both
-// prompt paths must set it, daily-log snapshot included.
+// (R9-14, L-6). It reaches the manager through `LoopConfig.systemPromptFor`,
+// which the loop calls with the tools it presents on that iteration (R21-1);
+// both prompt paths must set it, daily-log snapshot included.
describe('TaskExecutor hands the system prompt to the loop (R9-14)', () => {
beforeEach(() => {
vi.clearAllMocks()
})
- async function loopSystemPrompt(deps: TaskExecutorDeps): Promise<unknown> {
+ const PRESENTED_TOOL = {
+ name: 'presented_only',
+ description: 'PRESENTED-MARKER',
+ parameters: { type: 'object' },
+ }
+
+ async function loopSystemPromptFor(
+ deps: TaskExecutorDeps
+ ): Promise<(tools: (typeof PRESENTED_TOOL)[]) => string> {
vi.mocked(runToolUseLoop).mockResolvedValueOnce({ type: 'response', content: 'ok' } as any)
await new TaskExecutor(createTask('hi'), deps).run()
const call = vi.mocked(runToolUseLoop).mock.calls.at(-1)
if (!call) throw new Error('Expected runToolUseLoop to be called')
- return call[0].systemPrompt
+ const systemPromptFor = call[0].systemPromptFor
+ if (typeof systemPromptFor !== 'function') {
+ throw new Error('Expected LoopConfig.systemPromptFor to be set')
+ }
+ return systemPromptFor
}
- it('T-R9-14f the legacy path passes the assembled identity with its daily logs', async () => {
+ it('T-R9-14f the legacy path builds the prompt over the presented tools, daily logs included', async () => {
const workspaceService = {
assembleSystemPrompt: vi.fn(async () => 'IDENTITY\n\n## Daily Log\nDAILY-LOG-ENTRY'),
} as any
- const systemPrompt = await loopSystemPrompt(createDeps({ workspaceService }))
+ const systemPromptFor = await loopSystemPromptFor(createDeps({ workspaceService }))
+
+ const withTool = systemPromptFor([PRESENTED_TOOL])
+ const withoutTool = systemPromptFor([])
expect(workspaceService.assembleSystemPrompt).toHaveBeenCalledTimes(1)
- expect(systemPrompt).toEqual(expect.stringContaining('DAILY-LOG-ENTRY'))
- expect(systemPrompt).toEqual(expect.stringContaining('powered by the test-model model'))
+ expect(withTool).toEqual(expect.stringContaining('DAILY-LOG-ENTRY'))
+ expect(withTool).toEqual(expect.stringContaining('powered by the test-model model'))
+ // The legacy port rebuilds the prompt from `context.available_tools`, so the
+ // count follows the list it is given, not the registry.
+ expect(withTool).toEqual(expect.stringContaining('PRESENTED-MARKER'))
+ expect(withoutTool).toEqual(expect.stringContaining('DAILY-LOG-ENTRY'))
+ expect(withoutTool).not.toEqual(expect.stringContaining('PRESENTED-MARKER'))
})
it('T-R9-14g the prompt-cache path passes both tiers with the daily-log snapshot', async () => {
@@ -2695,14 +2716,19 @@ describe('TaskExecutor hands the system prompt to the loop (R9-14)', () => {
})),
snapshotDailyLogs: vi.fn(async () => 'DAILY-SNAPSHOT-ENTRY'),
} as any
- const systemPrompt = await loopSystemPrompt(
+ const systemPromptFor = await loopSystemPromptFor(
createDeps({ workspaceService, promptCache: new PromptCache() })
)
+ const systemPrompt = systemPromptFor([PRESENTED_TOOL])
+
// Witness: the cache path ran, so the prompt below came from its parts.
expect(workspaceService.snapshotDailyLogs).toHaveBeenCalledTimes(1)
expect(systemPrompt).toEqual(expect.stringContaining('IDENTITY-FILE'))
expect(systemPrompt).toEqual(expect.stringContaining('DAILY-SNAPSHOT-ENTRY'))
+ // The cache path sends the parts it built once, whatever the loop
+ // presents, so the text does not depend on the list.
+ expect(systemPromptFor([])).toBe(systemPrompt)
} finally {
appConfig.promptCacheEnabled = previous
}
diff --git a/mcp-host/src/core/orchestration/__tests__/manageMessagesForIteration.test.ts b/mcp-host/src/core/orchestration/__tests__/manageMessagesForIteration.test.ts
index a8ca84f8f..730e4d326 100644
--- a/mcp-host/src/core/orchestration/__tests__/manageMessagesForIteration.test.ts
+++ b/mcp-host/src/core/orchestration/__tests__/manageMessagesForIteration.test.ts
@@ -1,80 +1,85 @@
import { describe, expect, it, vi } from 'vitest'
import { makeFakeConversation } from '../../conversation/__testing__/makeFakeConversation'
-import type { ReasoningPort, ToolRegistry } from '../../interfaces'
+import type { ContextManager, ReasoningPort, ToolRegistry } from '../../interfaces'
import { BasicSafety } from '../../safety/safety'
import type { ChatMessage, ToolDefinition } from '../../types'
import { SimpleEventEmitter } from '../eventEmitter'
import { buildLoopConfig } from '../loopConfig'
import { manageMessagesForIteration } from '../toolUseLoopRuntime'
+const PRESENTED: ToolDefinition = {
+ name: 'native_search',
+ description: 'Search',
+ parameters: { type: 'object' },
+}
+const DEFERRED: ToolDefinition = {
+ name: 'crm__search_contacts',
+ description: 'Search contacts',
+ parameters: { type: 'object' },
+}
+
+function configWith(manage: ContextManager['manage']) {
+ // The registry holds more than the loop presents, so a test can tell which
+ // list reached the manager.
+ const toolRegistry: ToolRegistry = {
+ get: () => null,
+ listDefinitions: () => [PRESENTED, DEFERRED],
+ register: vi.fn(),
+ }
+ const reasoning: ReasoningPort = {
+ respondWithTools: vi.fn(),
+ continueWithToolResults: vi.fn(),
+ }
+ const conversation = makeFakeConversation()
+ const config = buildLoopConfig({
+ reasoning,
+ toolRegistry,
+ safety: new BasicSafety(),
+ events: new SimpleEventEmitter(),
+ conversation,
+ contextManager: { manage },
+ })
+ return { config, conversation }
+}
+
describe('manageMessagesForIteration', () => {
- it('T-R2-2d hands the registry tool definitions to the context manager (#731)', async () => {
+ it('T-R2-2d hands the presented tool definitions to the context manager (#731, #780)', async () => {
// The tool schemas travel in the request the contract caps; the manager can
- // only count them if the loop passes them (review r2, M2b). The registry's
- // full list is a superset of what the loop presents, so the count errs high.
- const definitions: ToolDefinition[] = [
- { name: 'crm_search_contacts', description: 'Search', parameters: { type: 'object' } },
- ]
- const toolRegistry: ToolRegistry = {
- get: () => null,
- listDefinitions: () => definitions,
- register: vi.fn(),
- }
- const reasoning: ReasoningPort = {
- respondWithTools: vi.fn(),
- continueWithToolResults: vi.fn(),
- }
+ // only count them if the loop passes them (review r2, M2b). It passes the
+ // list it presents on this iteration, not the registry's (R21-1).
const manage = vi.fn((messages: ChatMessage[]) => messages)
- const conversation = makeFakeConversation()
- const config = buildLoopConfig({
- reasoning,
- toolRegistry,
- safety: new BasicSafety(),
- events: new SimpleEventEmitter(),
- conversation,
- contextManager: { manage },
- })
+ const { config, conversation } = configWith(manage)
const messages: ChatMessage[] = [{ role: 'user', content: 'hello' }]
- const managed = await manageMessagesForIteration(config, messages, 0, true)
+ const managed = await manageMessagesForIteration(config, messages, 0, [PRESENTED], true)
expect(managed).toBe(messages)
expect(manage).toHaveBeenCalledTimes(1)
- expect(manage).toHaveBeenCalledWith(messages, conversation, { tools: definitions })
+ expect(manage).toHaveBeenCalledWith(messages, conversation, { tools: [PRESENTED] })
})
- it('T-R9-14e hands the loop system prompt to the context manager (R9-14)', async () => {
+ it('T-R9-14e hands the system prompt built for the presented tools to the context manager (R9-14, R21-1)', async () => {
// The system prompt is not in `messages` (the reasoning port prepends it or
- // ships it out of band), yet it travels in the same capped request.
- const toolRegistry: ToolRegistry = {
- get: () => null,
- listDefinitions: () => [],
- register: vi.fn(),
- }
- const reasoning: ReasoningPort = {
- respondWithTools: vi.fn(),
- continueWithToolResults: vi.fn(),
- }
+ // ships it out of band), yet it travels in the same capped request. On the
+ // legacy path it describes the tools it is built over.
const manage = vi.fn((messages: ChatMessage[]) => messages)
- const conversation = makeFakeConversation()
- const config = buildLoopConfig({
- reasoning,
- toolRegistry,
- safety: new BasicSafety(),
- events: new SimpleEventEmitter(),
- conversation,
- contextManager: { manage },
- })
- config.systemPrompt = 'identity\n\n## Daily Log (frozen at session start)\nentry'
+ const { config, conversation } = configWith(manage)
+ const systemPromptFor = vi.fn(
+ (tools: ToolDefinition[]) =>
+ `identity\n\n## Daily Log (frozen at session start)\nentry\n${tools.map(t => t.name).join(',')}`
+ )
+ config.systemPromptFor = systemPromptFor
const messages: ChatMessage[] = [{ role: 'user', content: 'hello' }]
- const managed = await manageMessagesForIteration(config, messages, 0, true)
+ const managed = await manageMessagesForIteration(config, messages, 0, [PRESENTED], true)
expect(managed).toBe(messages)
+ expect(systemPromptFor).toHaveBeenCalledTimes(1)
+ expect(systemPromptFor).toHaveBeenCalledWith([PRESENTED])
expect(manage).toHaveBeenCalledTimes(1)
expect(manage).toHaveBeenCalledWith(messages, conversation, {
- tools: [],
- systemPrompt: 'identity\n\n## Daily Log (frozen at session start)\nentry',
+ tools: [PRESENTED],
+ systemPrompt: 'identity\n\n## Daily Log (frozen at session start)\nentry\nnative_search',
})
})
})
diff --git a/mcp-host/src/core/orchestration/__tests__/presentedToolsPressure.test.ts b/mcp-host/src/core/orchestration/__tests__/presentedToolsPressure.test.ts
new file mode 100644
index 000000000..7a0f307a3
--- /dev/null
+++ b/mcp-host/src/core/orchestration/__tests__/presentedToolsPressure.test.ts
@@ -0,0 +1,168 @@
+/**
+ * R21-1 (#780) — pressure counts the tool schemas the request carries.
+ *
+ * When the controller presents only the native tools (Codex `discovery`, or the
+ * legacy bridge latch), the deferred MCP schemas never reach the model. The
+ * context manager must count the list the loop hands to `reasoning` on that
+ * iteration, not the registry's full catalog.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { makeFakeConversation } from '../../conversation/__testing__/makeFakeConversation'
+import type { ContextManageOptions, ReasoningPort, Tool, ToolRegistry } from '../../interfaces'
+import { BasicSafety } from '../../safety/safety'
+import type {
+ ChatMessage,
+ ReasoningContext,
+ RespondResult,
+ ToolDefinition,
+ ToolOutput,
+} from '../../types'
+import { DeferrableToolController, type LatchStore } from '../deferrableToolController'
+import { SimpleEventEmitter } from '../eventEmitter'
+import { DefaultLoopController, buildLoopConfig } from '../loopConfig'
+import { runToolUseLoop } from '../toolUseLoop'
+
+const NATIVE = 'native_search'
+const DEFERRED = 'crm__export_contacts'
+// One deferred schema large enough to dominate the gauge if it were counted.
+const DEFERRED_DESCRIPTION = 'x'.repeat(40_000)
+
+function makeTool(name: string, description: string): Tool {
+ return {
+ name: () => name,
+ description: () => description,
+ parametersSchema: () => ({ type: 'object', properties: {} }),
+ execute: vi.fn(
+ async (): Promise<ToolOutput> => ({
+ content: `${name} result`,
+ duration_ms: 1,
+ is_error: false,
+ })
+ ),
+ requiresSanitization: () => false,
+ requiresApproval: () => false,
+ }
+}
+
+function makeRegistry(tools: Tool[]): ToolRegistry {
+ const map = new Map(tools.map(t => [t.name(), t]))
+ return {
+ get: (name: string) => map.get(name) ?? null,
+ listDefinitions: () =>
+ tools.map(t => ({
+ name: t.name(),
+ description: t.description(),
+ parameters: t.parametersSchema(),
+ })),
+ register: vi.fn(),
+ }
+}
+
+function makeLatch(): LatchStore {
+ let value: boolean | undefined
+ return {
+ get: () => value,
+ set: v => {
+ value = v
+ },
+ }
+}
+
+function names(tools: ToolDefinition[] | undefined): string[] {
+ return (tools ?? []).map(t => t.name)
+}
+
+async function runWithController(controller: DeferrableToolController) {
+ const results: RespondResult[] = [
+ { type: 'tool_calls', calls: [{ id: 'tc_1', name: NATIVE, arguments: {} }] },
+ { type: 'text', content: 'Done' },
+ ]
+ let index = 0
+ const next = async () => results[index++] ?? { type: 'error' as const, error: new Error('none') }
+ const reasoning: ReasoningPort = {
+ respondWithTools: vi.fn(next),
+ continueWithToolResults: vi.fn(next),
+ }
+ const manage = vi.fn(
+ (messages: ChatMessage[], _conversation: unknown, _options?: ContextManageOptions) => messages
+ )
+ const registry = makeRegistry([
+ makeTool(NATIVE, 'Search natively'),
+ makeTool(DEFERRED, DEFERRED_DESCRIPTION),
+ ])
+ const config = buildLoopConfig({
+ reasoning,
+ toolRegistry: registry,
+ safety: new BasicSafety(),
+ events: new SimpleEventEmitter(),
+ conversation: makeFakeConversation(),
+ loopController: controller,
+ contextManager: { manage },
+ })
+
+ const outcome = await runToolUseLoop(config, [{ role: 'user', content: 'Hi' }])
+
+ const presented = [
+ ...vi.mocked(reasoning.respondWithTools).mock.calls.map(c => c[0]),
+ ...vi.mocked(reasoning.continueWithToolResults).mock.calls.map(c => c[0]),
+ ].map((context: ReasoningContext) => names(context.available_tools))
+ const counted = manage.mock.calls.map(c => names(c[2]?.tools))
+ return { outcome, registry, presented, counted }
+}
+
+describe('R21-1 the context manager counts the presented tools (#780)', () => {
+ it.each([
+ [
+ 'Codex discovery mode',
+ () =>
+ new DeferrableToolController(
+ new DefaultLoopController(),
+ new Set([NATIVE]),
+ { dynamicToolsEnabled: false, dynamicToolsThreshold: 60, codexMode: 'discovery' },
+ makeLatch()
+ ),
+ ],
+ [
+ 'the legacy bridge latch',
+ () =>
+ new DeferrableToolController(
+ new DefaultLoopController(),
+ new Set([NATIVE]),
+ { dynamicToolsEnabled: true, dynamicToolsThreshold: 0 },
+ makeLatch()
+ ),
+ ],
+ ])('T-R21-1a %s: pre-LLM and post-tool pressure see only native tools', async (_, build) => {
+ const { outcome, registry, presented, counted } = await runWithController(build())
+
+ // Witnesses: the loop ran two iterations, the registry carries the deferred
+ // schema, and the controller withheld it from both requests.
+ expect(outcome).toMatchObject({ type: 'response', content: 'Done' })
+ expect(names(registry.listDefinitions())).toEqual([NATIVE, DEFERRED])
+ expect(presented).toEqual([[NATIVE], [NATIVE]])
+
+ // pre-LLM (iteration 0), post-tool (iteration 0), pre-LLM (iteration 1).
+ expect(counted).toEqual([[NATIVE], [NATIVE], [NATIVE]])
+ })
+
+ it('T-R21-1b direct presentation still counts every registered schema', async () => {
+ const { presented, counted } = await runWithController(
+ new DeferrableToolController(
+ new DefaultLoopController(),
+ new Set([NATIVE]),
+ { dynamicToolsEnabled: false, dynamicToolsThreshold: 60, codexMode: 'direct' },
+ makeLatch()
+ )
+ )
+
+ expect(presented).toEqual([
+ [NATIVE, DEFERRED],
+ [NATIVE, DEFERRED],
+ ])
+ expect(counted).toEqual([
+ [NATIVE, DEFERRED],
+ [NATIVE, DEFERRED],
+ [NATIVE, DEFERRED],
+ ])
+ })
+})