MCP文件压缩
一种MCP服务器,通过自动将文件汇总到其公共接口来降低Claude上下文窗口成本。
问题
当Claude跨多个文件处理大型任务时,上下文窗口会不断增长。每个API请求的成本基于 全尺寸 上下文,而不仅仅是新的令牌。这导致了二次成本增长:
- 实施
ptr.rs(2KB)→ 背景:2KB - 实施
raw_page.rs使用ptr.rs(3KB)→ 上下文:5KB - 实施
paged_pool.rs同时使用(4KB)→ 上下文:9KB
完成一个文件后,Claude不需要完整的实现,只需要公共接口(结构、函数、特征)。
解决方案
此MCP服务器:
- 跟踪“活动”文件 --您当前正在编辑的(完整内容)
- 自动汇总非活动文件 -当您切换文件时,前一个文件被总结为其公共API
- 使用AST解析 --确定性、快速、无LLM要求摘要
- 优雅地处理不支持的语言 --返回完整内容,不进行跟踪
安装
来自GitHub(推荐)
npx github:YOUR_USERNAME/mcp-file-compaction本地开发
git clone https://github.com/YOUR_USERNAME/mcp-file-compaction.git
cd mcp-file-compaction
npm install
npm run build配置
添加到您的Claude Code MCP设置中:
{
"mcpServers": {
"file-compaction": {
"command": "npx",
"args": ["github:YOUR_USERNAME/mcp-file-compaction"]
}
}
}或者为了当地发展:
{
"mcpServers": {
"file-compaction": {
"command": "node",
"args": ["/path/to/mcp-file-compaction/dist/index.js"]
}
}
}添加到您的 CLAUDE.md:
## File Operations
Use the file-compaction MCP server for file operations:
- `read_file` instead of `Read` when you need full file contents
- `peek_file` when you only need to check interfaces
- `edit_file` instead of `Edit` for modifications
- `write_file` instead of `Write` for new files
- `file_status` to see tracked files and context savings
This reduces context window size by keeping only summaries of inactive files.工具
read_file
读取文件并将其标记为活动文件。当您切换到其他文件时,会自动汇总上一个文件。
{ "path": "src/lib.rs" }peek_file
在不更改活动文件的情况下获取文件公共接口的摘要。可用于检查API。
{ "path": "src/ptr.rs" }edit_file
通过替换特定字符串来编辑文件。该文件将成为(或保持)活动文件。
{
"path": "src/lib.rs",
"old_string": "fn old_name(",
"new_string": "fn new_name("
}write_file
将内容写入文件,必要时创建文件。该文件将成为活动文件。
{
"path": "src/new_module.rs",
"content": "//! New module\n\npub fn hello() {}\n"
}文件状态
显示所有跟踪的文件,包括大小比较和节省。
Context Status
==============
Active: src/paged_pool.rs (full, 4.2 KB)
Cached Summaries:
src/ptr.rs 312 B (was 2.1 KB, saved 1.8 KB)
src/raw_page.rs 428 B (was 3.4 KB, saved 3.0 KB)
Total Context: 5.2 KB
Without Compaction: 11.5 KB
Savings: 6.3 KB (55%)伪造文件
完全从跟踪中删除文件。
{ "path": "src/old_file.rs" }支持的语言
目前支持摘要:
- 锈 (.rs)--提取公共结构、枚举、特征、函数、类型别名、常量和重新导出
不支持的文件类型可以正常读取/编辑,无需跟踪——它们不会干扰压缩。
总结是如何工作的
对于Rust文件,例如:
//! Type-safe pointer wrappers.
use std::marker::PhantomData;
#[derive(Debug, Clone)]
pub struct Ptr {
raw: *mut T,
_marker: PhantomData,
}
impl Ptr {
pub fn new(raw: *mut T) -> Self {
Self { raw, _marker: PhantomData }
}
pub fn is_null(&self) -> bool {
self.raw.is_null()
}
// Private helper
fn internal_check(&self) -> bool {
!self.raw.is_null()
}
}总结如下:
// Purpose: Type-safe pointer wrappers.
#[derive(Debug, Clone)]
pub struct Ptr { ... }
impl Ptr {
pub fn new(raw: *mut T) -> Self;
pub fn is_null(&self) -> bool;
}私有项、实现细节和文档注释被压缩——只剩下公共接口。
许可证
麻省理工学院
