Skip to content

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

TypeScript

fix(mcp-host): count the tool schemas in compaction pressure (#731)

Alfredo Lopez1987fdd73560
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index d75c834a9..14d27dc12 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.383",
+ "version": "0.1.384",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.383",
+ "version": "0.1.384",
"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 61c1f2f95..5d560e00c 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.383",
+ "version": "0.1.384",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/extensions/contextManager.ts b/mcp-host/src/core/extensions/contextManager.ts
index 6a4d45aed..f3e7be30b 100644
--- a/mcp-host/src/core/extensions/contextManager.ts
+++ b/mcp-host/src/core/extensions/contextManager.ts
@@ -25,9 +25,10 @@ import { parseStructuredSummary } from '../conversation/structuredSummaryParser'
import { ContextManageOptions, ContextManager, LlmPort } from '../interfaces'
import type { AgentEventEmitter } from '../interfaces'
import { validateToolLinkages } from '../orchestration/toolUseLoop'
+import { heuristicCountTools } from '../tokenizer/heuristic'
import { tokenizerDryrunDelta, tokenizerDryrunTierMismatchTotal } from '../tokenizer/metrics'
import type { TokenCounter } from '../tokenizer/tokenCounter'
-import { ChatMessage, CompactionState, Conversation } from '../types'
+import { ChatMessage, CompactionState, Conversation, ToolDefinition } from '../types'
import { type PrePruneOptions, clerumPrePruneSavingsTokensTotal, prePrune } from './prePrune'
import { buildStructuredSummaryPrompt } from './structuredSummaryTemplate'
@@ -305,7 +306,8 @@ export class PressureContextManager implements ContextManager {
return postMessages
}
- const pressure = await this.computePressure(messages)
+ const tools = options?.tools ?? []
+ const pressure = await this.computePressure(messages, tools)
if (pressure < 0.8) {
return messages // Passthrough — does NOT touch compactionState (no attempt made).
@@ -327,7 +329,7 @@ export class PressureContextManager implements ContextManager {
clerumPrePruneSavingsTokensTotal.inc(savings)
}
this.emitPrePruneEvent(conversation.id, result)
- const newPressure = await this.computePressure(working)
+ const newPressure = await this.computePressure(working, tools)
if (newPressure < 0.8) {
return working // pre-prune alone was enough — skip the tier.
}
@@ -480,16 +482,18 @@ export class PressureContextManager implements ContextManager {
* delta and any tier mismatch are emitted as metrics for the bake-week.
* - dryRun=false: the counter (with `lastObservedInputTokens` shortcut)
* drives the decision directly.
+ * Every branch counts `tools` with the messages: both travel in the request
+ * the provider caps (#731).
*/
- private async computePressure(messages: ChatMessage[]): Promise<number> {
+ private async computePressure(messages: ChatMessage[], tools: ToolDefinition[]): Promise<number> {
if (!this.tokenCounter) {
- return estimateTokens(messages) / this.maxTokens
+ return (estimateTokens(messages) + heuristicCountTools(tools)) / this.maxTokens
}
if (this.dryRun) {
- const heuristic = estimateTokens(messages)
+ const heuristic = estimateTokens(messages) + heuristicCountTools(tools)
let real: number
try {
- real = await this.measureWithCounter(messages)
+ real = await this.measureWithCounter(messages, tools)
} catch (err) {
logger.warn({ err }, 'dryrun counter failed; using heuristic')
return heuristic / this.maxTokens
@@ -506,17 +510,20 @@ export class PressureContextManager implements ContextManager {
}
return heuristic / this.maxTokens
}
- return (await this.measureWithCounter(messages)) / this.maxTokens
+ return (await this.measureWithCounter(messages, tools)) / this.maxTokens
}
- private async measureWithCounter(messages: ChatMessage[]): Promise<number> {
+ private async measureWithCounter(
+ messages: ChatMessage[],
+ tools: ToolDefinition[]
+ ): Promise<number> {
// The `lastObservedInputTokens` shortcut (Hermes `update_from_response`)
// is intentionally NOT applied here in the first PR: the call site runs
// once per loop iteration so the per-decision call is affordable, and
// skipping `count()` would risk under-counting messages added since the
// last response. T2.2 (prompt cache) revisits this with a per-iteration
// shape diff.
- return this.tokenCounter!.count(messages)
+ return this.tokenCounter!.count(messages, tools)
}
/**
diff --git a/mcp-host/src/core/interfaces.ts b/mcp-host/src/core/interfaces.ts
index 3799a2f76..0fae23562 100644
--- a/mcp-host/src/core/interfaces.ts
+++ b/mcp-host/src/core/interfaces.ts
@@ -202,6 +202,14 @@ export interface ContextManageOptions {
* Automatic compactions (no focus) continue to use the auxiliary port.
*/
useMainLlm?: boolean
+
+ /**
+ * Tool definitions that travel with the next request. They share the
+ * request byte cap with the messages, so pressure counts them too (#731).
+ * The loop passes the registry's full list, a superset of what it presents,
+ * so the count errs high.
+ */
+ tools?: ToolDefinition[]
}
export interface ContextManager {
diff --git a/mcp-host/src/core/orchestration/toolUseLoopRuntime.ts b/mcp-host/src/core/orchestration/toolUseLoopRuntime.ts
index 2145831a6..2a5a72610 100644
--- a/mcp-host/src/core/orchestration/toolUseLoopRuntime.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoopRuntime.ts
@@ -45,7 +45,9 @@ export async function manageMessagesForIteration(
const beforeCount = messages.length
// P.5: the canonical signature requires the conversation so the manager's
// defensive guard and tier selection can see `pending_approval`/state.
- const managed = await config.contextManager.manage(messages, config.conversation)
+ const managed = await config.contextManager.manage(messages, config.conversation, {
+ tools: config.toolRegistry.listDefinitions(),
+ })
if (managed.length < beforeCount) {
if (logCompaction) {
logger.debug({ beforeCount, afterCount: managed.length, iteration }, 'Context compacted')