Skip to main content
Glama

ctxtrim

Shrink tool outputs before they hit your agent's context — deterministically, auditably, with zero dependencies. 在工具输出进入 agent 上下文之前把它瘦身——确定性、可审计、零依赖。

License: MIT Python 3.9+ Tests Dependencies

ctxtrim terminal demo


Why / 为什么

Coding agents burn their context window on redundant tool output: 50 repeated build lines, 3,000-line unchanged diffs, base64 blobs, pretty-printed JSON. That means slower agents, higher bills, and worse answers. Existing tools fix this with proxies and runtimes tied to one agent.

ctxtrim is the missing library: pure functions your tool, MCP server, or agent harness calls before handing text to an LLM. Same input → same output, every time. Every saved character is accounted for, rule by rule. And because tool output is untrusted input, ctxtrim also audits it for prompt injection and hidden payloads, and keeps a tamper-evident log of what entered the context.

编码 agent 的上下文窗口被冗余的工具输出吃掉:重复 50 遍的构建日志、3000 行未变更的 diff、base64 大块、格式化过的 JSON。结果是 agent 更慢、更贵、回答更差。现有方案 都是绑定单一 agent 的代理或运行时。

ctxtrim 补上缺失的库这一层:你的工具、MCP server、agent harness 在把文本交给 LLM 之前调用它。相同输入必得相同输出,每个字符的去向都有逐条规则留痕。工具输出是 不可信输入,ctxtrim 顺带审计提示注入与隐藏载荷,并保存防篡改日志。

Related MCP server: genpark-agent-context-dynamic-compressor-skill

Quick start / 快速开始

pip install ctxtrim        # or: pip install git+https://github.com/jsk-hash/ctxtrim.git
# shrink a tool output (deterministic, rule-by-rule trail on stderr)
$ ctxtrim shrink build.log --profile balanced
[... compressed output ...]
---
ctxtrim: 1759 -> 372 chars (78.9% saved, 1 strategies)

# respect a hard budget (lossy cut only as a last resort)
$ ctxtrim shrink huge.json --budget 2000 --profile tight

# audit untrusted text before it enters your agent's context
$ ctxtrim audit untrusted.txt
ctxtrim audit: risk score 60/100
  [HIGH] instruction-override x1 lines=3 — Text asks the model to ignore its instructions...

# share one context budget across several tool outputs
$ ctxtrim split --names log,db --need build.log --need db.json --total 4000

# prove later that nothing was edited
$ ctxtrim verify journal.jsonl
journal OK: 3 record(s)

MCP server / 作为 MCP 服务器运行

ctxtrim serve speaks MCP (newline-delimited JSON-RPC over stdio), so any MCP client can call ctxtrim as tools — add one block to your client config:

{ "mcpServers": { "ctxtrim": { "command": "ctxtrim", "args": ["serve"] } } }

Tools exposed: ctxtrim_shrink, ctxtrim_audit, ctxtrim_split.

# or from source
python -m ctxtrim.mcp_server

More recipes (Claude Code hook, in-process library wrapper): docs/integrate.md

from ctxtrim import compress, audit, allocate_pairs, Journal

res = compress(tool_output, budget=2000, profile="balanced")
res.ratio          # 0.483 — chars saved
res.trail()        # per-strategy accounting, exactly what ran
res.text           # still valid JSON if the input was JSON

findings = audit(untrusted_text)          # prompt-injection & payload heuristics
budgets = allocate_pairs(["log", "db"], [len(a), len(b)], 4000)

Journal("journal.jsonl").append(kind="shrink",
                                input_sha256=sha256(tool_output),
                                output_sha256=sha256(res.text))

Benchmarks / 基准

python tools/benchmark.py (bundled & synthetic workloads, budget=2000):

workload

original

ctxtrim

saved

still parses as JSON

build_log.txt

1,759

372

78.9%

—

tool_output.json

3,696

1,911

48.3%

✅ yes

test_runner_output

58,199

40,847

29.8%

—

diff_400ctx

13,177

323

97.5%

—

Deterministic end-to-end; the 67-test suite includes a byte-level determinism check.

How it works / 工作原理

Strategies run in a fixed order; each one is optional and reports its own savings. Lossless-ish strategies run always; the lossy head/tail cut runs only under a budget, only in the tight profile.

#

strategy

what it does

