Skip to main content
Glama

ContextGC

基于 AST 解析的上下文智能压缩 MCP 插件 — 节省 70-90% token

ContextGC 利用 AST 语法树提取代码骨架(imports、类型定义、函数签名),省略实现细节。这是唯一支持渐进式上下文加载的 MCP 工具:骨架 → 按需展开函数 → 完整代码。

工作原理

┌──────────────────────────────────────────────────┐
│  2000 行 React 组件 (≈18,000 tokens)              │
│                                                    │
│  ┌─ read_code_skeleton ──────────────────────────┐ │
│  │  imports + 类型 + 函数签名 (≈2,000 tokens)     │ │
│  │  函数体替换为省略标记                           │ │
│  └────────────────────────────────────────────────┘ │
│                                                    │
│  ┌─ read_function_body ──────────────────────────┐ │
│  │  按需展开指定函数实现 (≈500 tokens)             │ │
│  └────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────┘

Related MCP server: cerberus-mcp

功能

  • read_code_skeleton — 提取源文件结构骨架,减少 70-90% token 用量

  • read_function_body — 按需展开指定函数的完整实现

  • parse_error_log — 压缩错误日志,过滤 node_modules 栈帧

  • context_gc — 垃圾回收缓存骨架,释放上下文窗口空间

  • MCP Prompt 注入 — 自动引导 AI 使用 ContextGC 替代原生 read_file

  • 三级降级 — AST 解析 → 正则降级 → 截断兜底

  • LRU + TTL 缓存 — 骨架缓存随文件变更自动失效

快速开始

安装与运行

# 克隆
git clone https://github.com/YOUR_USERNAME/contextgc-mcp.git
cd contextgc-mcp

# 安装依赖
npm install

# 构建
npm run build

# 运行
node dist/index.js

配置 Claude Code

claude mcp add contextgc -- node /path/to/contextgc-mcp/dist/index.js

配置 Kilo Code / Cursor / Cline

在 MCP 设置中添加:

{
  "mcpServers": {
    "contextgc": {
      "command": "node",
      "args": ["/path/to/contextgc-mcp/dist/index.js"]
    }
  }
}

工具参考

read_code_skeleton

读取源文件并返回结构骨架。

参数

类型

必填

说明

filePath

string

源文件绝对路径

focusFunction

string

保留此函数的完整实现

focusLine

number

保留此行所在函数的完整实现

maxOutputLines

number

最大输出行数(默认 500)

read_function_body

展开指定函数的完整实现。

参数

类型

必填

说明

filePath

string

源文件绝对路径

functionName

string

要展开的函数名

includeContext

boolean

包含前后 5 行上下文(默认 true)

parse_error_log

压缩错误日志,提取关键信息,过滤噪音。

参数

类型

必填

说明

logContent

string

原始错误日志 / stderr 输出

workspaceRoot

string

工作区根路径,用于识别业务代码

maxFrames

number

最大保留堆栈帧数(默认 10)

context_gc

清除缓存骨架,释放上下文空间。

参数

类型

必填

说明

strategy

"lru" | "all" | "older-than"

