Claude代码的无损上下文管理
MCP服务器+挂钩增强层,提供无损内存检索、跨压缩事件的自动上下文保存和并行数据处理运算符。
根据论文 *远程代码代理的无损上下文管理* Ehrlich&Blackman(2025)描述了一种确定性架构,该架构通过维护不可变的消息存储、分层摘要DAG和运算符级递归工具,在长上下文基准测试中优于Claude Code。
特性
- 不可变消息存储 --SQLite+FTS5全文搜索,仅可追加
- 层次化摘要DAG --三级升级压缩(preserve_details、bullet_points、确定性截断)
- 自动上下文恢复 --钩子捕获消息并在压缩后注入摘要
- MCP工具 —
lcm_status,lcm_grep,lcm_describe,lcm_expand用于记忆检索 - 并行数据运算符 —
llm_map和agentic_map用于处理具有并发Haiku调用的JSONL文件
先决条件
安装
1.克隆存储库
git clone https://github.com/dpalmqvist/lossless-context-management.git
cd lossless-context-management2.安装依赖项
uv sync3.使用Claude Code注册MCP服务器
claude mcp add --transport stdio lcm -- \
uv --directory /path/to/lossless-context-management run python -m lcm.server替换 /path/to/lossless-context-management 使用克隆仓库的实际路径。
4.配置挂钩
将以下内容添加到您的项目中 .claude/settings.json (或合并到现有的):
{
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume",
"hooks": [
{
"type": "command",
"command": "/path/to/lossless-context-management/hooks/session_start.sh",
"timeout": 10
}
]
},
{
"matcher": "compact",
"hooks": [
{
"type": "command",
"command": "echo '{\"type\":\"compact\"}' | /path/to/lossless-context-management/hooks/session_start.sh",
"timeout": 30
}
]
}
],
"PostToolUse": [
{
"matcher": "Bash|Edit|Write|Read",
"hooks": [
{
"type": "command",
"command": "/path/to/lossless-context-management/hooks/post_tool_use.sh",
"timeout": 10,
"async": true
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "/path/to/lossless-context-management/hooks/user_prompt_submit.sh",
"timeout": 10,
"async": true
}
]
}
]
}
}替换 /path/to/lossless-context-management 与实际路径。
5.设置API密钥
export ANTHROPIC_API_KEY="your-key-here"用法
安装后,LCM工具在Claude Code中可用:
| 工具 | 说明 |
|---|---|
lcm_status | 会话统计:消息计数、摘要计数、令牌、DAG深度 |
lcm_grep | 使用FTS5或正则表达式搜索消息历史记录,按覆盖摘要分组 |
lcm_describe | 查找任何LCM ID(消息、摘要或文件)的元数据 |
lcm_expand | 将摘要展开到其组成消息 |
llm_map | 与无状态Haiku调用并行处理JSONL项 |
agentic_map | 使用多轮代理循环处理JSONL项目 |
命令行界面
# Check session status
uv run lcm status [session_id]
# Manual hook operations
uv run lcm hook capture
uv run lcm hook inject
uv run lcm hook init发展
# Install with dev dependencies
uv sync --dev
# Run tests (75 tests, ~0.5s)
uv run pytest tests/ -v
# Test with MCP Inspector
npx @modelcontextprotocol/inspector uv --directory . run python -m lcm.server运作原理
- 钩子 自动将Claude Code的转录中的消息捕获到仅可追加的SQLite存储中
- 当令牌计数超过 τ_软 (50K令牌),最旧的未汇总消息被分组到块中并汇总为 叶节点 在DAG中
- 当5+个未密集的叶节点累积时,它们是 浓缩的 进入更高级别的摘要节点
- 在 τ_卡片 (20万个令牌),所有未概括的消息都被压缩
- 压实后 会话开始钩子 注入一个包含顶级摘要和LCM ID的上下文恢复块
- 然后,Claude Code可以使用
lcm_expand和lcm_grep深入了解对话历史的任何部分
参考
埃利希,N.和布莱克曼,S.(2025)。 *远程代码代理的无损上下文管理*.arXiv:2506.18655。https://arxiv.org/abs/2506.18655
许可证
麻省理工学院
