tbguard
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@tbguard pack src/ and docs/ into a 4k-token context and report the savings"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
tbguard
A context and token budget guard for coding agents. It runs as a CLI or as an MCP server over stdio. Before files reach the model, it:
drops noise: lockfiles, build output,
node_modules, logs, minified bundles, binaries, generated files, and anything over 1 MB;cleans what's left: removes trailing whitespace, collapses runs of blank lines, and folds repeated lines;
enforces a hard cap: 4k / 8k / 16k tokens, or any integer. The packed output is never larger than the budget;
logs the savings: every call appends raw vs. final token counts to a JSONL ledger.
It has zero runtime dependencies (Python 3.10+, standard library only). tiktoken is used if it is installed.
Quick start
pip install -e . # or just run: python -m tbguard ...
tbguard pack src/ docs/ -b small --report > context.txt
tbguard statsAs an MCP server (Claude Code, Claude Desktop, or any MCP client):
{
"mcpServers": {
"tbguard": { "command": "python", "args": ["-m", "tbguard", "serve"] }
}
}Tools exposed:
tool | args | returns |
|
| savings summary line + packed context |
|
| token count, keep/drop and the reason |
| none | cumulative totals from the ledger |
Related MCP server: genpark-agent-context-dynamic-compressor-skill
Benchmarks
These are real runs on this machine (Windows 11, Python 3.14, heuristic tokenizer). Times are wall clock and include interpreter start-up.
input | raw tokens | packed | saved | time |
| 80,358 | 1,299 | 98.4% | 0.23 s |
a 740k-token mixed folder (3D assets, scripts, this repo) at | 740,214 | 15,969 | 97.8% | 1.1 s |
The first row is mostly filtering. The second row is mostly the budget doing its job. Run python examples/make_sample.py to regenerate the sample.
Architecture
paths ──► collect_files ──► classify_path ──► classify_content ──► strip_noise_lines
(prunes noise (dir names, (NUL bytes, (whitespace,
dirs, >1 MB) globs) @generated, minified) repeats)
│
▼
pack (smallest-first fair share)
│
truncate_to (keep head ⅔ + tail ⅓)
│
packed text + GuardReport ──► ledger.jsonlFair-share packing. Files are packed smallest first. Each one gets
remaining / files_lefttokens, so a single 50k-token file can't take the whole budget from ten small ones. The output keeps your original order.Head and tail truncation. When a file must be cut, imports, signatures and the end of the file survive, and the middle is replaced with
... [N lines omitted by tbguard] .... The cut point is found by binary search over per-line token prefix sums (O(n log n)), followed by an exact recount.Hard guarantee.
count_tokens(packed) <= budget, and the tests check this at five budget sizes.MCP without an SDK. The server is about 150 lines of newline-delimited JSON-RPC 2.0 (
initialize,ping,tools/list,tools/call). Tool failures come back in-band asisError: true, and bad arguments return-32602, as the spec requires.
Trade-offs and limits
Token counts are estimates unless
tiktokenis installed. The heuristic averages a characters/4 estimate with a per-word estimate. It is close for code and prose, but it is not exact for any particular model. Usepip install .[exact]to get cl100k counts. Different models tokenize differently, so leave some headroom.Priority is input order, not relevance. There is no embedding or ranking step, by design: it would add dependencies and latency. Put the most important paths first.
Truncation works on lines, not syntax. It can cut through the middle of a function body. Parsing with an AST would fix that, but only for one language at a time.
Filtering is opinionated. For example,
bin/,vendor/and*.jsonlare dropped. Override with--ignore(to add globs), or editNOISE_DIRS/NOISE_GLOBS.The ledger is local only. It lives at
.tbguard/ledger.jsonl(override withTBGUARD_LEDGER). Nothing is sent anywhere.
Tests
python -m unittest discover -s tests -t .23 tests cover filters, the token estimator, the budget guarantee, truncation, starvation, the ledger, MCP protocol handling and the stdio loop.
License
MIT
Available Tools
3 toolsguard_contextB
Read files/dirs, drop noise (lockfiles, build output, logs, minified/binary), and pack them under a strict token budget.
Inputs: paths (required), budget, ignore.
inspect_fileC
Token count for a file and whether the guard would drop it.
Inputs: path (required).
savings_summaryB
Total tokens saved across all logged calls.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 3 tools
Each tool has a clear role: guard_context packs files under a budget, inspect_file previews a single file's token count and drop decision, and savings_summary reports aggregate savings. inspect_file overlaps slightly with guard_context since it previews the guard's behavior, but the descriptions make the boundary clear enough.
All names use snake_case and are readable. Two follow a verb_noun pattern (guard_context, inspect_file) while savings_summary is noun_noun, a minor deviation but not confusing.
Three tools is well-scoped for a narrow token-budget/context-packing utility: inspect, pack, and report savings. No tool feels redundant or missing from the count perspective.
The core workflow is covered: inspect a file, pack a context under budget, and view cumulative savings. Minor gaps exist—no way to configure the token budget or drop patterns, and no per-call savings detail or reset—but agents can work around these.
Maintenance
Related MCP Connectors
Turn a GitHub repo or docs site into agent-ready context: pack it or search it, over MCP.
Compress coding-agent context ~64%. Hosted Neural Keep MCP for Cursor/Claude/Codex.
LLM cost optimization gateway, repo token-waste auditor & model arbitrage MCP server.
A paid remote MCP for OpenAI Codex context compressor, built to return verdicts, receipts, usage log
Related MCP Servers
- FlicenseNot gradedqualityBmaintenanceEnables 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-
- FlicenseNot gradedqualityNot gradedmaintenanceEnables 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.-
- AlicenseNot gradedqualityBmaintenanceEnables 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.1MIT
- AlicenseNot gradedqualityBmaintenanceEnables local LLM tools and agentic IDEs to inspect repository token maps, retrieve clean token-bounded codebase snapshots, and audit code for hardcoded secrets via MCP over stdio.4MIT