Skip to content

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

TypeScript

feat(guardrails): add token-trim built-in for the llm lane (phase 2)

Andy Pavia3921c31001ca
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 8519e148d..15f46834e 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.239",
+ "version": "0.1.240",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.239",
+ "version": "0.1.240",
"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 2dcb39dec..0fd114fe5 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.239",
+ "version": "0.1.240",
"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/guardrails/index.ts b/mcp-host/src/core/guardrails/index.ts
index 0699d26ef..aaac41702 100644
--- a/mcp-host/src/core/guardrails/index.ts
+++ b/mcp-host/src/core/guardrails/index.ts
@@ -27,4 +27,6 @@ export { buildLlmBuiltinChain } from './llm/builtinChain'
export type { BuiltinItem, RequestShaper } from './llm/builtinChain'
export { applyPromptShaping } from './llm/builtins/promptShaping'
export type { PromptShapingConfig } from './llm/builtins/promptShaping'
+export { applyTokenTrim } from './llm/builtins/tokenTrim'
+export type { TokenTrimConfig } from './llm/builtins/tokenTrim'
export { guardrailDecisionsTotal, guardrailBoundaryDurationMs } from './metrics'
diff --git a/mcp-host/src/core/guardrails/llm/__tests__/builtinChain.test.ts b/mcp-host/src/core/guardrails/llm/__tests__/builtinChain.test.ts
index 37137266f..2d8b2b860 100644
--- a/mcp-host/src/core/guardrails/llm/__tests__/builtinChain.test.ts
+++ b/mcp-host/src/core/guardrails/llm/__tests__/builtinChain.test.ts
@@ -41,8 +41,22 @@ describe('buildLlmBuiltinChain', () => {
expect(r.temperature).toBeUndefined()
})
- it('skips unknown built-in types', () => {
+ it('token-trim on an empty message list is a no-op', () => {
const r = req()
- expect(buildLlmBuiltinChain([{ type: 'token-trim' }])(r)).toEqual(r) // not yet implemented → no-op
+ expect(buildLlmBuiltinChain([{ type: 'token-trim' }])(r)).toBe(r) // nothing to prune
+ })
+
+ it('skips genuinely unknown built-in types', () => {
+ const r = req()
+ // Cast: an admin-invalid type is rejected at admission in prod; here it's skipped.
+ expect(buildLlmBuiltinChain([{ type: 'nonsense' } as never])(r)).toEqual(r)
+ })
+
+ it('composes prompt-shaping + token-trim', () => {
+ const shape = buildLlmBuiltinChain([
+ { type: 'token-trim', config: { maxInputTokens: 1_000_000 } },
+ { type: 'prompt-shaping', config: { temperature: 0.3 } },
+ ])
+ expect(shape(req()).temperature).toBe(0.3)
})
})
diff --git a/mcp-host/src/core/guardrails/llm/__tests__/tokenTrim.test.ts b/mcp-host/src/core/guardrails/llm/__tests__/tokenTrim.test.ts
new file mode 100644
index 000000000..35265542d
--- /dev/null
+++ b/mcp-host/src/core/guardrails/llm/__tests__/tokenTrim.test.ts
@@ -0,0 +1,29 @@
+/**
+ * token-trim built-in tests (spec §7.2). Covers the built-in's own gate logic
+ * (budget gate, passthrough). The four prune passes themselves are covered by
+ * the existing prePrune suite; this just verifies the thin request adapter.
+ */
+import { describe, expect, it } from 'vitest'
+import type { ChatMessage, ToolCompletionRequest } from '../../../types'
+import { applyTokenTrim } from '../builtins/tokenTrim'
+
+const req = (messages: ChatMessage[] = []): ToolCompletionRequest => ({ messages, tools: [] })
+
+describe('applyTokenTrim', () => {
+ it('under budget → request unchanged (same reference)', () => {
+ const r = req([{ role: 'user', content: 'hi' } as ChatMessage])
+ expect(applyTokenTrim(r, { maxInputTokens: 1_000_000 })).toBe(r)
+ })
+
+ it('empty message list → unchanged', () => {
+ const r = req([])
+ expect(applyTokenTrim(r, {})).toBe(r)
+ })
+
+ it('does not mutate the input request', () => {
+ const messages = [{ role: 'user', content: 'hi' } as ChatMessage]
+ const r = req(messages)
+ applyTokenTrim(r, { maxInputTokens: 1_000_000 })
+ expect(r.messages).toBe(messages)
+ })
+})
diff --git a/mcp-host/src/core/guardrails/llm/builtinChain.ts b/mcp-host/src/core/guardrails/llm/builtinChain.ts
index 0736251cf..9ff1a6328 100644
--- a/mcp-host/src/core/guardrails/llm/builtinChain.ts
+++ b/mcp-host/src/core/guardrails/llm/builtinChain.ts
@@ -8,6 +8,7 @@
*/
import type { ToolCompletionRequest } from '../../types'
import { type PromptShapingConfig, applyPromptShaping } from './builtins/promptShaping'
+import { type TokenTrimConfig, applyTokenTrim } from './builtins/tokenTrim'
/** One entry of `guardrails.builtins[]` (spec §7.2). */
export interface BuiltinItem {
@@ -45,8 +46,10 @@ export function buildLlmBuiltinChain(builtins: unknown[] | undefined): RequestSh
if (item.type === 'prompt-shaping') {
const cfg = (item.config ?? {}) as PromptShapingConfig
shapers.push(req => applyPromptShaping(req, cfg))
+ } else if (item.type === 'token-trim') {
+ const cfg = (item.config ?? {}) as TokenTrimConfig
+ shapers.push(req => applyTokenTrim(req, cfg))
}
- // TODO(phase2): item.type === 'token-trim' → reuse prePrune (§7.2).
}
if (shapers.length === 0) return IDENTITY
diff --git a/mcp-host/src/core/guardrails/llm/builtins/tokenTrim.ts b/mcp-host/src/core/guardrails/llm/builtins/tokenTrim.ts
new file mode 100644
index 000000000..5189cccec
--- /dev/null
+++ b/mcp-host/src/core/guardrails/llm/builtins/tokenTrim.ts
@@ -0,0 +1,57 @@
+/**
+ * `token-trim` built-in (spec §7.2) — a first-party, in-process `pre` rewrite
+ * contributor that reduces input tokens toward a budget by reusing the existing
+ * four-pass `core/extensions/prePrune.ts` (dedup, one-line summaries, JSON-safe
+ * arg truncation, historical-media strip). LLM-free; protects the tail turns.
+ *
+ * Budget-gated: when `maxInputTokens` is set and the request is already under it,
+ * the request is left unchanged. Ordering/config are uniform with the built-in
+ * chain (spec §7.2). Note: an operator who also enables the context-manager
+ * prePrune will prune twice (idempotent-ish) — that is a config choice.
+ */
+import {
+ DEFAULT_PRE_PRUNE_OPTIONS,
+ type PrePruneOptions,
+ prePrune,
+} from '../../../extensions/prePrune'
+import type { ToolCompletionRequest } from '../../../types'
+
+export interface TokenTrimConfig {
+ /** Only trim when the request's heuristic input tokens exceed this budget. */
+ maxInputTokens?: number
+ protectedTailTurns?: number
+ summaryThresholdTokens?: number
+ maxArgsBytes?: number
+ dedupEnabled?: boolean
+ oneLineSummariesEnabled?: boolean
+ jsonSafeTruncateEnabled?: boolean
+ stripMediaEnabled?: boolean
+}
+
+function toPrePruneOptions(config: TokenTrimConfig): PrePruneOptions {
+ return {
+ protectedTailTurns: config.protectedTailTurns ?? DEFAULT_PRE_PRUNE_OPTIONS.protectedTailTurns,
+ summaryThresholdTokens:
+ config.summaryThresholdTokens ?? DEFAULT_PRE_PRUNE_OPTIONS.summaryThresholdTokens,
+ maxArgsBytes: config.maxArgsBytes ?? DEFAULT_PRE_PRUNE_OPTIONS.maxArgsBytes,
+ dedupEnabled: config.dedupEnabled ?? DEFAULT_PRE_PRUNE_OPTIONS.dedupEnabled,
+ oneLineSummariesEnabled:
+ config.oneLineSummariesEnabled ?? DEFAULT_PRE_PRUNE_OPTIONS.oneLineSummariesEnabled,
+ jsonSafeTruncateEnabled:
+ config.jsonSafeTruncateEnabled ?? DEFAULT_PRE_PRUNE_OPTIONS.jsonSafeTruncateEnabled,
+ stripMediaEnabled: config.stripMediaEnabled ?? DEFAULT_PRE_PRUNE_OPTIONS.stripMediaEnabled,
+ }
+}
+
+/** Apply token-trim to a completion request, returning a new request (or the same when nothing changed). */
+export function applyTokenTrim(
+ request: ToolCompletionRequest,
+ config: TokenTrimConfig
+): ToolCompletionRequest {
+ const result = prePrune(request.messages, toPrePruneOptions(config))
+ // Budget gate: under budget → leave the request untouched.
+ if (config.maxInputTokens !== undefined && result.preTokens <= config.maxInputTokens)
+ return request
+ if (result.messages === request.messages) return request // no pass fired
+ return { ...request, messages: result.messages }
+}