token-savior 标志

token-savior

社区热门
Mibayy

MCP server that gets Claude to 97.9% (188/192) on a real coding benchmark at -80% active tokens and -83% wall time, vs 78.3% plain. Structural code navigation + persistent memory engine. Works with every MCP client.

发布者Mibayy
代码仓库token-savior
语言Python
复刻数
101
星标数
1.2K
可用工具
0
传输类型stdio
分类
许可协议MIT
链接
  • 将工具接入 AI 工作流

    token-savior 提供 MCP 功能,可供兼容的 AI 客户端和智能体使用。

  • 0 个可用工具

    浏览下方可调用的操作;如果服务器提供了名称和描述,也会一并显示。

  • 可直接复制的配置

    使用安装配置片段,在您首选的 MCP 客户端中配置此服务器。

  • 开源社区热度

    关联的代码仓库有 1.2K 个星标和 101 个复刻。

Token Savior

One MCP server. One profile. 97.9% on tsbench at -80% tokens. Structural code navigation, persistent memory, and Bash command rewriting for AI coding agents.

PyPI Benchmark Python 3.11+ MCP CI

mibayy.github.io/token-savior -- project site + benchmark landing Benchmark source + fixtures: not currently published (see Reproducing the score below)


Benchmark -- 96 real coding tasks (Claude Opus 4.7, May 2026)

Plain Claude CodeWith Token Savior
Score141 / 180 (78.3%)188 / 192 (97.9%)
Active tokens / task17 2213 395 (-80%)
Wall time / task110.6 s18.9 s (-83%)

Reproduces with the optimized profile (single env var). The harness that produced these numbers is described below; its repository is not public at the moment, so take the figures as reported rather than as independently verifiable.

A re-measurement was published here on 2026-08-09 and has been withdrawn on 2026-08-10. It reported new-token savings from a small replacement harness. Those numbers did not measure this server at all: across 143 benchmark sessions, exactly one called a Token Savior tool. The client running the harness had MCP deferred-tool loading enabled, so all 18 tools sat behind a ToolSearch lookup instead of appearing in the model's manifest. The model never saw them and fell back to Grep and Read — 66 greps, 30 reads, one MCP call. What varied between the "profiles" was the size of the cached prefix, not what the agent did.

The lesson is worth more than the numbers were: a benchmark of an MCP server must assert that its tools were actually called. Ours did not, so it happily compared two identical agents. That assertion now exists in the harness.

The headline figures above therefore stand as reported and unverified, as stated in the previous paragraph. Re-measuring them properly is open work.


Who starred this repo?

starscope

On June 30, 2026 GitHub restricted stargazer and watcher lists to repo admins and collaborators, which broke every "who starred my repo" tool at once. I rebuilt one that still works, precisely because it only reads repos you own or can push to: starscope ranks the people who starred or forked your repo by influence, and surfaces their social accounts when their GitHub profile declares them.

Numbers on this very repo, computed with it: 1,147 people, 27% with a public social account, and the most followed carries 18,922 followers. The named list is visible to the repo owner and to nobody else — the public page shows aggregates only.


What's new

Release notes live where they can't drift out of sync with the code:


Quick start

bash
pip install "token-savior-recall[mcp]"

Add to your MCP config (e.g. Claude Code):

json
{
  "mcpServers": {
    "token-savior-recall": {
      "command": "/path/to/venv/bin/token-savior",
      "env": {
        "WORKSPACE_ROOTS": "/path/to/project1,/path/to/project2",
        "TOKEN_SAVIOR_CLIENT": "claude-code",
        "TOKEN_SAVIOR_PROFILE": "optimized"
      }
    }
  }
}

That's it. TOKEN_SAVIOR_PROFILE=optimized ships the Pareto-optimum config that wins tsbench. It bundles:

  • tiny_plus (15 hot tools manifest)
  • thin inputSchema (-44% manifest)
  • capture sandbox disabled
  • memory hooks gated for cross-project safety

No other tuning needed.


Activation (Bash compaction + rewriting)

Bash compaction and the PreToolUse rewriter are opt-in. Two env vars and one CLI call:

