Skip to main content

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 顺带审计提示注入与隐藏载荷,并保存防篡改日志。

Quick start / 快速开始

pip install ctxtrim        # or: pip install git+https://github.com/ctxtrim/ctxtrim
# 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
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.

Metadata

Release files for ctxtrim 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for ctxtrim 0.1.0
File Interpreter ABI Platform Actions
ctxtrim-0.1.0-py3-none-any.whl Python 3 none any Details for ctxtrim-0.1.0-py3-none-any.whl

Release files / ctxtrim-0.1.0-py3-none-any.whl

Download URL ctxtrim-0.1.0-py3-none-any.whl
Size 21.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b2e0ffdef673555730ba801264472b7959888efb6b244f18ff5c72206ed14950
BLAKE2b-256 checksum
How to use checksums
7debddb41361cb7c1c8b32bcae2b20fff44856c3b54a5ba9d4bfce07cb7bc0bb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Security for ctxtrim 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page