tokencompress
A local, zero-cloud MCP server for token and text compression. It provides tools to compress, auto-compress, measure, and decompress text using offline rules, lossless gzip packing, or a local Ollama semantic model.
README
tokencompress
本地、零云依赖的 token / 文本压缩工具包。把冗长 prompt、日志、长文压短,省 token、省钱、不联网。
- 纯 Python,无强制依赖(可选
tiktoken做精确 GPT 计数) - 四种形态随便挑:MCP 服务 / HTTP API / CLI / 当库导入
- 离线规则压缩 + 可选本地 Ollama 语义压缩 + gzip 无损打包
- 智能自动压缩:短输入原样放行,代码块/URL/JSON 自动豁免,只压正文
English
tokencompress is a local, zero-cloud token & text compression toolkit for LLM prompts, context windows, and log/transport volume.
- 🔒 100% local — no API keys, no network calls. Rules & lossless run fully offline; semantic mode only talks to a local Ollama.
- 🧩 Four interfaces — MCP server, HTTP API, CLI, and importable Python library.
- 🌏 Bilingual — first-class Chinese + English filler/stop-word removal and phrase abbreviation.
- 🤖 Smart auto-compress — short inputs pass through untouched; code blocks, URLs, and JSON are auto-exempt; only prose gets compressed.
- 📦 Lossless mode — gzip + base64 packing for logs/transport, fully reversible.
Keywords: token compression, prompt compression, LLM context, local-first, privacy, MCP, CLI, Chinese NLP, text compression, Ollama.
安装
cd tokcompress
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
没有自带 venv。按上面“安装”步骤建
.venv即可;或pip install .后直接用系统python3。
最简单的用法
1) 当库导入(推荐给写代码的人)
from tokencompress import compress, auto_compress, measure
# 手动压
r = compress("你的长文本……", method="rules")
print(r["compressed"]) # 压缩后的文本
print(r["metrics"]["token_ratio"]) # 0.71 表示省了约 29% token
# 智能自动压:短的不动,长的才压
out = auto_compress("你的长文本……")["compressed"]
2) 命令行(CLI)
# 压一段文字
python -m tokencompress compress "你的长文本……"
# 从管道读(最常用)
cat long_prompt.txt | python -m tokencompress autocompress -
# 只算 token 数
python -m tokencompress measure "你的长文本……"
3) tca 包装脚本(一行管道,最简)
# 压缩剪贴板
pbpaste | ./bin/tca
# 压缩文件
cat long_prompt.txt | ./bin/tca
# 自定义触发阈值(token 数,低于此值原样放行)
echo "很长的文本……" | ./bin/tca --threshold 300
可选:把下面这行加进 ~/.zshrc,之后任意位置都能用 tca:
alias tca="$HOME/path/to/tokencompress/bin/tca" # 替换成你的实际路径
4) HTTP 服务(给别的程序调用)
python -m tokencompress serve --port 8787
curl -s -X POST localhost:8787/compress \
-H 'Content-Type: application/json' \
-d '{"text":"你的长文本……","method":"rules"}'
端点:/health /strategies /backends /measure /compress /decompress /autocompress
5) 接入 WorkBuddy(MCP)
把 examples/mcp_config.json 的内容加进 ~/.workbuddy/mcp.json 的 mcpServers,
重启 WorkBuddy 后,对话里就能直接让模型调用 compress_text / auto_compress_text 等工具。
压缩方法
| method | 说明 | 是否可逆 | 依赖 |
|---|---|---|---|
rules |
离线规则流水线:去空白/去重/去填充词/短语缩写 | 否(有损但语义保留) | 无 |
semantic |
本地 Ollama 模型做语义压缩 | 否 | 本机 Ollama |
both |
先 rules 再语义 | 否 | 本机 Ollama(无则回退 rules) |
lossless |
gzip + base64 打包,用于日志/传输 | 是 | 无 |
rules 流水线顺序:whitespace → dedup → filler → abbreviate → truncate
可用 compress(text, strategies_list=[...]) 指定只跑其中几步。
真实压缩率(本机实测)
案例 1:中英混合 prompt(method=rules)
输入:“我们需要因为时间成本的原因去写一个用于短视频生成的提示词,for example 我们可以这样描述:given a topic,in order to 让模型生成一段画面。actually 要注意避免图像畸变这个问题,basically 这个细节很重要,also 要让画面保持稳定。”
| 指标 | 压缩前 | 压缩后 | 比率 |
|---|---|---|---|
| tokens(离线估算) | 128 | 92 | 0.719 |
| bytes | 301 | 261 | 0.867 |
命中的规则:filler(去掉 actually/basically/also)、abbreviate(for example→e.g.、in order to→to)
输出:“我们需要因为时间成本的原因去写一个用于短视频生成的提示词,e.g. 我们可以这样描述:given a topic,to 让模型生成一段画面。 要注意避免图像畸变这个问题, 这个细节很重要, 要让画面保持稳定”
案例 2:重复日志(method=lossless)
输入:50 行相同的
INFO ... worker-7 processed batch id=8821 items=64 ok
| 指标 | 压缩前 | 压缩后 | 比率 |
|---|---|---|---|
| bytes | 3050 | 144 | 0.047 |
可逆:解压后与原文逐字节一致 ✓(适合日志归档/网络传输)
案例 3:智能自动压缩(auto_compress)
- 短输入(≤ 500 token,可配
--threshold):原样放行,绝不误伤指令 - 长输入(上面案例 1 重复 6 遍):自动压缩,
token_ratio ≈ 0.717 - 代码块(
```)、URL、文件路径、JSON 行:永远不压
常见问题
token 数是怎么算的? 离线估算:CJK ≈ 1 token/字符,拉丁文 ≈ 1 token/4 字符。
装了 tiktoken 后 measure(text, model="gpt-4o") 可拿到精确 GPT 计数。
会把我数据发到云端吗? 不会。rules / lossless 完全本地。semantic 只连本机
http://localhost:11434(Ollama),不联网、不经过任何第三方。
装了 Ollama 怎么启用语义压缩? 拉一个小模型(如 qwen2.5:3b),list_backends()
会显示 ollama: available。之后 compress(text, method="semantic") 即可。
文件结构
tokcompress/
├── tokencompress/ # 包本体
│ ├── __init__.py # 导出 compress / measure / decompress / auto_compress ...
│ ├── core.py # 统一入口
│ ├── strategies.py # 规则流水线 + 无损打包 + 语义压缩
│ ├── tokenizer.py # token 估算 / 后端探测
│ ├── cli.py # 命令行
│ ├── http_server.py # HTTP API
│ └── mcp_server.py # MCP 服务
├── bin/tca # 一键自动压缩包装脚本
├── examples/ # mcp_config.json / usage.md
└── requirements.txt
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.