Sophon

io.github.lacausecrypto由 GitHub 帳號 lacausecrypto 發布v0.5.4更新於 Oct 24, 2026

Honest token economics for MCP agents. 68% tokens saved, zero-ML Rust binary.

發布方自己的服務:Sophon Consulting

概覽

AI 產生的概覽

一個在本機執行的 Rust MCP 伺服器,以確定性方式壓縮提示詞、對話歷史、檔案讀取與指令輸出,為編碼代理降低 token 用量。

可以做什麼
Sophon 透過 stdio 提供 11 個 MCP 工具,用來壓縮代理傳送給模型的文字。compress_prompt 只保留長提示詞中與查詢相關的段落,compress_history 產生摘要、事實與近期視窗,compress_output 以 21 個領域篩選器清除指令 stdout/stderr 的雜訊。其他工具負責檔案讀寫差異、重複樣板片段編碼、token 計數、工作階段節省統計,以及依查詢排序的程式碼庫摘要。查詢時不需要嵌入模型或 API 金鑰,以單一本機二進位檔執行。
適用情境
適合編碼代理工作流程中,重複讀取檔案、冗長指令輸出與不斷成長的對話歷史占主要 token 開銷的情境,尤其是搭配 Claude Code、Cursor 或 Cline 使用時。它疊加在供應商提示快取或記憶系統之前,而非取代它們。不適用於高召回率的對話記憶、大型文件的多跳推理、OCR 或 PDF 版面處理,以及非常小的輸入。
執行需求
以本機程序透過 stdio 啟動,可透過 npm 套件 mcp-sophon 安裝(postinstall 會下載適用於 macOS arm64/x64、Linux arm64/x64 或 Windows x64 的預先建置二進位檔),也可用 Rust 1.75+ 從原始碼建置。選用功能需要額外的建置參數。選用環境變數包括 SOPHON_MEMORY_PATH、SOPHON_RETRIEVER_PATH、SOPHON_HYBRID、SOPHON_ROLLING_SUMMARY、SOPHON_CHUNK_TARGET、SOPHON_EMBEDDER 與 SOPHON_LLM_CMD。未宣告驗證機制。
安裝前請注意
npm 的 postinstall 指令碼會從 GitHub Releases 下載預先建置的二進位檔,因此安裝過程會取得並執行第三方程式碼。SOPHON_MEMORY_PATH 與 SOPHON_RETRIEVER_PATH 等選用設定會把對話記憶與檢索區塊寫入磁碟。SOPHON_LLM_CMD 會呼叫外部 LLM 指令,可能產生供應商費用並將內容傳送給該供應商。hook 安裝器會修改代理的設定檔。所回報的節省數據來自專案自身的量測,其中也包含壓縮反而增加 token 的已記錄情況。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Sophon,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

Sophon

Deterministic context compression for MCP agents. One Rust binary. Zero ML at query time. Reproducible benchmarks, real-data measurements.

[npm version] [npm total downloads] [GitHub release] [CI] [License: MIT] [Rust 1.75+] [MCP] [Tests]

Sophon is a deterministic context layer for agents speaking the Model Context Protocol. It compresses prompts, conversation memory, code digests, file deltas, and shell output — without an embedding model at query time, without a GPU, and without API keys.

Single 5.2 MB Rust binary. MCP-native. cl100k_base-accurate. Default build pulls no Python, no ML weights, no network.


What it does, in 30 seconds

ToolWhat it solves
compress_promptLong structured prompt → keep only sections relevant to the query
compress_historyGrowing conversation → summary + facts + recent window + optional retrieval
compress_outputShell stdout/stderr → 21 domain-aware filters (git, cargo, docker, kubectl, JSON, …)
read_file_delta / write_file_deltaRe-reads + edits → diffs only, never the whole file
encode_fragmentsRepeated boilerplate → single token reference
update_memoryAppend turn → JSONL persist + incremental rolling summary
navigate_codebaseRepo digest with tree-sitter / regex + PageRank, ranked by query

11 MCP tools total (full table below).


Real numbers — measured on this repo's own dev cycle

We built four independent benches that each capture a different chunk of an agent's tool traffic. All four run against this repo's actual git history + working tree on the operator's machine. Reproducible byte-for-byte by anyone with cargo build --release.

