context-engine
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
Context Engine · 上下文引擎
记忆、技能、会话记录、项目文档——都是文本,都是喂给模型的上下文。 既然底质相同,就不该维护三套检索、三套拼接、三套预算。
Context Engine 把这些东西统一成一种中间表示(ContextChunk),由一个装配器负责排序、去重和 token 预算,再用不同接口暴露给不同使用者:
Python API:嵌进自己的 Agent / 服务
CLI(
ctxe):人直接查和装配HTTP/JSON:跨语言、跨进程
MCP(stdio):让任意 MCP Host 的 Agent 直接调用
它还提供一个蒸馏接口:把上下文包导出成 SFT 数据,训练一个「上下文小模型」,在推理侧用同一个 compress(text, max_tokens) 契约做压缩。
为什么是「一个引擎」
资产 | 形态 | 生命周期 | 过去 | 现在 |
长期记忆 | Markdown | 人工维护、长期 | 单独读取 |
|
技能 | Markdown + frontmatter | 按需加载 | 单独索引 |
|
会话记录 | JSONL | 追加、会过期 | 单独截断 |
|
项目文档 | Markdown | 随仓库演进 | 塞进提示词 |
|
它们的差别是生命周期和治理策略,不是存储架构。把这些差别编码成 kind / scope / priority / provenance 元数据,就能共用一件事:
同一套相关性排序(BM25-lite,CJK 感知)
同一套去重(近重复只保留得分最高的一份)
同一个硬预算装配器(
used_tokens <= budget_tokens)同一条蒸馏流水线
分开做,就会得到三份互相不知道对方存在的上下文,重复、超预算、无法整体压缩。
Related MCP server: core-context
架构
flowchart LR
subgraph Sources
M[memory<br/>MEMORY.md / USER.md / daily]
S[skills<br/>SKILL.md trees]
T[session<br/>JSONL transcripts]
D[files<br/>docs / instructions]
end
M --> A[adapters]
S --> A
T --> A
D --> A
A --> C[ContextChunk<br/>kind · scope · priority · provenance]
C --> R[rank<br/>relevance + kind + recency + priority]
R --> U[dedupe]
U --> B[assemble<br/>token budget]
B --> P[ContextPack<br/>render / messages / json]
P --> I1[Python API]
P --> I2[CLI]
P --> I3[HTTP]
P --> I4[MCP]
P --> K[distill<br/>SFT jsonl]
K --> L[LoRA small model]
L --> X[compress interface]快速开始
git clone https://github.com/jokemanfire/context-engine
cd context-engine
python -m pip install -e .
# 直接跑内置 demo(4 类来源、13 个块)
ctxe -c examples/context-engine.toml stats
ctxe -c examples/context-engine.toml search "上下文引擎如何控制预算"
ctxe -c examples/context-engine.toml pack "上下文小模型怎么蒸馏" --budget 600接入自己的 OpenClaw 风格工作区:
ctxe init --preset openclaw --home ~/.openclaw/workspace
ctxe pack "上次关于磁盘布局的决策" --budget 1500四个接口,一个实现
Python
from context_engine import ContextEngine, load_config
engine = ContextEngine.from_config(load_config("context-engine.toml"))
engine.index()
bundle = engine.assemble("部署失败怎么排查", budget_tokens=1200)
print(bundle.render()) # 带 provenance 的上下文包
messages = bundle.to_messages() # 直接喂给模型CLI
ctxe search "预算" -k 5 --kind skill
ctxe pack "预算" --budget 800 --json
ctxe compress --query "预算" --max-tokens 300 --metricsHTTP
ctxe serve --port 8787
curl -s localhost:8787/v1/assemble -H 'content-type: application/json' \
-d '{"query":"预算如何控制","budget":600}' | jq -r .text/v1/search、/v1/assemble、/v1/compress、/v1/distill/dataset、/v1/stats、/v1/reindex。
MCP
{
"mcpServers": {
"context-engine": {
"command": "ctxe",
"args": ["mcp", "-c", "/path/to/context-engine.toml"]
}
}
}暴露的工具:context_search、context_assemble、context_compress、context_stats。
蒸馏成上下文小模型
接口是三层,缺一不可:
# 1. 导出「完整包 -> 压缩包」SFT 数据(teacher 可换成任意 LLM)
ctxe distill --queries-file examples/queries.txt --out data/ctx-sft.jsonl
# 2. 先用 dry-run 看训练计划(不需要 GPU / 依赖)
ctxe train --dataset data/ctx-sft.jsonl --dry-run
# 真正训练(需要 pip install -e '.[train]')
ctxe train --dataset data/ctx-sft.jsonl --model Qwen/Qwen2.5-0.5B-Instruct \
--out checkpoints/ctx-distiller --cpu
# 3. 推理侧用同一个契约替换 teacher
ctxe compress --query "预算" --max-tokens 300 --model checkpoints/ctx-distiller数据格式就是标准 chat SFT:
{"messages":[
{"role":"system","content":"You are a context distiller..."},
{"role":"user","content":"Budget: 320 tokens.\n\n<context-pack>..."},
{"role":"assistant","content":"<compressed pack>"}
],"meta":{"query":"...","teacher":"heuristic-extractive","source_tokens":1184,"target_tokens":302}}压缩契约只有一个方法:
class StudentContextModel(Protocol):
def compress(self, text: str, max_tokens: int) -> str: ...HeuristicStudent 是无依赖基线(也是默认 teacher),TransformersStudent 加载蒸馏后的 checkpoint。仓库没有声称已经训练出可用的生产小模型——训练脚本、数据管线、评测口径是完整的,权重需要你自己跑。
设计不变量
可溯源:每个块都能回答「从哪个文件、哪一节来」。
预算硬约束:装配结果
used_tokens <= budget_tokens;装不下的块记录reason=budget,不静默丢弃。接口零业务逻辑:CLI / HTTP / MCP 只做参数转换,行为差异必须回到引擎配置里。
差异即策略:新增一种上下文,先想清楚它的
kind / scope / priority / 生命周期,而不是新建一套系统。
目录
src/context_engine/
ir.py # ContextChunk / Provenance / ContextBundle
engine.py # index / search / assemble / persist
rank.py # BM25-lite + kind/recency/priority
dedup.py # 近重复抑制
tokenizer.py # 混合中英 token 估算(可替换)
sources/ # memory / skills / session / files
distill/ # dataset / compress / train / evaluate
interfaces/ # cli / http / mcp
examples/ # demo 语料 + 配置
tests/ # 27 个单元与端到端测试
docs/ # 架构、蒸馏、社区提案测试
make test
# 或
PYTHONPATH=src python -m unittest discover -s tests -v覆盖:IR 往返、分块、四类 source、排序、去重、预算、截断、持久化、HTTP、MCP 全链路、蒸馏数据与压缩指标。
现状与边界
token 估算是启发式(1 CJK ≈ 1 token,4 其它字符 ≈ 1 token),可通过
set_tokenizer()换成 tiktoken / 厂商 tokenizer。检索是词法 BM25-lite,没有向量检索;接口已隔离,后续可加 embedding 通道而不动上层。
蒸馏的默认 teacher 是抽取式基线,不是大模型;换成任意 LLM 只需实现
compress()。评测指标(压缩比、fact recall)是便宜可复现的代理指标,不是人工评测。
贡献与通明湖社区
Apache-2.0。社区贡献路径、以及「是否适合进入通明湖社区」的提案与待决问题见 docs/PROPOSAL.md。
设计说明:docs/ARCHITECTURE.md
蒸馏细节:docs/DISTILLATION.md
贡献指南:CONTRIBUTING.md
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Cross-tool persistent memory and context for AI assistants over MCP.
Hosted agent memory: store, search, and recall facts across sessions from any MCP client.
Private-by-default, local-first memory/context/task orchestrator for MCP apps and agents.
shared AI-context layer for teams — persistent memory your agents search and update over MCP
Related MCP Servers
- AlicenseNot gradedqualityDmaintenancePersistent memory MCP server for AI coding agents. Stores, searches, and retrieves context across sessions using SQLite and FTS5.MIT
- FlicenseNot gradedqualityCmaintenanceA local MCP server that semantically searches Markdown context files and extension context links, providing tools for context_search, context_read, and context_status.-
- AlicenseNot gradedqualityCmaintenanceProvides a local context-memory layer for AI assistants, enabling retrieval-augmented queries, explanations, feedback, and status checks via MCP tools.1Apache 2.0
- AlicenseNot gradedqualityDmaintenanceMCP server that enables persistent, hybrid, local memory for LLM agents, with vector + BM25 search, knowledge graph, and policy-driven retention, providing token-budgeted context injection for AI assistants.MIT