
llmtrim
io.github.fkiene由 GitHub 帳號 fkiene 發布v0.13.4更新於 Nov 3, 2026
MCP server and proxy that compresses LLM prompts, tool output, and replies to cut token cost.
概覽
llmtrim 提供提示詞壓縮工具,讓助理壓縮 LLM 請求內容與文字以降低 token 成本,並可用本機代理處理即時流量。
- 可以做什麼
- 依指定供應商(OpenAI、Anthropic 等)壓縮完整的 LLM 請求內容並回傳精簡版本
- 壓縮純文字或工具輸出,例如日誌、diff 與 grep 結果,折疊重複行並保留錯誤原文
- 讀取與 status 指令相同的本機帳本,回報 token 與費用節省情形
- 同一引擎也可作為命令列工具、函式庫或本機 HTTPS 代理使用,在請求途中進行精簡
- 適用情境
- 當助理或代理迴圈送出的請求含有大量建置日誌、工具 schema、貼上的上下文或大型 JSON 陣列,而你希望在不改變工具與答案的前提下減少計費 token 時適用。也適合在採用代理前先查看實測節省效果。
- 執行需求
- 以本機程序執行,需安裝 npm 套件 @llmtrim/cli 並透過 mcp 子指令啟動 MCP 伺服器。此工具不儲存 API 金鑰,MCP 伺服器本身未宣告任何環境變數或請求標頭。
安裝
在 SourceWeft 中
- 開啟 儀表板中的 llmtrim,將其新增到工作區。
- 為需要使用其工具的對話啟用該服務。
Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。
其他 MCP 客戶端
參照 儲存庫 中的啟動說明。
README
llmtrim
Local proxy that compresses LLM API traffic so you pay less. Same answers, smaller bill.
−31% input · −74% output · −66% round-trip cost · 112 live A/B cases · ~5 ms/call · no model to load
Using Claude Code? One install also gets you /sub
to serve it through CLIProxyAPI.
Proxy · CLI · MCP · library (Python · Ruby · Swift · Kotlin · JS/WASM)
[CI] [License: MPL 2.0] [crates.io] [npm] [npm downloads] [Rust 1.88+]
What it does • Install • Day to day • In action • Works with • Claude Code • Numbers • Config • CLI & library
What it does
You run Claude Code, Codex, Cursor, or your own app. Every turn, the tool sends a large request: system prompt, tools, history, raw command output. You pay for every token of that, including the parts that do not help the model.
A 200-line build log with two errors. Tool schemas resent on every call. JSON with hundreds of near-identical rows. That bulk is still billed.
llmtrim sits on your machine as a local proxy, trims the waste, and forwards a smaller request. The reply is unchanged. You keep the same tools and answers; you spend less.
Compression cannot raise your bill or break a request; worst case is zero savings. Everything runs locally, nothing is sent to us. In action →
For Claude Code the same install also wires /sub to route sessions through another subscription. Details →
Get started
That's it. setup starts a local proxy and wires your shell. When Claude Code is present, it also turns on /sub. You do not run a separate install for that.
Any tool that honors
HTTPS_PROXYworks (Claude Code, Codex, Cursor, Aider, your SDK). GitHub Copilot does not (certificate pinning). Full list →
Other installers (Homebrew, curl, Scoop, Cargo, Docker)
Full options: INSTALL.md.
Desktop tray (menu bar / system tray)
Menu-bar / system-tray popover with the same savings numbers. Bundled in Homebrew, Scoop, and npm; setup can enable open-at-login. Open with llmtrim tray. On Linux desktops, interactive ensure can fetch the tray binary from the latest release (needs libwebkit2gtk-4.1 and libayatana-appindicator3).
Is this safe?
Same technique as mitmproxy, scoped to LLM API hosts only. setup changes three things; llmtrim uninstall reverses all three:
- Private CA in
~/.llmtrim/(name-constrained; cannot intercept your bank or email) - Shell env:
HTTPS_PROXY+ CA trust - Login service: daemon at login
No API keys stored (your tool's auth is forwarded). Prompts never touch disk; only anonymous token counts. Recoverable tool results stay in bounded daemon RAM for five hours by default and disappear on restart. Full threat model: SECURITY.md.
Day to day
After setup, update, or ensure, owned Claude Code /sub stays in sync with the binary.
Time series: llmtrim status --daily · --weekly · --monthly · --json · --csv.
In action
An agent ran a build. The tool returned 58 lines; two were errors. All 58 would have been billed.
4,662 chars → 978 (−79%). Errors stay verbatim. Repeated INFO lines fold into a template plus the values (lossless when the range is regular).
Try it on a request body of your own:
Log folding is one stage. Others kick in on different waste:
[!IMPORTANT] Compression cannot raise your bill or break a request. Each stage is re-measured with the provider's real tokenizer and undone if it does not save tokens. If the provider rejects the compressed body, the original is resent. Worst case is zero savings.
Existing prompt-cache prefixes (cache_control) are left alone. First-arrival recoverable shaping (llmtrim recall r_…) is off by default; live-zone tool-output windowing still runs, and a re-run of the same tool ships in full. To skip shaping for a command (verbatim stdout, including a terminal trailer), set toolout_passthrough = ["*gpt.sh*"] or prefix the command with LLMTRIM_TOOL_OUTPUT=passthrough. Lines starting with LLMTRIM_KEEP: survive windowing even when the rest is clipped.
All 10 compressors
Stages run in savings order. Nothing under a cache_control marker is rewritten.
Default auto enables each stage only where it pays. safe is lossless-only. Config →
Claude Code
When ~/.claude exists, setup, update, and ensure wire /sub (and routed subagents). No separate install command for that.
Subscription reroute (`sub`) (opt-in; may conflict with provider ToS)
Send Claude Code through CLIProxyAPI instead of Anthropic, or as a fallback hop when the current path fails. Login is CLIProxyAPI's TUI; decide for yourself whether that fits the provider ToS.
Interactive: llmtrim status → tab 4 Sub — Off / Always / Fallback, then e to edit the
input→output map (type to search CLIProxyAPI's catalog;
s save, a add, d delete). [ ] rotate the fallback first hop.
llmtrim update also updates CLIProxyAPI when you use it. Point LLMTRIM_CLIPROXY_URL at an
existing instance to skip the managed sidecar.
Route only a delegated Claude Code subagent while leaving the parent window unchanged:
Then ask naturally: Implement it using a Grok subagent, use Terra, or review this with GPT Terra.
Provider-only agents preserve the child request's Claude tier through the configured mapping; an
explicit model agent pins that provider model. Request-local agents override the window /sub and
global policy only for their own requests. llmtrim agents uninstall removes only llmtrim-owned
agent files and records an opt-out so ensure leaves them removed.
This window only (installed with ensure; includes subagents; survives /clear):
Sidecar: ~/.llmtrim/cliproxy/ (binary + config). Auth: ~/.cli-proxy-api when present, else
~/.llmtrim/cliproxy/auth. Env: LLMTRIM_SUB, LLMTRIM_SUB_MODE, LLMTRIM_CLIPROXY_URL,
LLMTRIM_CLIPROXY_KEY.
Anthropic /login vs claude.ai connectors: with global sub in always mode, by
default llmtrim writes a dummy ANTHROPIC_AUTH_TOKEN into ~/.claude/settings.json (same
idea as claude-code-proxy's
ANTHROPIC_AUTH_TOKEN=unused) so Claude Code does not need a live Anthropic OAuth session.
The MITM strips that dummy token and sends /v1/messages to CLIProxyAPI; non-messages
Anthropic probes are answered locally so they never return 401 Invalid bearer token.
Claude Code treats any API-key auth as overriding claude.ai login, so claude.ai connectors
are disabled while the dummy token is set. That is expected. To keep connectors (and accept
Anthropic /login when the session expires):
Restart Claude Code after sub on / sub off / sub mode / sub anthropic-login for the
settings change to take effect. Fallback whose first hop is "what's in use" still needs a real
Anthropic login.
Use it as a CLI, MCP, or library
Same engine, no proxy required. No extra model calls; compress runs in-process.
CLI pipe
Rust · Python · JS
Bindings and WASM notes: crates/llmtrim-uniffi · crates/llmtrim-wasm.
MCP server
Tools: llmtrim_compress, llmtrim_compress_text, llmtrim_stats (same ledger as status).
Works with
Any tool that honors HTTPS_PROXY and an env-provided CA:
No proxy: any MCP client can call llmtrim as tools (llmtrim mcp install), or use the CLI / library.
Providers come from the llm_providers registry (OpenAI, Anthropic, Google, DeepSeek, Mistral, xAI, Moonshot, Zhipu, Qwen, OpenRouter, …) and update with it. Non-LLM connections pass through untouched.
Configuration
Default is fine for most traffic. auto inspects each request and picks compressors by shape (tools → agent, code → code, long Q&A → rag, else aggressive).
Override with LLMTRIM_PRESET=<name> or preset = "<name>" in $XDG_CONFIG_HOME/llmtrim/config.toml:
Advanced presets
auto composes these per request shape, so most users never set them directly. Pick one when you know your traffic and want to skip shape detection:
Per-flag overrides (power users)
Every stage is individually tunable via config flags; preset wins over individual flags. The full table is long; see the field list in config.rs or run llmtrim compress --help. The most useful knobs:
Env: LLMTRIM_PRESET (preset), LLMTRIM_CONFIG (config-file path).
Runtime settings (env or config file)
These knobs are orthogonal to compression. Each resolves env-first, then from the config file, so set whichever fits. The env var wins when both are present.
extra_hosts entries must be exact hostnames (llm.acme.com, never a bare acme.com): each one widens the name-constrained MITM CA, which regenerates automatically on the next launch to cover them.
Claude Code options (subscription reroute) are under Claude Code.
Upstream proxy (corporate egress or chaining local tools)
Outbound calls use CONNECT + verifying TLS; the upstream only sees the encrypted stream.
Looping to llmtrim's own listen address is rejected. Put the variable in the daemon's
launch environment (launchd / systemd), not only your interactive shell. Profile secrets
sit in plaintext.
Companion tools on another port (e.g. headroom) are fine.
The numbers
Every case is sent twice, once original and once compressed, then both answers are scored and billed at real rates. Cost and quality are measured together, not estimated, across 112 cases:
The token cuts are model-independent (−31% input, −74% output). The dollar saving tracks the model's output-to-input price ratio: −66% here, projecting to −57% at GPT-4o rates and −59% at Claude Sonnet rates. The proxy compresses only the new-content surface and never rewrites the cache-controlled prefix, so your prompt-cache discount survives.
Accuracy preserved on standard benchmarks
The same A/B on the standard academic suites, at a conservative shape-matched preset (qwen3-next-80b, paired 95% CI). Quality is the score on the original request vs the compressed one. GSM8K comes from the frontier above (n=12); the other three are the named benchmarks readers compare against (n=20 each):
Three rows compress with no quality loss; GSM8K is the one dip:
- BFCL drops the tool schemas the query doesn't need (a menu of 2 to 37 candidates per call).
- SQuAD v2 still answers its unanswerable questions correctly.
- TruthfulQA holds factual accuracy exactly: its ~75-token prompts are almost all answer text, so the safe preset finds nothing to cut.
- GSM8K trades −8pp of accuracy for −71% cost, so measure per workload before enabling its reasoning preset. ¹Its input goes negative because that preset injects a Chain-of-Draft instruction whose payoff is output-side (see the frontier table).
Evidence and a one-line reproduce (named-benchmark snapshot):
Methodology, per-corpus frontier, and confidence intervals: crates/llmtrim-cli/bench/README.md. Reproduce it:
How it compares
Each tool compresses one slice of the request. llmtrim compresses input and output, leaves the cached prefix untouched to keep the prompt cache stable, and scores on whether the answer survives the cut, not on tokens removed. Both axes below use the o200k_base encoder and reproduce from this repo.
Input
Input reduction (deterministic) next to answer quality from a live A/B. Quality is the drop vs llmtrim at each tool's compared setting (✅ held, a statistical tie; ❌ significantly lower), so a big reduction with a ❌ means the tool bought tokens by losing answers:
Overhead is the median per-call compress time (Python wall-clock, not like-for-like CPU): Headroom and leanctx run ML on CPU here (faster on a GPU) and pay a one-time model load on top (~3 s and ~4 s); llmtrim is Rust and entroly is lexical, so neither does.
autois the quality-gated default;aggressiveaccepts lossy cuts where the gate holds.- Headroom drops to 0% with its ML disabled (its routers no-op on prose).
- leanctx and entroly are lossy with no quality gate; entroly has no low-reduction mode.
Headroom ties at matched reduction (24-25%, n=30, not significant) but its longer answers hit the model's output-token limit and get truncated 12 times to llmtrim's 2, the output inflation behind its higher cost. leanctx (measured at 26%) and entroly (at 69%, its mildest) score significantly lower than llmtrim (n=20), and fall further at their headline reductions (vs-leanctx, vs-entroly).
Output
Output reduction by asking for terser responses, on a paid live call over 9 coding prompts:
The cost is the 949-token system prompt caveman resends on every request (right column); llmtrim's is 19 for nearly the same cut. Both still net-save here, so caveman's deeper cut comes out ahead only when the output it removes is worth more than the 949 tokens it adds back (vs-caveman artifact).
The tools stack: RTK shrinks CLI output, then llmtrim compresses the tool schemas on top. Full head-to-heads: crates/llmtrim-cli/bench/README.md.
Known limits
These are surfaced by the same A/B that proves the savings:
- Anthropic / Gemini token counts are approximate. There's no public exact tokenizer, so a BPE proxy is used and flagged in
status. OpenAI is exact. - Output savings aren't measured live. The proxy compresses input; an output saving needs the A/B counterfactual, which only the offline benchmark runs.
status"saved" is input-side. - The default is quality-gated, not lossless. Lossy stages run only where the eval shows quality holds. Want a byte-faithful round-trip? Use the
safepreset. - "Lossless" is input-side, not response restoration. A lossless stage preserves the information the model reads (a folded log run, a TOON-encoded array, an abbreviation legend the model decodes in-prompt), and the token gate reverts any input cut that doesn't pay off. The engine does not transform the model's response back to an original form.
Acknowledgments
Every compressor is a deterministic implementation of published research: the ideas are theirs, the engineering and the token gate are ours.
Papers + crates behind each stage
Retrieval & context: BM25 (Robertson & Zaragoza 2009, bm25); BM25+ (Lv & Zhai, CIKM 2011); RM3 (Lavrenko & Croft, SIGIR 2001); TextTiling (Hearst, CL 1997); TextRank (Mihalcea & Tarau, EMNLP 2004); MMR (Carbonell & Goldstein, SIGIR 1998); Submodular objective (Lin & Bilmes, ACL 2011); modified-greedy knapsack maximizer (Tang et al., SIGMETRICS 2021, arXiv:2008.05391); DPP diverse sampling (Chen et al., NeurIPS 2018); Lost in the Middle (arXiv:2307.03172); DSLR (arXiv:2407.03627).
Code: RepoCoder (arXiv:2303.12570); Hierarchical Context Pruning (arXiv:2406.18294); The Hidden Cost of Readability (arXiv:2508.13666); Minification token accounting (arXiv:2606.01326).
Tool output: Drain (He et al., ICWS 2017); Brain (Yu et al., IEEE TSC 2023); LogLSHD (arXiv:2504.02172).
Dedup & abbreviation: SimHash (Charikar, STOC 2002, gaoya); CompactPrompt (arXiv:2510.18043); Maximal repeats (arXiv:1304.0528) + Re-Pair (Larsson & Moffat, DCC 1999).
Output control: Chain-of-Draft (arXiv:2502.18600); TALE (arXiv:2412.18547).
Serialization: TOON (Token-Oriented Object Notation), Johann Schopplich.
Built on tiktoken-rs, tree-sitter, image, whatlang, hudsucker, rusqlite, and more.
Found a problem?
Each failing check names its fix. If a request was mangled, set LLMTRIM_CAPTURE_DIR and
open an issue with the before/after pair.
If llmtrim saved you money, a ⭐ helps others find it.
Star History
[Star History Chart]Licensed under MPL-2.0. Use llmtrim freely in your stack, including commercially, with no source-disclosure obligation for your own code; the file-level copyleft applies only to modifications you make to llmtrim's own source files. Contributions via DCO sign-off.
來源:README.md,提交 7dce1a4
工具
0版本歷史
1- v0.13.4最新Sep 16, 2026
評分
已滿足適用檢查項的 50%
該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。
- 近 30 天內可連通25 分
請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。
- 已宣告認證方式10 分
請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。
- 已列出工具15 分
請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。
- 描述必需15 分
- 圖示10 分
- 文件15 分
- 授權條款10 分