bash
export TS_BASH_COMPACT=1       # PostToolUse output compactors (34 of them)
export TS_BASH_REWRITE=1       # PreToolUse command rewriter (10 rules)

ts init --agent claude --yes   # auto-merge hooks into ~/.claude/settings.json

ts init is idempotent. It detects existing hook entries, dedups by (matcher, command), prints a unified diff, and backs up settings.json to .bak-YYYYMMDD-HHMMSS (UTC) before writing. Supported agents: claude, cursor, gemini, codex, openclaw. Pass --dry-run to preview, or --global to write the user-level config.

Optional audit log of every rewrite:

bash
export TS_BASH_REWRITE_LOG=$HOME/.local/state/token-savior/rewrites.jsonl

Compactor catalog (34)

FamilyCompactors
gitstatus, diff, log, push/pull, commit, add, fetch, checkout, branch, worktree list, stash list
ghrun list, run view, pr diff, pr view, issue view, repo view
test/lintpytest, jest, vitest, eslint, biome, cargo test, cargo build/clippy, tsc
cloudkubectl get, kubectl logs, aws sts, aws ec2, aws lambda, aws logs, aws iam, aws dynamodb, aws s3
dockerdocker ps, docker logs
packagingnpm/yarn/pnpm list, pip list/show
shell catch-allsgrep, find, cat, curl

Each compactor is a pure function (no I/O, no globals) returning a token-efficient rendering. The dispatcher returns None when no matcher fires, leaving the existing sandbox path untouched. Compound commands (cd ... && cmd) fall through to the last meaningful segment.

These run in PostToolUse, so they do not shrink the current turn. The hook fires after the tool has returned; it can add context, not remove it. The compact rendering is appended below the raw output, which stays. What you gain is persistence: the full output goes to the capture sandbox and outlives a context compaction. For an actual reduction of what reaches the model, use the PreToolUse rewriter (TS_BASH_REWRITE=1) — it edits the command before it runs.


ts_discover -- find missed TS opportunities

New MCP tool that scans your Claude Code transcripts for patterns where TS tools would have been cheaper than what the agent actually did.

python
ts_discover()                       # active project, last 30 days
ts_discover(project=None)           # ALL transcript projects
ts_discover(format="adoption")      # TS vs native ratio per session
ts_discover(format="adoption_json") # same, JSON

Findings: Read->Grep->Read chains, sequential find_symbol, edits without get_edit_context, memory_search without memory_index, native shell on code files. Args are pruned to load-bearing keys (PII-safe). Streams JSONL with mtime fast-skip.


ts init CLI

bash
ts init --agent claude [--global] [--dry-run] [--yes]
ts init --agent cursor
ts init --agent gemini
ts init --agent codex
ts init --agent openclaw

Detects the target agent's settings location, deep-merges the Token Savior hook config (PostToolUse + PreToolUse), preserves existing hooks, dedups, prints a unified diff. Backs up to settings.json.bak-YYYYMMDD-HHMMSS (UTC). Re-running is a no-op.


What it does

Claude Code reads whole files to answer questions about three lines, and forgets everything the moment a session ends. Token Savior fixes both, plus a third axis: it bounds the noisy Bash output that bloats turn budgets between code reads — by rewriting the command before it runs.

It indexes your codebase by symbol -- functions, classes, imports, call graph -- so the model navigates by pointer instead of by cat. Measured reduction: 97% fewer chars injected across 170+ real sessions.

On top of that sits a persistent memory engine. Every decision, bugfix, convention, guardrail and session rollup is stored in SQLite WAL + FTS5

  • vector embeddings, ranked by Bayesian validity and ROI, and re-injected as a compact delta at the start of the next session.

And on top of that, since v4.1, sit the Bash compactors and the PreToolUse rewriter. Bench numbers above.

Which of those two actually shrinks a turn, and which does not. Measured 2026-08-09, and worth stating plainly because the distinction is not obvious:

  • The PreToolUse rewriter changes the command before it runs, so a smaller output is produced and a smaller output reaches the model. This is a real reduction in the current turn.
  • The PostToolUse compactors run after the tool has returned. A PostToolUse hook can only add context; by the time it fires, the raw output has already been sent. The compact rendering is appended, it does not replace anything. What the compactors genuinely buy you is different and still valuable: the full output is preserved in the capture sandbox and survives a context compaction, so it can be queried later instead of being re-run.

