Skip to main content
Glama
pandolfipedro

ContextCache MCP

README.md
# ContextCache MCP

> **Budget-aware context packs for AI coding assistants.**  
> Stop sending entire codebases to your LLM. Send only what matters — within a token budget you control.

[![Node](https://img.shields.io/badge/node-%3E%3D20-brightgreen)](https://nodejs.org)
[![MCP](https://img.shields.io/badge/MCP-compatible-blue)](https://modelcontextprotocol.io)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.8-blue)](https://www.typescriptlang.org/)

ContextCache is a local **MCP server** that indexes your TypeScript/JavaScript project and returns **Context Packs** — minimal, dependency-aware file sets optimized for a specific task.

Works with **Cursor**, **Claude Code**, **Codex CLI**, and any MCP-compatible client.

---

## Why use ContextCache?

| Without ContextCache | With ContextCache |
|---------------------|-------------------|
| AI reads 200–500 files blindly | AI receives 5–15 ranked files |
| 50k+ tokens per request | 2k–8k tokens within your budget |
| Misses `UserRepository.ts` behind `AuthService.ts` | Dependency graph expands related files |
| No visibility into context cost | `token_metrics` + `relevance_score` on every pack |

**Example:** task `"fix login bug"` on a 500-file repo → returns `AuthService.ts`, `JwtMiddleware.ts`, and their dependencies — not your entire `src/` tree.

---

## Features

- **Budget-aware selection** — set `budget_tokens`; engine stops before exceeding it
- **Dependency graph** — BFS expansion from seed files (not flat keyword search)
- **AST-based indexing** — TypeScript Compiler API extracts classes, functions, imports, exports
- **Incremental index** — skips unchanged files via `content_hash`
- **Query cache** — instant responses for repeated tasks (auto-invalidated on reindex)
- **Relevance score** — 0.0–1.0 signal strength on every pack
- **100% local** — SQLite on disk, no cloud, no API keys, no embeddings required
- **Two MCP tools** — `get_context_pack`, `get_file_summary`

---

## Quick start

### Prerequisites

- **Node.js 20+**
- A **TypeScript or JavaScript** project to index

### 1. Clone & build

```bash
git clone https://github.com/YOUR_USERNAME/contextcache-mcp.git
cd contextcache-mcp
npm install
npm run build
```

### 2. Index your project

```bash
# From your project root:
node /path/to/contextcache-mcp/apps/indexer/dist/cli.js init
node /path/to/contextcache-mcp/apps/indexer/dist/cli.js index
node /path/to/contextcache-mcp/apps/indexer/dist/cli.js stats
```

### 3. Add MCP server to your AI client

**Cursor** — create or edit `.cursor/mcp.json` in your project:

```json
{
  "mcpServers": {
    "contextcache": {
      "command": "node",
      "args": ["/absolute/path/to/contextcache-mcp/apps/server/dist/index.js"],
      "env": {
        "CONTEXTCACHE_ROOT": "${workspaceFolder}"
      }
    }
  }
}
```

**Claude Desktop** — edit `claude_desktop_config.json` with the same block.

See [mcp-config.example.json](./mcp-config.example.json) for a template.

### 4. Use it

Ask your assistant to call `get_context_pack` at the start of a coding task:

```json
{
  "task": "fix authentication bug in login flow",
  "budget_tokens": 4000,
  "mode": "cursor"
}
```

**Sample response:**

```json
{
  "relevance_score": 0.84,
  "budget_used": 2300,
  "budget_remaining": 1700,
  "summary": "3 core files, 2 dependencies via graph.",
  "files": [
    {
      "path": "src/auth/AuthService.ts",
      "score": 0.92,
      "summary": "Classes: AuthService. Exports: login, authenticate",
      "token_estimate": 340
    }
  ],
  "dependencies": [
    { "path": "src/repos/UserRepository.ts", "relation": "imported_by", "depth": 1 }
  ],
  "token_metrics": {
    "full_project_tokens": 58000,
    "selected_tokens": 2300,
    "saved_tokens": 55700,
    "reduction_percent": 96.0
  }
}
```

---

## MCP tools

### `get_context_pack`

Builds a complete context pack for a task.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `task` | `string` | **required** | What you want to accomplish |
| `budget_tokens` | `number` | `8000` | Maximum tokens for the pack |
| `mode` | `"json"` \| `"text"` \| `"cursor"` | `"json"` | `text`/`cursor` returns markdown |
| `use_snapshot` | `boolean` | `false` | Compare against manual snapshot baseline |
| `skip_cache` | `boolean` | `false` | Bypass query cache |

### `get_file_summary`

Returns structured metadata for a single file.

```json
{ "path": "src/auth/AuthService.ts" }
```

---

## CLI

```bash
npm run contextcache -- <command>
```

| Command | Description |
|---------|-------------|
| `init [path]` | Create `.contextcache/` in a project |
| `index [paths...]` | Index TS/JS files (incremental) |
| `stats` | Index stats, token totals, relevance averages |
| `snapshot` | Save a manual baseline snapshot |
| `pack <task>` | Generate a context pack from terminal |

```bash
# Human-readable pack
npm run contextcache -- pack "fix login bug" -b 4000 -m text

# JSON pack
npm run contextcache -- pack "fix login bug" -b 4000 -m json
```

---

## How it works

```
Your task + budget_tokens
         │
         ▼
   QueryCache ── hit? ──► return cached pack
         │ miss
         ▼
   HeuristicRanker ──► rank files by symbols, paths, imports
         │
         ▼
   DependencyGraph ──► expand related files (BFS, 2 hops)
         │
         ▼
   TokenBudgetManager ──► select files until budget is full
         │
         ▼
   Context Pack + relevance_score + token_metrics
```

**Ranking signals:** symbol match · path match · graph proximity · import match

---

## Benchmarks

```bash
npm run benchmark
npm run benchmark:report   # saves benchmarks/results/latest.json
```

Tracks `relevance_score`, `precision`, `reduction_percent`, and `generation_time_ms` against fixture projects.

---

## Project structure

```
contextcache-mcp/
├── apps/
│   ├── shared/     # ContextEngine, DependencyGraph, indexer
│   ├── indexer/    # CLI (contextcache)
│   └── server/     # MCP server (stdio)
├── benchmarks/
├── mcp-config.example.json
└── ARCHITECTURE.md
```

Each indexed project gets a `.contextcache/` folder:

```
your-project/.contextcache/
├── config.json
└── contextcache.db
```

---

## What it is NOT

- Not a RAG / vector search tool
- Not a cloud service
- Not a flat file finder — it builds **coherent packs** via dependency graph
- Not dependent on paid embedding APIs (MVP)

---

## Roadmap

- [ ] Python & C# parsers (tree-sitter)
- [ ] Optional semantic search (local embeddings)
- [ ] `get_related_files` tool
- [ ] npm global install (`npx contextcache`)

---

## Requirements

| Requirement | Version |
|-------------|---------|
| Node.js | 20+ |
| Languages (MVP) | TypeScript, JavaScript |

---

## Contributing

Issues and PRs welcome. See [ARCHITECTURE.md](./ARCHITECTURE.md) for technical details.

1. Fork the repo
2. Create a branch (`git checkout -b feature/my-feature`)
3. Run `npm run build && npm run benchmark`
4. Open a PR

---

## License

[MIT](./LICENSE)