GC 策略(默认 lru

ttlMinutes

number

older-than 策略的过期分钟数(默认 30)

配置

在工作区根目录创建 contextgc.config.json

{
  "skeleton": {
    "preserveComments": "doc",
    "preserveTypes": true,
    "maxOutputLines": 500
  },
  "cache": {
    "maxEntries": 100,
    "ttlMs": 1800000
  },
  "logTrimmer": {
    "maxFrames": 10,
    "filterPatterns": ["node_modules", "dist", ".next"]
  }
}

环境变量

变量

说明

默认值

CONTEXTGC_CONFIG

自定义配置文件路径

自动搜索

CONTEXTGC_ENABLED

全局开关

true

CONTEXTGC_LOG_LEVEL

日志级别(debug/info/warn/error

warn

支持的语言

语言

解析器

状态

JavaScript / JSX

Babel

✅ 完整支持

TypeScript / TSX

Babel

✅ 完整支持

Python / Go / Rust / Java / C++

正则降级

⚠️ 基础支持

其他语言

正则降级

⚠️ 基础支持

Tree-sitter 集成(完整多语言 AST 支持)计划在 v0.2 实现。

架构

AI 编码助手 (宿主)
        │ MCP (JSON-RPC 2.0 over stdio)
        ▼
┌─────────────────────────────────┐
│       ContextGC MCP Server       │
│  ┌───────────────────────────┐  │
│  │      MCP 协议层            │  │
│  └─────────┬─────────────────┘  │
│  ┌─────────▼─────────────────┐  │
│  │     工具编排层              │  │
│  │  骨架 | 展开函数 | 日志 | GC│  │
│  └─────────┬─────────────────┘  │
│  ┌─────────▼─────────────────┐  │
│  │     解析器抽象层            │  │
│  │  Babel | Tree-sitter | 正则 │  │
│  └───────────────────────────┘  │
└─────────────────────────────────┘

开发

# 安装依赖
npm install

# 构建
npm run build

# 运行测试
npm test

# 监听模式运行测试
npm run test:watch

# 开发模式(自动重编译)
npm run dev

Token 节省基准

场景

原始

压缩后

压缩率

2000 行 React 组件(骨架提取)

~18,000 tok

~2,000 tok

89%

1000 行 npm build 报错日志

~8,000 tok

~400 tok

95%

500 行 diff 输出

~5,000 tok

~1,500 tok

70%

综合大型项目调试会话

~80,000 tok

~15,000 tok

81%

以上为理论估算值,实际压缩率取决于代码风格和文件结构。

许可证

MIT

Available Tools

4 tools
context_gcA

Trigger context garbage collection. This clears cached file skeletons that are no longer needed, freeing context window space. Use this when you notice context is getting full or after completing a task branch.

ParametersJSON Schema
NameRequiredDescriptionDefault
strategyNoGC strategy: 'lru' evicts least-recently-used entries, 'all' clears everything, 'older-than' clears entries older than TTL. Default: 'lru'.
ttlMinutesNoOnly used with 'older-than' strategy. Entries older than this many minutes will be evicted. Default: 30.

TDQS

A4.1/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description bears full responsibility. It discloses the tool clears cached file skeletons and frees context window space, and mentions the effect of different strategies. It does not warn of any destructive side effects, but the described action is a non-destructive cleanup of 'no longer needed' items.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences long: the first states what it does, the second gives usage guidance. It is front-loaded and concise, with no superfluous information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has two well-documented parameters and no output schema. The description covers the purpose and usage, but does not mention what the tool returns (e.g., success status). Given the complexity, this is a minor gap.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% coverage with detailed descriptions for both parameters, including enum values and defaults. The description does not add significant new information beyond what is already in the schema, so a score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Trigger context garbage collection' with the specific verb 'trigger' and resource 'context garbage collection'. It further explains it clears cached file skeletons to free context window space, which is distinct from sibling tools like parse_error_log or read_code_skeleton.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly tells when to use: 'when you notice context is getting full or after completing a task branch.' It doesn't cover when not to use or alternatives, but the context is clear and sufficient give the tool's specific purpose.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

parse_error_logA

Parses and compresses error logs / stack traces to extract only the essential error information. Filters out node_modules frames, keeps only your source code references. Use this instead of reading raw stderr output to save 90%+ tokens.

ParametersJSON Schema
NameRequiredDescriptionDefault
logContentYesThe raw error log / stderr output to compress
workspaceRootNoAbsolute path of the workspace root, used to identify business code frames.
maxFramesNoMaximum number of stack frames to include. Default: 10.

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses key behaviors: filters out node_modules frames, keeps only source code references, and compresses to save tokens. It does not mention any destructive actions or side effects, which is appropriate for a parsing tool. However, it could be more explicit about the output format.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences long, front-loaded with the main action, and every sentence adds value. No redundant or vague language. It is efficient and easily parseable by an AI agent.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (parsing logs) and the fact that the schema covers all parameters, the description provides sufficient context. It explains the filtering behavior and token savings. The output format is not described, but it's implied to be a compressed version of the input. No output schema exists, so the description could briefly mention the output structure.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so baseline is 3. The description adds minimal new semantics beyond the schema; it reinforces the purpose of filtering and compressing but doesn't provide additional detail about parameter constraints or usage nuances.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool parses and compresses error logs/stack traces, with the specific verb 'Parses and compresses' and resource 'error logs / stack traces'. It distinguishes itself by mentioning it filters out node_modules and keeps only source code references, which sets it apart from reading raw stderr.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly says 'Use this instead of reading raw stderr output to save 90%+ tokens', providing clear guidance on when to use this tool. It does not mention when not to use it or alternative tools, but the sibling tools are unrelated, so no further differentiation is necessary.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

read_code_skeletonA

Reads a source code file and returns ONLY its structural skeleton (imports, type definitions, class declarations, function signatures with parameter types and return types). Internal logic is replaced with '/* ... [omitted by ContextGC] ... */'. Use this tool FIRST when exploring files larger than 100 lines to save 70-90% context tokens. After reviewing the skeleton, use read_function_body to expand specific functions.

ParametersJSON Schema
NameRequiredDescriptionDefault
filePathYesAbsolute path to the source code file
focusFunctionNoName of function/method to keep full body for. Use when you need to see a specific implementation.
focusLineNoLine number to focus on — keeps the containing function's body intact.
maxOutputLinesNoMaximum number of lines in the output. Default: 500.

TDQS

A4.7/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, but description fully discloses that internal logic is replaced with comments, saving tokens. No destructive behavior or contradictions; description carries the burden well.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three short sentences: first defines action, second states when to use, third guides next step. No unnecessary words, perfectly front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no output schema, description explains what output looks like (structural skeleton with omitted internals). Parameters are well-documented in schema; tool's purpose is fully covered.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so baseline is 3. Description does not add parameter details beyond what schema provides. The focus parameters are explained in schema adequately.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it reads source code and returns structural skeleton only, specifying included and omitted parts. It distinguishes from sibling 'read_function_body' by noting it can expand specific functions.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly says 'Use this tool FIRST when exploring files larger than 100 lines to save 70-90% context tokens' and directs to use 'read_function_body' after reviewing. Provides context and alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

read_function_bodyA

Expands the full implementation of a specific function/method from a file. Use AFTER read_code_skeleton when you need to see a particular function's logic. This returns ONLY the requested function's complete body, not the entire file.

ParametersJSON Schema
NameRequiredDescriptionDefault
filePathYesAbsolute path to the source code file
functionNameYesName of the function or method to expand
includeContextNoInclude 5 lines of context before/after the function. Default: true.

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description must convey behavior. It explains the return scope (only the requested function body) and mentions the includeContext parameter. Missing disclosure of error handling or performance, but the core behavior is clear.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, no redundant words. First sentence states purpose, second sentence gives usage guidance. Highly efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

All parameters are documented in schema and description. The description clarifies the return value (function body) despite missing output schema. Adequate for the complexity of the tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so baseline is 3. The description does not add additional semantic meaning beyond what the schema provides for the parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses specific verb 'expands' and identifies the resource 'function body'. It clearly distinguishes from sibling 'read_code_skeleton' by stating it returns only the function body, not the entire file.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly instructs to use this tool AFTER read_code_skeleton when needing a specific function's logic. Does not explicitly state when not to use, but the context implies it is for focused detail rather than broad file reading.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 4 tool updatesv0.1.0
    • First observedcontext_gc
    • First observedparse_error_log
    • First observedread_code_skeleton
    • First observedread_function_body

TDQS

A4.4/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a clear, distinct purpose: freeing cache, compressing error logs, reading structural skeletons, and expanding function bodies. No overlap in functionality.

Naming Consistency5/5

All tools follow a consistent verb_noun snake_case pattern, e.g., context_gc, parse_error_log, read_code_skeleton, read_function_body. Predictable and clear.

Tool Count5/5

Four tools is well-scoped for a server focused on context optimization. Each tool earns its place with a specific function, not too few or too many.

Completeness4/5

The tool set covers the key strategies: triggering GC, compressing errors, reading skeletons, and expanding functions. Minor gaps like clearing specific caches exist but do not hinder typical workflows.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    C
    quality
    A
    maintenance
    An MCP server that filters and compresses context by 80-90% before sending to an LLM, using code knowledge graphs and compression.
    20
    2
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    An MCP server that provides ultra-efficient code exploration through AST analysis, reducing LLM token usage by up to 95% while enabling instant call graph generation and dependency analysis for massive codebases.
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    An AST-based MCP server that provides token-efficient codebase skeletons to LLM agents, reducing context token usage by 80-95% by exposing structural information instead of full source files.
    5
    4 npm
    3
    MIT
  • -
    license
    Not graded
    quality
    Not graded
    maintenance
    AST-aware code exploration MCP server for AI agents, optimized for token efficiency.
    -