DimensionWhat it measuresSavedBench
historycompress_history over real commits94.6 %real_session_capture.py
shellcompress_output on real git/cargo/gh/ls stdout84.4 %real_session_shell.py
filereadscompress_prompt on real Rust / Python / Markdown / TOML files71.7 %real_session_filereads.py
searchcompress_output on real grep/find patterns79.5 %real_session_search.py
🎯 Weighted blend (35/30/20/15)typical agent session estimate84.7 %real_session_holistic.py

real_session_holistic.py runs all four sub-benches with --json, parses them, and produces the weighted blend. Default weights reflect this repo's observed shape; pass --weights "history=0.4,..." to model your own workload.

USD economy on Claude Opus 4.7

Saved per session
Naive input pricing ($15/MT)$2.03
With prompt caching (25-turn reads at $1.50/MT)$3.24

Pass --model sonnet or --model haiku to real_session_deep_dive.py if you're re-pricing for a cheaper tier.

Where each dimension falls short (we say it ourselves)

  • history measures only what git captures (commits + diffs) — typically ~5-10 % of a real session's tool traffic. The 94.6 % is the upper bound, not the typical case.
  • shell mixes commands that compress well (git diff 95 %) with commands that don't (gh repo view --json adds tokens, −9 %). 84.4 % is a real-world average, not a curated highlight.
  • filereads uncovered that compress_prompt on raw source files compresses by budget cap, not by query routing — same file with 3 different queries → identical output. Section detection only fires on structured input (Markdown headers, XML tags). Documented inline in the bench.
  • search depends entirely on YOUR repo's state. A repo with no TODOs gets 0 % on grep TODO.

The blended 84.7 % is napkin-math from a linear weighted average across four real measurements. Not a cherry-picked synthetic. Run the benches yourself to verify.

Other reproducible benchmarks (synthetic, on-thesis)

TestResultBench
compress_output across 18 command families90.1 % weighted aggregatecompress_output_per_command.py
25-turn synthetic Claude Code session68.1 % session tokens savedsession_token_economics.py
compress_prompt across 22 prompt shapes70.2 % mean, 36 ms mean latencyprompt_compression_extended.py
Code retrieval on "where is X?" questionsrecall@3 = 70 % (vs grep 10 %, FULL 20 %)repo_qa.py
vs LLMLingua-2 on structured prompts+8.9 pt accuracy at 35× lower latencyllmlingua_compare.py
Sophon + Anthropic prompt caching+24 % tokens / +49 % $ on top of cachingsophon_plus_prompt_caching.py
Sophon + mem0Additional savings on retrieved memoriessophon_plus_mem0.py

Why Sophon — "in front of X"

Sophon is not a memory platform, a recall system, an OCR stack, or a replacement for provider-side caching. It's a deterministic compressor that slots in front of whatever memory / cache / code-nav layer you already use, and attacks the tokens those layers can't.

In front of Anthropic / OpenAI prompt caching

Provider caching handles the static half of a request — system prompt, tool definitions, reused documents. It doesn't touch the dynamic half (growing conversation history, tool outputs). Sophon compresses exactly that half. The two stack cleanly.

+24 % tokens / +49 % $ saved on top of prompt caching on a 25-turn Claude session — because the uncached dynamic block is billed at 10× the cached rate. See sophon_plus_prompt_caching.py.

In front of mem0 / Letta / Zep / Graphiti

Memory systems retrieve the right memories. Sophon shrinks what gets sent to the LLM after retrieval. If mem0 returns 2 kB of raw memories, compress_prompt keeps only the sections the query actually references.

Honest caveat: on very short retrieved blocks (< ~200 tokens) Sophon's wrapper adds overhead and you should pass through. The bench reports this directly.

In front of Claude Code / Cursor / Cline

Primary use case. Every repeat file read becomes a read_file_delta; every shell command output goes through compress_output; every repeated boilerplate block gets a fragment_cache token. Install transparently with sophon hook install --agent claude --global.

In front of a RAG pipeline

navigate_codebase produces a PageRanked repo digest that a RAG retriever would otherwise spend expensive embedding calls to build. Tree-sitter / regex symbol extraction over 11 languages, sub-second.