If your goal is a smaller turn, TS_BASH_REWRITE=1 is the switch that does it. If your goal is to stop losing command output across compactions, that is TS_BASH_COMPACT=1.


Profile comparison

ProfileTools exposedManifest tokensWhen to use
optimized15~1.5 KTRecommended default -- Pareto win on tsbench
autoadaptive~1-2 KTPer-client telemetry-based (experimental)
tiny6~0.6 KTMinimal hot loop
lean51~4 KTLegacy -- broader surface
compact-only1~0.3 KTBash layer only (rewriter + capture) -- you already run symbol nav elsewhere
full68~6 KTEverything exposed

You probably want optimized.


How it composes with adjacent tools

Token Savior spans several layers, and most neighbouring tools occupy exactly one of them. Overlap is opt-out per layer, so running both is usually fine once you disable the half you already have. Thanks to @chirag127 for mapping this out in #45.

ToolLayerOverlapWhat to do
RTK (repo currently unreachable)PostToolUse Bash output compressionSame layer, same PostToolUse limit: neither shrinks the current turnPick one. TS_BASH_COMPACT=0 to defer to RTK
serenaSymbol-graph navigationDirect, with find_symbol / get_dependentsRun TS as compact-only if serena is your navigator
codebase-memoryPersistent code graphWith the memory engineTS_MEMORY_DISABLE=1
Ponytail, CavemanOutput-side compression (code and prose)Partial, output side onlyComplementary, no knob needed

The layers Token Savior owns that these do not: the PreToolUse Bash rewriter (it shrinks the command before it runs, not the output after), structural editing that keeps the index in sync, and the audit tools (detect_breaking_changes, find_dead_code, analyze_config).

If you only want the Bash layer, TOKEN_SAVIOR_PROFILE=compact-only advertises a single tool and leaves the compactors and rewriter running. Of those two, the rewriter is the one that reduces the current turn.


Token savings

OperationPlain ClaudeToken SaviorReduction
find_symbol("send_message")41M chars (full read)67 chars-99.9%
get_function_source("compile")grep + cat chain4.5K charsdirect
get_change_impact("LLMClient")impossible16K charsnew capability
96-task tsbench (Opus, plain vs ts)17 221 active/task3 395 active/task-80%
7-day Bash output bench (v4.3)~30 K tokens/week~9.6 K tokens/week~20.4 K/week

Install

pip (MCP server)

bash
pip install "token-savior-recall[mcp]"
# Optional hybrid vector search:
pip install "token-savior-recall[mcp,memory-vector]"

uvx (no venv, no clone)

bash
uvx token-savior-recall

Claude Code one-liner

bash
claude mcp add token-savior -- /path/to/venv/bin/token-savior

Development

bash
git clone https://github.com/Mibayy/token-savior
cd token-savior
python3 -m venv .venv
.venv/bin/pip install -e ".[mcp,dev]"
pytest tests/ -q

Suite size: 1898 passed, 2 skipped on main. CI green on Python 3.11 / 3.12 / 3.13.


Bench it yourself

The compactor numbers above come from replaying real Claude Code transcripts through the dispatcher. Two scripts live under scripts/:

bash
python3 scripts/bench_compactors_real.py       # match rate + mean savings
python3 scripts/bench_compactors_unmatched.py  # top unmatched commands

