contextshrinker
Zero-dependency Go MCP server that indexes codebases into an embedded Kùzu graph DB—enabling 90%+ token reduction, precise call-chain queries, and AI architectural health audits.
README
<p align="center"> <img src="logo.png" alt="contextshrinker logo" width="350" /> </p>
contextshrinker
contextshrinker is a zero-dependency, headless Model Context Protocol (MCP) server written in Go. It indexes local codebases into an embedded Kùzu graph database to drastically reduce LLM token bloat for autonomous AI agents (such as Claude Code, Cursor, Antigravity IDE, Aider, and Claude Desktop).
Instead of forcing AI agents to read raw source files or run clumsy grep-based searches, contextshrinker allows agents to query a semantic graph of your project's architectural dependencies, function call chains, and class inheritance structures—reducing input context consumption by 90% to 98%.
🚀 Key Features
- Universal Agent Compatibility: Attaches seamlessly to any MCP-compliant coding tool or IDE over standard I/O (
stdio). - Zero External Databases: Completely self-contained. Runs an in-process graph database (Kùzu) inside your project's local
.contextshrinker/directory. - Auto-Managed LSP Daemons: Automatically detects project languages, programmatically provisions sandboxed language servers (like
goplsfor Go orpyrightfor Python) if missing, and queries their RPC interfaces in the background to build call graphs. - Multi-Language Support: Full AST syntax parsing and semantic indexing for Go, Python, JavaScript, TypeScript, and Java.
- Clean Project Isolation: Every workspace maintains its own
.contextshrinker/directory containing isolated configuration rules (.contextshrinker/ignore) and graph database files (.contextshrinker/db/). - Live State Sync: Uses
fsnotifyto watch your files recursively. On save, a debounced delta update purges old nodes and re-indexes modified files in real-time. - Interactive Graph Visualization: Generates a stunning, Vis.js-powered dark-mode HTML codebase visualization (
.contextshrinker/contextshrinker_graph.html) on-demand.
🛠️ Architecture: The Two-Pass Ingest
To index your code cleanly, contextshrinker runs a two-pass ingestion sequence:
graph TD
A[Walk Workspace] -->|Filter via .contextshrinker/ignore| B[Pass 1: Tree-sitter Syntax]
B -->|Create Nodes| C[(Kùzu Graph DB)]
C --> D[Pass 2: LSP Semantic Cross-References]
D -->|Create CALLS / IMPLEMENTS Edges| C
- Pass 1 (Tree-sitter AST Extraction): Rapidly scans source files to extract entities (Functions/Methods, Classes/Structs, Variables) and their associated docstrings, inserting them as nodes.
- Pass 2 (LSP Semantic Resolving): Queries background Language Server Protocol (LSP) daemons for cross-references to identify and connect invocations (
CALLS), imports (IMPORTS), and class inheritances (IMPLEMENTS/EXTENDS).
📥 Installation
Option 1: Precompiled Binaries (Fastest)
If you don't want to install Go, you can download a precompiled portable package for your platform:
- Go to the Releases page.
- Download the archive for your OS (
.tar.gzor.zip). - Extract the archive. Keep the executable (
contextshrinker) and its dynamic library (libkuzu/kuzu_shared) in the same folder. - Run the executable from that directory:
macOS / Linux:
chmod +x contextshrinker
./contextshrinker --help
Windows:
contextshrinker.exe --help
Option 2: Build from Source (Requires Go)
Prerequisites
- Go (1.21 or later)
- Node.js & npm (for automatically installing JS/TS and Python LSPs)
Compile
Clone the repository and run:
go build -o contextshrinker
To install it directly to your system PATH:
go install
🔌 Integration into Coding Agents
contextshrinker runs on-demand as a child process of your coding agent. Register the absolute path to the compiled binary in your client:
1. Antigravity IDE (Gemini Agent Panel)
- Open the Antigravity IDE.
- Click the
...(More Options) menu in the Agent Panel. - Select "Manage MCP Servers" $\rightarrow$ "View raw config".
- Register the server in your
mcp_config.json:{ "mcpServers": { "contextshrinker": { "command": "/absolute/path/to/contextshrinker" } } }
2. Claude Code (CLI)
Add the server automatically:
claude mcp add contextshrinker /absolute/path/to/contextshrinker
3. Cursor IDE
- Navigate to Settings $\rightarrow$ Features $\rightarrow$ MCP.
- Click + Add New MCP Server.
- Set configuration:
- Name:
contextshrinker - Type:
command - Command:
/absolute/path/to/contextshrinker
- Name:
4. Claude Desktop
Add it to your ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"contextshrinker": {
"command": "/absolute/path/to/contextshrinker"
}
}
}
🧰 Exposed Tools
Once configured, the following tools will automatically be available to your AI coding agents:
search_codebase- Arguments:
query(string) - Description: Executes Full-Text Search and Cypher queries to match structures and docstrings across classes, functions, and variables.
- Arguments:
get_call_chain- Arguments:
target_function(string),depth(integer, max 5) - Description: Resolves upstream caller chains using variable-length path Cypher queries to map calling dependencies.
- Arguments:
get_file_structure- Arguments:
file_path(string) - Description: Retrieves the complete abstract node structure (classes, interfaces, methods, variables) contained in a single file without feeding the raw text contents to the context window.
- Arguments:
visualize_codebase- Description: Triggers an on-demand HTML export, saving
contextshrinker_graph.htmlinside your.contextshrinker/directory.
- Description: Triggers an on-demand HTML export, saving
get_architecture_report- Description: Retrieves the complete codebase architectural health report containing metrics on God Objects, coupling hotspots, cycles, dead unexported functions, AI metrics (SCR, DCR, BVI, AOI, Call Chain Depth Index - CDI), and actionable code quality guidelines (Jeff Dean principles) with AI system prompt directives.
🏛️ Codebase & Architecture Optimization
You can use contextshrinker to systematically audit coupling, analyze domain boundaries (DDD), and guide code restructuring (e.g. splitting a monolith into modules) using LLMs.
Optimization Workflow
-
Generate the Architectural Metrics & Guidelines: Run the analysis command in your terminal to inspect the codebase graph and generate a report:
./contextshrinker analyzeThis generates
contextshrinker-report.mdcontaining metrics for God Objects (high outbound coupling), Black Holes (high inbound calls), Cyclic Import Paths, Dead Code (unused private functions), AI Metrics (including Call Chain Depth Index - CDI), and Actionable Code Quality & LLM Architecture Guidelines (Jeff Dean principles). -
Obtaining the System Prompt: Retrieve the principal systems architect prompt from the CLI:
./contextshrinker prompt architect -
Analyzing with LLMs:
- Set the output of the
prompt architectcommand as the System Prompt for your LLM. - Provide the contents of the generated
contextshrinker-report.mdas the Context / Input. - Ask the LLM to propose bounded context splits or interface boundaries.
- Set the output of the
-
Agentic / Tool-Use Workflows: If using an MCP-compatible agent (like Antigravity IDE, Claude Code, or Cursor), you can ask it directly:
"Run the contextshrinker analysis report, read the generated markdown, and act as a Systems Architect to audit our design hotspots. Use the
get_call_chainandget_file_structuretools to inspect the coupling before suggesting concrete module extractions."
⚙️ Configuration & Ignores
To prevent workspace graph bloat, standard library and dependency folders (node_modules/, vendor/, .git/, etc.) are ignored by default.
To add custom ignores, initialize the project and generate a .csignore file at your workspace root by running:
contextshrinker init
Each line in .csignore is matched recursively:
# Custom project ignores
*.log
tmp-output/
dist/
.vitepress
💡 Best Practices for Large Projects
If you are using contextshrinker on a medium-to-large project (e.g., hundreds or thousands of files), running the initial codebase ingestion directly from inside an LLM/agent prompt (like Claude Code or Cursor) can cause agent timeout issues. This happens because the agent has a tight timeout limit (typically 60 seconds) while waiting for the first-time workspace parsing and LSP references resolution to complete.
To prevent this, follow this optimized workflow in your terminal before starting the agent:
- Initialize the workspace:
Run the initialization command to create the configuration directory and default ignore list:
contextshrinker init - Configure your ignores:
Open the generated
.csignorefile at your workspace root and add any large directories you want to exclude (e.g. documentation sites, test assets, built build folders). - Build the database offline:
Run the analyze command once from your terminal to build the initial graph database:
This performs the heavy lifting of Tree-sitter parsing and LSP semantic cross-referencing offline. Once the database is populated, subsequent agent requests and live state syncs will run incrementally in seconds, preventing any future timeouts!contextshrinker analyze
📊 Command Line Interface (CLI) Mode
You can query the codebase graph, start the MCP server daemon explicitly, retrieve systems architect prompts, or generate health analysis reports directly from your terminal.
1. Start the MCP Server
By default, running ./contextshrinker with no arguments starts the MCP server daemon. You can also trigger it explicitly:
./contextshrinker start
2. Run Codebase Architectural Analysis
Analyze the codebase structure (God objects, inbound call hot-spots, cyclic imports, dead code, Call Chain Depth Index - CDI, and LLM code quality guidelines) and write a report to contextshrinker-report.md:
./contextshrinker analyze
3. Print Principal Systems Architect Prompt
Print the Domain-Driven Design (DDD) principal systems architect system prompt to stdout:
./contextshrinker prompt architect
4. Search the Codebase
Find functions, classes, or variables matching a query:
./contextshrinker search "IngestWorkspace"
5. Trace Call Chains
Trace upstream callers of a target function name (default depth is 3, maximum is 5):
./contextshrinker call-chain "IngestWorkspace" --depth 3
6. Retrieve File Structure
Get the structure of a file without reading its full text content:
./contextshrinker structure "main.go"
7. Generate Interactive Visualization
Generate a Vis.js codebase graph representation:
./contextshrinker visualize
Open the generated .contextshrinker/contextshrinker_graph.html in any browser to explore your project's architecture interactively.
Options (Global Flags)
-
--workspace <path>: Specifies the project directory (defaults to.). -
--db <path>: Specifies the database storage directory (defaults to.contextshrinker/db). -
--reindex: Forces a full workspace ingestion scan (re-parsing code and mapping LSP relationships) before executing the query. If the database is empty, ingestion runs automatically. -
Note: Because Kuzu DB establishes an exclusive file-level lock, ensure your IDE's MCP client is paused or stopped when running CLI commands on the active database, or use a different workspace/db directory with the CLI flags.
📄 License
This project is licensed under the MIT License.
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.