When NOT to use Sophon

  • Long-form conversational recall above 80 % — Sophon caps at ~40 % on LOCOMO and we don't chase it. Run mem0 / Letta / Zep for recall, then optionally pipe their output through Sophon.
  • Multi-hop reasoning on massive documents — that's HippoRAG or GraphRAG.
  • OCR / PDF layout — out of scope. Use Docling / Marker / Unstructured upstream.
  • Very small inputs (< ~200 tokens) — Sophon's section scaffolding can cost more than it saves.

Quick start

Install via npm (recommended)

bash
npm install -g mcp-sophonsophon doctor          # verify install + show config

The postinstall script downloads the right prebuilt binary for your platform from the GitHub Releases page. Supported: macOS arm64/x64, Linux arm64/x64, Windows x64.

Build from source

bash
git clone https://github.com/lacausecrypto/mcp-sophoncd mcp-sophon/sophoncargo build --release -p mcp-integration       # ~5.2 MB binary

Optional features:

bash
# 11-language tree-sitter AST extraction (~25 MB):cargo build --release -p mcp-integration --features codebase-navigator/tree-sitter
# BGE-small semantic embedder (~34 MB), activate with SOPHON_EMBEDDER=bge:cargo build --release -p mcp-integration --features bge
# All features (~42 MB):cargo build --release -p mcp-integration --features "codebase-navigator/tree-sitter,bge"

Requires Rust 1.75+.

Wire it into an MCP client

Most clients accept this snippet (Claude Desktop, Claude Code, Cursor, Cline, Continue):

json
{  "mcpServers": {    "sophon": {      "command": "sophon",      "args": ["serve"]    }  }}

Run sophon doctor to print the right config path for your client.

Recommended runtime setup

bash
# Persistent memory + on-disk retriever store + BM25+Hash hybridexport SOPHON_MEMORY_PATH=~/.sophon/memory.jsonlexport SOPHON_RETRIEVER_PATH=~/.sophon/retrieverexport SOPHON_HYBRID=1
sophon serve

Quick CLI

bash
sophon exec -- cargo test                       # run + compress combined outputsophon compress-prompt --prompt ./system.txt --query "rust errors" --max-tokens 500sophon hook install --agent claude --global     # transparent Claude Code integrationsophon stats --period session                   # token savings rollup

Programmatic (one-shot JSON-RPC)

bash
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"compress_prompt","arguments":{"prompt":"<rust>?: operator</rust><web>fetch()</web>","query":"rust errors","max_tokens":500}}}' \  | sophon serve

What the binary ships

11 MCP tools, all stdio:

ToolWhat it does
compress_promptKeep query-relevant sections of a long prompt
compress_historySummary + facts + recent + optional retrieval over the conversation
compress_outputStrip noise from command stdout/stderr (21 domain filters + JsonStructural)
navigate_codebasetree-sitter / regex digest of a repo, PageRanked by query
update_memoryAppend messages, JSONL persist, optional rolling summary
read_file_deltaVersion/hash-aware file read, unchanged → minimal payload
write_file_deltaSend edits as diffs, not full files
encode_fragments / decode_fragmentsDetect repeated boilerplate, swap with tokens
count_tokenscl100k_base-accurate token count
get_token_statsSession-level savings rollup

Binary sizes by feature set:

BuildSize
Default (regex extractors, HashEmbedder)5.2 MB
+ tree-sitter (11 languages)~25 MB
+ BGE semantic embedder~34 MB
All features~42 MB

MCP protocol: 2025-06-18. notifications/cancelled actually drops the response (since v0.5.4). Structured JSON-RPC error codes (-32000..-32099 reserved for Sophon). Infallible dispatcher — a malformed request can't kill the stdio loop.


Filesystem confinement (opt-in)

For clients running untrusted prompts, set SOPHON_ALLOWED_ROOT to an existing workspace directory. read_file_delta, write_file_delta, and navigate_codebase reject resolved paths outside this directory. By default, trusted local integrations retain unrestricted filesystem access. This is a path-level defense, not a hardened OS sandbox: although known symlinks and dangling symlinks are checked, a concurrent actor who can modify directory links may swap a path between authorization and the subsequent file operation (TOCTOU). Do not expose these tools to hostile users with write access to the same filesystem; use operating-system isolation for strict security boundaries. New files require an existing parent directory when confinement is enabled.

Configuration

Run sophon doctor to see every SOPHON_* env var currently set with validation warnings. Full catalogue (24 flags) lives in runtime_flags.rs. The flags worth knowing:

FlagEffectCost
SOPHON_RETRIEVER_PATH=/dirActivate the semantic retriever (chunk store on disk)~0
SOPHON_MEMORY_PATH=/file.jsonlPersistent conversation memory across sophon serve runs~0
SOPHON_HYBRID=1BM25 sparse-lexical + HashEmbedder fused via RRF~1 ms
SOPHON_ROLLING_SUMMARY=1Build rolling summary at update_memory time, not at query timeLLM call moved to ingest
SOPHON_CHUNK_TARGET=500Bigger chunks preserve cross-sentence context~0
SOPHON_EMBEDDER=bgeSwap HashEmbedder for BGE-small (needs --features bge)model load at startup
SOPHON_LLM_CMD="claude -p --model haiku"LLM shell-out command (used by summarizer when configured)per-call subprocess

Deprecated v0.4.0 recall-chasing flags — SOPHON_HYDE, SOPHON_FACT_CARDS, SOPHON_ENTITY_GRAPH, SOPHON_ADAPTIVE, SOPHON_LLM_RERANK, SOPHON_TAIL_SUMMARY, SOPHON_REACT, SOPHON_GRAPH_MEMORY, SOPHON_MULTIHOP_LLM — chase LOCOMO recall, an axis we no longer optimise. Still functional but sophon doctor flags them. Removed in a future major.


Honest limitations

The full list lives in BENCHMARK.md § 8. Headlines:

  • LOCOMO conversational recall caps at ~40 %. mem0 / HippoRAG hit 80-90 % with neural retrieval at query time — we chose determinism + sub-100 ms p99 instead. Pipe mem0 in front of Sophon if you need that recall.
  • HashEmbedder is keyword-bound. "favorite food" ↔ "weakness for ginger snaps" doesn't match. Activate BGE (SOPHON_EMBEDDER=bge) for semantic recall — costs +25 MB binary + model load.
  • No multimodal ingestion. Images / PDFs / audio out of scope. Run Docling / Marker / Unstructured upstream.
  • Rolling summary doesn't help on small sessions. When the un-summarised tail fits the budget, the rolling cache is a no-op. Useful for long-running sessions with SOPHON_LLM_CMD set.
  • Some commands don't compress. gh repo view --json adds tokens, git log --oneline saves 0.4 %. Sophon's job isn't to compress already-compact output — it's to compress redundant verbose output. The benches name the gaps explicitly.

Project layout

.├── README.md           ← you are here├── BENCHMARK.md        ← full per-section benchmark detail├── CHANGELOG.md        ← version history + deprecated numbers├── benchmarks/         ← reproducible scripts for every number above├── npm/                ← npm wrapper package└── sophon/crates/      ← 11-crate Rust workspace    ├── prompt-compressor/    compress_prompt    ├── memory-manager/       compress_history, update_memory, rolling summary    ├── delta-streamer/       read/write_file_delta    ├── fragment-cache/       encode/decode_fragments    ├── semantic-retriever/   chunker + HashEmbedder + BM25 + entity graph    ├── output-compressor/    21 command-aware filters + JsonStructural    ├── codebase-navigator/   tree-sitter / regex + PageRank    ├── cli-hooks/            transparent agent installer    └── mcp-integration/      stdio server, async dispatch, cancellation

Contributing

PRs welcome. Run the test suite:

bash
cd sophon && cargo test --workspace --lib --tests --exclude prompt-compressor   # 405 testscd sophon && cargo test --features codebase-navigator/tree-sitter               # +AST testscd sophon-py && .venv/bin/pytest tests/                                         # 4 Python tests

Every benchmark claim is reproducible — pointers to the scripts live in BENCHMARK.md. If a number doesn't reproduce on your machine, open an issue.

Particularly welcome:

  • TypeScript bindings (Python bindings ship in sophon-py/)
  • gh family filter (gh run list, gh pr list, gh repo view --json) — the bench shows this is currently a gap
  • SOPHON_EMBEDDER_CMD shell-out plugin pattern (mirror of SOPHON_LLM_CMD) for Voyage / OpenAI / Cohere
  • Multi-repo real_session_holistic.py runs against popular open-source repos

License

MIT. See LICENSE.

來源:README.md,提交 e4bc0b4

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v0.5.4最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分

其他 Sophon 整合