lossy?

1

blob_placeholder

replaces giant base64/hex runs (>1200 chars) with [ctxtrim blob N chars sha256=…]

no*

2

json_compact

drops null/empty fields, trims arrays to head-10+tail-10 with an elision marker, truncates giant string values — output stays valid JSON

near-lossless

3

log_dedupe

collapses runs of ≥3 identical consecutive lines to line + [ctxtrim repeat xN]

no

4

ws_normalize

strips trailing spaces, collapses blank-line runs, dedents common indent

no

5

diff_collapse

collapses >8-line runs of unchanged diff context to 3+marker+3

no*

6

head_tail

cuts to budget keeping 70% head / 30% tail with an elision marker

yes

Profiles: safe (1–4, never loses content), balanced (1–5, default), tight (1–6, budget-aware).

* elided content is replaced by a SHA-256 digest + exact byte count, so the omission is explicit, not silent.

Audit rules / 审计规则

ctxtrim audit scans untrusted text with deterministic heuristics (regex only, no model calls): instruction-override phrasing, role hijacking, spoofed system/chat-template tags, curl … | sh style exfiltration, destructive commands, credential-shaped literals, hidden/bidi Unicode, large encoded blobs. Findings carry severity, line numbers and a hint. Heuristics raise attention; they are not a security guarantee — that honesty is part of the design.

Journal / 审计日志

Journal appends JSONL records where each record's SHA-256 covers the record and the previous record's hash. verify() walks the whole chain and reports exactly which record was edited or removed. Stdlib only, greppable, diffable.

Security posture / 安全姿态

  • Zero runtime dependencies — nothing to hijack in a supply chain; CI fails if dependencies stops being [].

  • No network, no process spawning, no dynamic execution — eval/exec/compile/__import__/subprocess/socket/urllib/pickle/ctypes are banned from src/ and a dedicated test enforces it.

  • Deterministic transforms — reviewed line by line; no model-in-the-loop rewriting of your content.

  • See SECURITY.md for the threat model and reporting policy.

Comparison / 与同类项目的差异

proxies / runtimes (rtk, headroom…)

meme tools

ctxtrim

integration

binds to one agent/workflow

chat-only

embeddable library + standalone CLI

transform

varies, often model-assisted

lossy joke

deterministic rules, per-rule trail

reproducibility

not guaranteed

no

same input → same output, tested

injection auditing

no

no

built-in heuristics

tamper evidence

no

no

hash-chained journal

dependencies

many

varies

zero (stdlib only)

Complementary, not competitive: use ctxtrim inside whatever harness you run.

Requirements / 环境

Python 3.9 – 3.13, any OS. Nothing else.

Roadmap / 路线图

  • MCP server wrapper (ctxtrim serve) exposing shrink/audit/split as tools

  • Claude Code hook recipe (one-file integration guide)

  • pluggable custom strategies via entry points

  • optional token-accurate budgeting (tokenizer adapters, still optional deps)

  • --report html static audit report

Contributing / 参与

PRs welcome — see CONTRIBUTING.md. Every PR runs the full suite including the source-security self-audit.

License / 协议

MIT — the most permissive mainstream license. Use it, fork it, ship it.

Acknowledgements / 致谢

The problem statement was validated by the 2025–2026 wave of context-cost tools (rtk, headroom, context-mode, caveman & friends). ctxtrim takes the idea to the library layer with determinism and auditability as first-class citizens.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents and MCP-compliant clients to dynamically shrink long-horizon context windows, pruning verbose tool outputs, HTML boilerplate, and semantic redundancy by roughly 40-70% without frontier LLM round-trips. Runs deterministically as a zero-dependency Python stdio server, accepting a payload plus optional compression and risk-bound options.
      7
      -
    • F
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables MCP-compatible clients and autonomous agents to dynamically compress long-horizon context by pruning verbose tool outputs, HTML boilerplate, and semantic redundancy by 40-70%. It reduces token burn and latency through deterministic, zero-dependency processing.
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables MCP-compatible developer environments to shrink verbose tool outputs—test logs, git diffs, directory listings, and file dumps—before they reach the context window, preserving compiler errors, failure signatures, and decisive anchors. It runs either as direct callable tools or as a transparent proxy wrapping other MCP servers such as filesystem, git, or terminal providers.
      1
      MIT