Skip to main content
Glama
README.md
# TokenMS (Token Management System)

> **Local-First Code Intelligence and Context Management for AI Coding Agents**
> Compress context, prevent exploratory rediscovery loops, and bridge architectural disconnects across Python, TypeScript, Rust, and Flutter (Dart).

[![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![Python: 3.11+](https://img.shields.io/badge/Python-3.11%2B-blue.svg)](https://www.python.org/)
[![Protocol: MCP](https://img.shields.io/badge/Protocol-MCP-green.svg)](https://modelcontextprotocol.io/)
[![Tests: Passing](https://img.shields.io/badge/Tests-111%20Passing-brightgreen.svg)]()
[![Contributions Welcome](https://img.shields.io/badge/Contributions-Welcome-brightgreen.svg)](CONTRIBUTING.md)
![GitHub forks](https://img.shields.io/github/forks/HARSHNEXX/TokenMS?style=social)

[About this project](./about.md) | [Contributing](./CONTRIBUTING.md) | [Security](./SECURITY.md)

---

## The Problem

AI coding agents waste a large portion of their token budget on file discovery rather than actual work.

A typical agent session without TokenMS looks like this:

| Without TokenMS | With TokenMS |
| :--- | :--- |
| Agent reads 8-15 whole files to find relevant code | Agent receives only the exact symbols needed |
| Repeated `grep` and exploratory reads per task | Structured AST retrieval in a single call |
| Manual relationship discovery across modules | Cross-module pathway traversal built in |
| 6,000-330,000 tokens consumed per task | 1,500-3,500 tokens per task (budget-controlled) |
| Agent loses critical context in long conversations | Persistent curated knowledge ledger across sessions |

The root cause: agents are optimized for chat, not for navigating large codebases. They read files sequentially, re-read them when context shifts, and have no way to know that `AuthService` in `auth/service.py` is the class that actually matters for the task at hand.

**TokenMS solves this at the infrastructure level**, not by prompting the agent to "be smarter."

---

## What is TokenMS?

**TMS** runs locally alongside your editor as a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) service. It parses your repository into an Abstract Syntax Tree (AST) symbol graph, maps cross-module relationships, and uses Knapsack optimization to assemble only the exact classes, functions, and interfaces required for a task into a compact token budget.

### Key Capabilities

* **Multi-Language AST Parsing:** Extracts classes, methods, signatures, and docstrings for Python, TypeScript, JavaScript, Rust, and Dart via Tree-Sitter.
* **Hybrid Multi-Modal Retrieval:** Blends SQLite FTS5 (BM25 lexical search) with phrase proximity n-grams, Personalized PageRank (PPR) graph walks, and local CPU vector embeddings.
* **Enclosing Class Context & Decorator Hoisting:** Slices focal functions while automatically preserving surrounding class headers, constructors, and annotations (such as `@override`, `@Post`, `@Injectable`).
* **Neuropathway Edge Traversal:** Bridges decoupled architectural layers (for example, tracing a Flutter UI button to its Riverpod provider, repository, and Supabase client).
* **Local-First & Zero Cloud Cost:** Runs entirely on your CPU using SQLite with Write-Ahead Logging (WAL) and local vector embeddings. No external API keys or cloud dependencies required.
* **Adaptive Token Budget Controller:** Dynamically scales context from 1,200 to 4,000 tokens based on query complexity and multi-channel candidate consensus.

---

## First-Run Experience

Here is exactly what happens after installation, step by step.

### Step 1: Install TokenMS

```bash
git clone https://github.com/HARSHNEXX/TokenMS.git
cd TokenMS
python -m venv .venv

# Windows:
.venv\Scripts\activate
# Linux / macOS:
source .venv/bin/activate

pip install -e .
```

> **Note on the embedding model:** On the very first run, TMS downloads the [Model2Vec](https://github.com/MinishLab/model2vec) static embedding model (~30 MB) from HuggingFace. This is a one-time download; afterwards the model is cached locally and TMS operates entirely offline. No API keys are needed at any point.

### Step 2: Index your project

Run this once inside the repository you want TMS to understand:

```bash
cd /path/to/your/project
python -m tms.app index

# Verify the index is healthy
python -m tms.app status
```

TMS parses every supported source file, extracts AST symbols, computes cross-module call graphs, and stores everything in `.tms/index.sqlite`. Indexing a 50 KLOC Python project typically takes 10-30 seconds.

### Step 3: Configure your MCP client

#### Cursor

Add to `.cursor/mcp.json` or your Global Cursor Settings:

```json
{
  "mcpServers": {
    "tms": {
      "command": "python",
      "args": ["-m", "tms.app", "serve"],
      "cwd": "${workspaceFolder}"
    }
  }
}
```

#### Claude Desktop

Add to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "tms": {
      "command": "python",
      "args": ["-m", "tms.app", "serve"],
      "cwd": "/path/to/your/project"
    }
  }
}
```

### Step 4: Agent requests task context

When your agent starts a task, it calls `resolve_task_context` with a natural language description:

```
Task: "Add retry logic to the payment processor"
```

TMS responds with the precise symbols your agent needs: the `PaymentProcessor` class signature, its `process()` method body, the `RetryPolicy` interface it depends on, and any decorators or error handlers in scope. The response is typically 1,500-3,500 tokens.

### Step 5: Agent works on focused context

Your agent reads only the symbols TMS returned, makes its edits, and calls `record_outcome` to reinforce verified symbols into the curated knowledge ledger. Future tasks on the same codebase get even more accurate context.

```
resolve_task_context("Add retry logic to the payment processor")
  -> 2,840 tokens of exactly relevant code returned
  -> Agent edits PaymentProcessor.process() with full context
  -> record_outcome() persists verified symbols to ledger
```

---

## Architecture

```text
                           AI Coding Agent
             (Claude Desktop / Cursor / VS Code)
                                  |
                        MCP Protocol (stdio)
                                  |
+-------------------------------------------------------------------+
|                            TMS Gateway                            |
|                                                                   |
| [resolve_task_context]  [query]  [batch]  [edit]  [record_outcome]|
+-------------------------------------------------------------------+
       |                          |                        |
       v                          v                        v
+----------------------+  +---------------------+  +----------------+
|  Hybrid Retrieval    |  |  AST Safe Patcher   |  | Output Parser  |
| - SQLite FTS5 (BM25) |  | - AST Fingerprints  |  | - Error traces |
| - Graph PageRank     |  | - Preconditions     |  | - Log cleaner  |
| - Local Embeddings   |  | - Live Buffer Sync  |  +----------------+
| - Knapsack Packer    |  +---------------------+
+----------------------+             |
       |                             |
       +--------------+--------------+
                      |
+-------------------------------------------------------------------+
|                    Storage & Persistence Layer                    |
|                                                                   |
| - SQLite WAL Database (.tms/index.sqlite)                         |
| - Serialized single-writer queue (avoids SQLITE_BUSY locks)       |
| - Git-versioned curated ledger (.tms/curated_knowledge.jsonl)     |
+-------------------------------------------------------------------+
```

---

## Standard MCP Tools

TMS provides 8 standardized tools exposed over stdio:

| Tool | Purpose | Primary Inputs |
| :--- | :--- | :--- |
| `resolve_task_context` | Primary agent entry point for evidence-backed context | `task_query`, `token_budget`, `compact`, `semantic_hints`, `target_layers`, `unsaved_buffers` |
| `query` | Targeted AST symbol and relationship inspection | `query_type` (`callers`, `symbol`, `neighbors`), `target_id` |
| `batch` | Runs multiple queries in a single round-trip | `queries` (list of query dicts) |
| `edit` | AST-verified symbol replacement (safe buffer and disk) | `rel_path`, `symbol_name`, `new_symbol_code`, `expected_ast_fingerprint` |
| `validate` | Safe test or linter execution with output compression | `test_command` (`pytest`, `flutter test`, `npm test`) |
| `record_outcome` | Reinforces verified symbols and vocabulary in memory | `task_id`, `status` (`resolved` / `failed`), `verified_files` |
| `reconcile_knowledge` | Re-indexes repository, prunes stale entries, syncs ledger | _None_ |
| `get_status` | Returns index health, file counts, and WAL stats | _None_ |

---

## Agent Best Practices: The 4 Execution Rules

To achieve maximum token savings, configure your agent system prompt with these 4 rules. Without them, agents can fall into the additive trap of querying TMS and reading entire files anyway.

1. **Step 0 (Resolve Context First):**
   Call `resolve_task_context` exactly once at the beginning of any coding task with the natural language query.
2. **Trust Retrieved Code:**
   Treat the AST symbols, enclosing classes, and interface contracts returned by TMS as primary context. Do not run exploratory grep or inspect unedited companion files.
3. **Strict File Read Limits:**
   Read at most 2 to 3 files that are actively being modified. Read each target file once in full rather than in micro-chunks.
4. **One-Pass Consolidated Edits:**
   Apply all imports, methods, and widget modifications in a single contiguous edit block to prevent re-reading files to verify shifted line numbers.

When agents follow these rules, cumulative session tokens drop by **40% to 50%**.

---

## Empirical Benchmark Results

Measured across 17 real-world development tasks on the TMS codebase itself (118 files, 429 symbols, 5,584 relationships), spanning storage backends, cross-boundary extractors, AST parsers, and client-side architectures. Results are **live-verified** — the numbers below were produced by running `scripts/benchmark_external_repo.py` against the live SQLite index.

### Methodology

| Parameter | Detail |
| :--- | :--- |
| **Tasks** | 17 built-in `DeepBenchmarkTask` instances, one per TMS subsystem |
| **Tokenizer** | char/4 approximation (~4 chars per token), consistent across all strategies |
| **Baseline: Full Repo Dump** | All source files concatenated (222,520 tokens for this repo) |
| **Baseline: Lexical / Grep** | BM25 top-5 hits per query; matched files read in full |
| **Baseline: Whole Subsystem** | Every file in the subsystem directory for the task read in full |
| **TMS** | Single `resolve_task_context` call per task, 2,500 token budget |
| **Quality check** | Recall@5 and MRR measured per task against ground-truth symbol IDs |

### Results

| Strategy | Total Tokens (17 tasks) | Avg / Task | Savings vs Subsystem |
| :--- | :--- | :--- | :--- |
| **Full Repository Dump** | 3,782,840 | 222,520 | 99.4% more tokens than TMS |
| **Lexical Whole-Files (Grep)** | 112,144 | 6,597 | 55.0% more tokens than TMS |
| **Whole-Subsystem Reading** | 106,532 | 6,267 | 52.6% more tokens than TMS |
| **TMS Knapsack Resolution** | **50,444** | **2,967** | **Baseline winner** |

> **What "Total Tokens" means:** The sum of raw file bytes ÷ 4 injected into the agent's context window across all 17 tasks under that strategy. Does not include output tokens or conversation overhead.

> **Context quality:** TMS returned valid, actionable context for all 17 tasks (Recall@5 = 0.66 avg, MRR = 0.84 avg). Tasks where recall was lower used subsystems with many small files; TMS selected a broader set of related symbols rather than the exact ground-truth ones — still sufficient to make the correct edit.

### Live Per-Task Example (10 of 17 tasks)

| Task | Domain | Subsystem tokens | TMS tokens | Saving | Recall@5 | MRR |
| :--- | :--- | ---: | ---: | ---: | ---: | ---: |
| DB-01 | Storage & WAL | 5,748 | 3,089 | 46.3% | 0.67 | 1.00 |
| EDIT-02 | AST Editing | 2,814 | 2,384 | 15.3% | 1.00 | 1.00 |
| CB-03 | Cross Boundary | 4,959 | 3,028 | 38.9% | 0.67 | 1.00 |
| PARSE-04 | AST Parsing | 15,776 | 3,030 | **80.8%** | 1.00 | 1.00 |
| BUDGET-09 | Token Budgeting | 34,206 | 3,125 | **90.9%** | 0.67 | 1.00 |
| MCP-11 | Gateway & MCP | 7,991 | 2,959 | 63.0% | 0.67 | 1.00 |
| SEMANTIC-15 | Semantic & RRF | 7,295 | 3,030 | 58.5% | 0.33 | 0.50 |
| RUST-16 | Rust & Cargo | 3,877 | 3,019 | 22.1% | 0.67 | 1.00 |
| DART-17 | Flutter & Dart | 5,845 | 3,123 | 46.6% | 0.33 | 1.00 |
| DOCINGEST-13 | Doc Ingestion | 2,799 | 2,433 | 13.1% | 1.00 | 1.00 |

> **Why some tasks show 0% saving:** 6 tasks have subsystems smaller than the 2,500 token budget floor (e.g., Validation = 546 tokens). TMS still returns correct context for them (MRR 0.5 to 1.0); there is simply nothing to compress when the source is already smaller than the budget. At a 600 token budget these also show savings.

### Latency

| Metric | Value |
| :--- | :--- |
| Average cold latency (cache empty) | 755 ms |
| Fastest cold resolution | 237 ms |
| Cached latency (Tier-1 memory hit) | ~0.016 ms |
| Cache speedup factor | ~47,000x |
| Average compression ratio vs subsystem | 2.11x |

You can reproduce these numbers on your own repo:

```bash
python scripts/benchmark_external_repo.py --repo-root /path/to/your/project
```

---

## Development & Testing

```bash
# Run all unit and integration tests (111 tests)
pytest

# Run specific subsystem tests
pytest tests/test_knapsack_assembly.py tests/test_pathway_engine.py
```

---

## Contributing

Contributions are welcome. This project is open to forks, bug reports, feature requests, and pull requests.

Please read [CONTRIBUTING.md](./CONTRIBUTING.md) for contribution guidelines and the [SECURITY.md](./SECURITY.md) for responsible disclosure.

---

## License

Apache License 2.0. See [LICENSE](LICENSE) for details.