The first walks ~/.claude/projects/*/*.jsonl, replays every Bash output through the registry, and reports per-family savings + overall match rate. The second buckets the unmatched commands so the next compactor target is obvious from the histogram.

Reproducing the tsbench score

Honest status, checked 2026-08-09: the benchmark repository these instructions pointed at returns 404, and so did the BENCHMARK-SUMMARY link above. Rather than leave a recipe that cannot run, here is what the harness does, so the number can be judged on its method:

  • A generated toy repo (deterministic seed) with four planted traps: a symbol defined twice, a three-level call chain, an a -> b -> c -> a import cycle, and a dead function whose name contains a live one.
  • Eight read-only tasks, scored mechanically against an expected list and a forbidden list. The forbidden list is the half that matters: an answer can contain the right target and the wrong one, and a grader that only looks for the right one would score it correct.
  • A sans_ts control arm running plain Read/Grep/Glob, without which the bench compares Token Savior profiles to each other and can never conclude "useless" — and therefore never "useful" either.

One trap worth knowing about if you rebuild it: the harness spawns claude -p, which inherits ~/.claude/settings.json. If any Token Savior PreToolUse hook is enabled on the machine, it applies to the control arm too and rigs the comparison. Neutralise them in both arms (TS_GUARD_OFF=1 TS_READ_GUARD=0 TS_BASH_REWRITE=0).


Bonus: ts CLI for non-MCP agents

For agents without MCP (Cursor, Aider, Continue, scripts, CI), the ts command exposes a subset of the tools via shell:

bash
ts use /path/to/project
ts get my_function          # JSON output
ts search 'pattern'
ts daemon start             # ~145ms per call vs 1.5s cold fork
ts init --agent cursor      # wire up Bash hooks for non-Claude agents

On Claude Code, prefer the MCP server -- measured cheaper than CLI on Opus 4.7. The CLI is there for the portability case.


Environment variables

All optional. Values shown as =1 also accept nothing else — set exactly 1; values shown as bool accept 1/true/yes (and on where noted).

Server & tool manifest

VarDefaultPurpose
WORKSPACE_ROOTScurrent dirComma-separated project roots to index. Codex trap: Codex whitelist-filters the MCP server environment, so an exported shell variable never arrives — set it in config.toml under [mcp_servers.token-savior] env (or env_vars)
PROJECT_ROOT—Single-root alternative to WORKSPACE_ROOTS
CLAUDE_PROJECT_ROOT—Deliberate active-project override (Token Savior's own contract — no host sets it). Registered if valid, wins over every other boot signal
TS_STICKY_ACTIVEoff (bool, on ok)Freeze the active project: explicit project= hints and absolute path arguments still route each call, but no call repoints the shared default. For parallel agents in sibling worktrees
TOKEN_SAVIOR_PROFILEfullTool profile. optimized — the value the quickstart config and ts init recommend — ships the Pareto manifest, implies thin schemas, and omits the capture tools from the manifest
TS_THIN_SCHEMAS=1off (on in optimized)Strip verbose tool schemas from the manifest
TS_AUTO_HOT_K10Hot-tool count exposed by the telemetry-driven auto profile
TOKEN_SAVIOR_CHAIN_NUDGEon0/false/off disables chained-tool nudges
TS_MEMORY_DISABLE=1offDisable the memory engine (clean-context workloads)
TS_CAPTURE_DISABLED=1offSkip read-side capture sandboxing and drop the capture tools from the manifest (no profile flips this; optimized only hides the capture tools)
TS_CODE_MODE_DISABLE=1offDisable code-mode tools
TS_CODE_MODE_NODEnodeNode binary used by the code-mode sandbox
TS_RESOURCES_DISABLEDoff (bool)Don't expose observations as ts://obs/{id} MCP resources
TS_WARM_STARToff (bool)Pre-build project slots at startup
TOKEN_SAVIOR_NO_WARMUPoff (bool)Skip the ts_search embedding warm-up
TS_SEARCH_COLD_DELEGATEoff (bool, on ok)Delegate the cold ts_search call to a running ts daemon
TS_SOCK/tmp/ts.sockUnix socket of the ts daemon (CLI + cold delegate)
TOKEN_SAVIOR_CLIENTauto-detectedClient label (claude-code, …) for telemetry/client detection
TOKEN_SAVIOR_SESSION_LABEL—Free-form label attached to session telemetry

Indexing

VarDefaultPurpose
INCLUDE_PATTERNSbuilt-in listColon-separated globs; replaces the default include list
EXCLUDE_PATTERNSbuilt-in listColon-separated globs; replaces the default exclude list
EXCLUDE_EXTRA—Colon-separated globs appended to the default excludes
TOKEN_SAVIOR_EXCLUDE_PATTERNS—Colon-separated globs appended at the indexer level
TOKEN_SAVIOR_MAX_FILE_SIZE500000Max file size (bytes) to index
TOKEN_SAVIOR_MAX_FILES10000Max files per project
TOKEN_SAVIOR_WATCHERautoFile watcher: auto / on / off
TS_WATCHER_FORCE_POLLINGoffForce the polling watcher backend

Claude Code hooks

VarDefaultPurpose
TS_CAPTURE_THRESHOLD_BYTES4096Minimum tool-output size to sandbox
TS_CAPTURE_REPLACE=1offStrong-replace: tell the agent to ignore the inline output and capture_get the URI
TS_CAPTURE_TTL_DAYS30Captures older than this are purged on the next capture_put; 0 disables the GC
TS_BASH_COMPACT=1offPostToolUse compactors. Preserves output across compaction; does NOT shrink the current turn (see note above)
TS_COMPACT_INLINE_THRESHOLD4096Hybrid mode: compact-result size above which the full original is also sandboxed
TS_COMPACT_TINY_THRESHOLD256Hybrid mode: compact-result size below which the sandbox is always skipped
TS_BASH_REWRITE=1offEnable the PreToolUse Bash command rewriter
TS_BASH_REWRITE_LOG—JSONL audit log of every rewrite
TS_HOOK_MINIMAL=1offSessionStart memory hook emits only the Memory Index block

Memory extras

VarDefaultPurpose
TS_VIEWER_PORToffPort for the observation web viewer (unset = disabled)
TS_AUTO_EXTRACT=1 + TS_API_KEYoffLLM auto-extraction of memory observations (Anthropic API key required)
TS_MODELclaude-sonnet-4-6Auto-extraction model override
TOKEN_SAVIOR_MEMORY_AUTO_SAVE=1offAuto-save memory observations
TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID—Critical-observation feed

Storage, dashboard, debugging

VarDefaultPurpose
TOKEN_SAVIOR_STATS_DIR~/.local/share/token-saviorTelemetry + stats directory
TOKEN_SAVIOR_DASHBOARD_HOST127.0.0.1Dashboard bind host
TOKEN_SAVIOR_DASHBOARD_PORT8921Dashboard port
TOKEN_SAVIOR_INCLUDE_TMP_PROJECTSoff (bool)Dashboard also lists projects under temp dirs
TOKEN_SAVIOR_DEBUG=1offDebug logging
TOKEN_SAVIOR_TRACEoff (bool)MCP request lifecycle tracing

Not knobs: CLAUDECODE, CLAUDE_CODE_ENTRYPOINT, CLAUDE_PROJECT_DIR, CLAUDE_CONTEXT_REMAINING_PCT, CODEX_* and HERMES_* are read for host/client detection and boot-time project hints — the environment sets them, you don't. (CLAUDE_PROJECT_DIR is what Claude Code actually exports; it always names the main checkout, never the worktree the session works in, so the launch directory outranks it when that directory is a linked worktree. CLAUDE_PROJECT_ROOT moved up into the knobs table: nothing sets it but you.)

Naming trap: TS_PROFILE in the benchmark snippets is tsbench's variable; the server reads TOKEN_SAVIOR_PROFILE.


License

MIT

安装

TypingMind
前提条件:

Node.js 18+

{
  "mcpServers": {
    "mibayy-token-savior": {
      "command": "",
      "args": []
    }
  }
}

将 token-savior MCP 与多个 AI 模型配合使用

TypingMind 在工作区级别连接 MCP 工具,因此连接 token-savior 后,您就可以在 TypingMind 中搭配不同的 AI 模型使用,无需为每个模型单独设置。 此 MCP 通过您设备上的 TypingMind MCP 连接器在本地运行。

本地连接器设置指南

如果 MCP 服务器需要访问您电脑上的本地文件、应用或私有资源,请选择此方式。

1

打开 MCP 设置

在 TypingMind 中,依次前往“设置”、“高级设置”和“模型上下文协议”,然后选择“设置连接器”。

  1. 在您的浏览器中打开 TypingMind。
  2. 点击“设置”图标。
  3. 进入“高级设置”。
  4. 打开“模型上下文协议”部分。
  5. 点击“设置连接器”,然后选择“此设备”。
TypingMind MCP 连接器设置界面,已选择“此设备”
2

运行连接器命令

选择“此设备”,从 TypingMind 复制命令并在终端中运行。使用 MCP 时,请保持该进程运行。

  1. 复制 TypingMind 显示的设置命令。
  2. 在 macOS 上打开“终端”,或在 Windows 上打开 Windows Terminal。
  3. 粘贴并运行命令。
  4. 如果终端询问您是否继续,请确认安装软件包。
  5. 使用 MCP 工具时,请勿关闭终端窗口或停止其中的连接器进程。
3

将 token-savior 添加为服务器

当连接器状态为“就绪”时,点击“编辑服务器”,然后粘贴 MCP 服务器配置。

  1. 等待连接器状态显示为“就绪”。
  2. 点击“编辑服务器”。
  3. 粘贴 token-savior MCP 服务器配置。
  4. 保存服务器列表。
  5. 如需确认连接器是否仍处于就绪状态,请刷新。
TypingMind MCP 设置界面,显示正在运行的服务器和“编辑服务器”按钮
{
  "mcpServers": {
    "mibayy-token-savior": {
      "command": "npx",
      "args": [
        "-y",
        "token-savior-recall"
      ]
    }
  }
}
4

在不同模型中使用同一连接

保存服务器列表,打开“插件”,启用 token-savior MCP 工具,然后在 TypingMind 中选择任意受支持的 AI 模型,即可在聊天中使用这些工具,或将其分配给智能体。

  1. 在 TypingMind 中打开“插件”页面。
  2. 启用 token-savior MCP 工具。
  3. 开始聊天并选择您想使用的 AI 模型。
  4. 在聊天中使用 MCP 工具,或将其分配给 AI 智能体。
  5. 根据需要随时切换到其他 AI 模型,无需重新连接 MCP。
在 TypingMind 聊天中使用已启用的 MCP 工具和选定的 AI 模型
您能使用 token-savior 帮我完成这项任务吗?
token-savior
当然,我看过了。
以下是我使用 token-savior 得到的结果。

常见问题

token-savior MCP 服务器有什么用途?

token-savior 是一个 MCP 服务器,可让兼容的 AI 客户端连接外部工具并获取上下文。在 TypingMind 中,只需添加一次此 MCP 服务器,即可在您的 AI 工作区中使用其工具。

可以在 TypingMind 中让多个 AI 模型使用 token-savior MCP 吗?

可以。TypingMind 在工作区层面连接 MCP 工具,因此您无需为每个模型单独配置 MCP 服务器,就能在 Claude、ChatGPT、Gemini 或您在 TypingMind 中配置的其他 AI 模型中使用 token-savior。

为什么在 TypingMind 中使用 token-savior MCP?

TypingMind 将多个 AI 模型、提示词、插件、AI 智能体、API 密钥和 MCP 工具整合到同一个工作区中,是最出色的大语言模型聊天前端之一。连接 token-savior 后,您可以在偏好的不同模型中使用其 MCP 工具,同时在 TypingMind 中井然有序地管理聊天工作流程。

如何将 token-savior MCP 连接到 TypingMind?

token-savior 通过 TypingMind 本地 MCP 连接器运行。当 MCP 服务器需要访问您计算机上的本地文件、桌面应用、命令行工具或私有资源时,这种方式最合适。

token-savior MCP 在 TypingMind 中提供哪些工具?

token-savior 提供 MCP 功能,您可以在 TypingMind 的插件页面启用这些功能,然后在聊天中使用,或将其分配给 AI 智能体。

使用 token-savior MCP 需要向 TypingMind 提供我的 API 密钥吗?

不需要。TypingMind 采用本地优先的设计,让您自行选择模型提供商,并自行管理 API 密钥、提示词和 MCP 配置。如果 token-savior 需要身份验证,请在创建连接时,为该 MCP 服务器添加所需的请求头、OAuth 设置或本地配置。

相关 MCP 服务器

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