tokensave

repository·master·Indexed 19 days ago

https://github.com/aovestdipaperino/tokensave

A semantic code intelligence engine and MCP server that builds a local knowledge graph from codebases in 50+ languages, including Rust, Go, Java, Python, and TypeScript. It reduces token consumption for AI coding agents by replacing manual file exploration with structured semantic queries, impact analysis, and smart context building. Features include multi-branch indexing, cross-session memory tools, and integration with agents such as Claude Code, Cursor, and Zed.

Tokens
87.3K
Snippets
234
Records
385
Agent score
66%

What's inside tokensave

  1. What is tokensave?

    master

    tokensave is a semantic code intelligence tool designed for AI coding agents (like Claude Code, Cursor, or Copilot). It provides a pre-indexed semantic knowledge graph of your codebase, allowing agents to query symbols, relationships, and source code directly via an MCP (Model Context Protocol) server.

    Instead of agents wasting tokens on repetitive grep, glob, and file read operations to explore a codebase, they can use tokensave to perform instant, structured lookups. This reduces token usage, minimizes tool calls, and keeps all processing 100% local using a libSQL graph database.

  2. Compare tokensave with alternative code intelligence tools

    master

    If you are deciding between tokensave and other tools like Dual-Graph, CodeGraph, or code-review-graph, consider these key differentiators:

    tokensave Advantages

    • Symbol-level Intelligence: Unlike file-level rankers (e.g., Dual-Graph), tokensave understands functions, structs, fields, call edges, and type hierarchies.
    • Extensive Toolset: Provides 70+ specialized MCP tools covering code quality (complexity, coupling, dead code), workflow (commit/PR context, test mapping), and refactoring (rename preview).
    • High Performance & Low Footprint: A single ~25 MB Rust binary with zero runtime dependencies. It uses libSQL with FTS5 for fast, indexed queries instead of full JSON scans.
    • Broad Language Support: Supports 50+ languages, including deep extraction for Nix, Protobuf, COBOL, and Fortran.
    • Agent Compatibility: Integrates with 12+ agents including Claude Code, Cursor, Copilot, Cline, Roo Code, and Zed.
    • Token Tracking: Every MCP tool response includes tokensave_metrics: before=N after=M to track exact token savings per call.
    • Multi-Branch Awareness: Supports optional per-branch indexing with cross-branch diff and search capabilities.

    Comparison Summary

    FeaturetokensaveDual-GraphCodeGraphcode-review-graph
    ApproachQueryable graphContext prefillCode graph + exploreCode graph + review
    MCP Tools70+5922
    Languages50+1119+19+
    ImplementationRust (single binary)Python + Node.jsNode.jsPython
    Runtime DepsNonePython & Node.jsNode.jsPython
  3. Understand the feature differences between Token Savior and tokensave

    master

    This document provides a comparative analysis between Token Savior (a Python-based project with 105 tools) and tokensave (a Rust-based project with 38 tools). While both projects aim to reduce token consumption via structural code navigation through MCP, Token Savior includes advanced features built around the code graph that are currently absent or less mature in tokensave.

    Key functional areas where Token Savior leads include:

    • Persistent Memory: Storing observations (decisions, bugfixes, etc.) in SQLite.
    • Context Optimization: Using knapsack optimization to fit symbols into a token budget.
    • Advanced Analysis: Program slicing, breaking change detection, and edit verification.
    • Predictive Navigation: Markov prefetching and Co-Activation Tensors (TCA) to predict next tool calls or related symbols.
  4. Overview of TokenSave MCP tools

    master

    TokenSave provides 37 MCP (Model Context Protocol) tools categorized into four functional waves to assist AI agents in codebase navigation, structural analysis, quality auditing, and workflow integration:

    1. Navigation: Tools for searching, context retrieval, finding callers/callees, and identifying affected files (tokensave_search, tokensave_context, tokensave_callers, tokensave_callees, tokensave_node, tokensave_files, tokensave_affected).
    2. Structure: Tools for detecting dead code, circular dependencies, module APIs, unused imports, and semantic changelogs (tokensave_dead_code, tokensave_circular, tokensave_module_api, tokensave_unused_imports, tokensave_changelog).
    3. Quality: Tools for computing cyclomatic complexity, detecting recursion, finding 'god classes', checking documentation coverage, and porting status (tokensave_complexity, tokensave_recursion, tokensave_god_class, tokensave_doc_coverage, tokensave_port_status, tokensave_port_order).
    4. Workflow & Branches: Tools for generating commit/PR context, mapping tests to source, and branch-aware searching/diffing (tokensave_commit_context, tokensave_pr_context, tokensave_test_map, tokensave_simplify_scan, tokensave_type_hierarchy, tokensave_branch_search, tokensave_branch_diff, tokensave_branch_list).
  5. How Multi-Branch Support works in tokensave

    master

    tokensave uses a Branch-Scoped DB with Copy-on-Switch model to ensure data isolation and correctness when switching git branches. Instead of a single shared database that accumulates 'ghost nodes' from deleted files, tokensave maintains separate SQLite databases for different branches.

    Database Structure

    • Main/Master Branch: Always uses the canonical database at .tokensave/tokensave.db.
    • Other Branches: Each non-default branch gets its own database file located in .tokensave/branches/<branch_name>.db.

    The Sync and Switch Flow

    1. Detection: During a sync or an MCP tool call, tokensave compares the current git branch (via git rev-parse --abbrev-ref HEAD) against the current_branch stored in its internal metadata.
    2. Branch Switch: If a change is detected:
      • If the target branch database does not exist, tokensave seeds it by copying the currently active database to the new branch path.
      • tokensave then reopens the connection to the new branch-specific database.
    3. Incremental Sync: Once the correct database is active, tokensave performs a standard incremental sync, re-indexing only the files that have changed relative to that specific branch's state.

    Advantages

    • Isolation: Each branch's graph is accurate and free from stale data from other branches.
    • Cross-Branch Comparison: Allows tools to open two different database handles simultaneously to perform impact analysis or diffing.
    • Efficiency: Branching from an existing branch (e.g., feature-a $\rightarrow$ feature-b) uses the active DB as a seed, minimizing the work required for the next incremental sync.
  6. How Multiproject Mode works

    master

    In Multiproject mode, tokensave treats direct subdirectories of the root as distinct projects. This allows a single .tokensave database to scope data to specific sub-projects within a larger workspace.

    Example Directory Structure:

    Code/              <- root, initialized with `tokensave init --multiproject` here
      shared.rs        <- project: [root]
      App1/
        src/main.rs    <- project: App1
      App2/
        src/lib.rs     <- project: App2

    This structure allows you to filter queries by project name, enabling you to isolate analysis to a specific application within a monorepo.

    Code/              <- root, init --multiproject here
      shared.rs        <- project: [root]
      App1/
        src/main.rs    <- project: App1
      App2/
        src/lib.rs     <- project: App2
  7. How companion Markdown documentation works

    master

    Tokensave supports two ways to index prose explanations alongside code so agents can read summaries instead of large files:

    1. Sidecar Files: A Markdown file named Filename.ext.readme.md placed next to Filename.ext. No configuration required.
    2. Docs Directory: A central directory (default tokensave-docs/) where Markdown files use YAML front matter to declare which files they cover via applies_to globs.

    Example Docs Directory entry:

    ---
    applies_to:
      - "**/*.es8.cs"
      - "src/legacy/**/*.cs"
    ---
    These files target the ES8 runtime; prefer the ES7 variants for new work.

    Retrieving Docs:

    • Use the tokensave_doc tool to get the doc path, content, covered files, and a doc_stale signal (true if the code was updated after the doc).
    • tokensave_entities reports has_doc and doc_path so agents can detect documentation availability before reading.
    ---
    applies_to:
      - "**/*.es8.cs"
      - "src/legacy/**/*.cs"
    ---
    
    These files target the ES8 runtime; prefer the ES7 variants for new work.
  8. Identify non-thread-safe tokensave tools

    master

    While most tokensave tools are read-only and safe to call in parallel, the following categories of tools mutate state and should not be parallelized:

    • Edit tools (modify source files):
      • tokensave_str_replace
      • tokensave_multi_str_replace
      • tokensave_insert_at
      • tokensave_insert_at_symbol
      • tokensave_replace_symbol
      • tokensave_ast_grep_rewrite
    • Session and memory tools (write to .tokensave/):
      • tokensave_session_start
      • tokensave_session_end
      • tokensave_record_decision
      • tokensave_record_code_area
    • Test tools (runs a cargo test subprocess):
      • tokensave_run_affected_tests
  9. Manage plugin security and loading

    master

    Plugins run in-process with full trust and no sandboxing. You can control plugin behavior via configuration:

    • Disable all plugins: Set plugins.enabled = false in your config (useful for CI/CD).
    • Allowlist plugins: Use plugins.allow = ["tokensave-elixir"] to restrict loading to specific plugins.
    • Override built-ins: Plugins that declare an extension already claimed by a built-in extractor take precedence (opt-in override) unless disabled in config.
  10. Compare tokensave with Dual-Graph

    master

    If you are deciding between tokensave and Dual-Graph (formerly Codex-CLI-Compact), consider these key architectural differences:

    • Approach: tokensave is a queryable code intelligence engine where the AI actively drives exploration using 70+ specialized MCP tools. Dual-Graph is a context prefill layer that passively injects ranked files into prompts.
    • Granularity: tokensave operates at the symbol level (functions, structs, fields, etc.) with full inter-procedural call graphs and type hierarchies. Dual-Graph operates primarily at the file level.
    • Storage: tokensave uses libSQL (SQLite) for O(1) lookups, full-text search (FTS5), and concurrent reads. Dual-Graph uses JSON files, which require full scans for lookups.
    • Language Support: tokensave supports 50+ languages (including Nix, Protobuf, COBOL, and Fortran) with a tiered extraction system. Dual-Graph supports 11 languages.
    • Licensing: tokensave is MIT-licensed Rust (fully open source and auditable). Dual-Graph uses a proprietary Python core (graperoot).
    • Integration: tokensave supports a wider range of agents (12+), including deep integration with Claude Code via PreToolUse hooks.
  11. Use vector embeddings for semantic search

    master

    CodeGraph supports semantic search through vector embeddings and cosine similarity.

    Key Components:

    • TextEmbedder: A wrapper around the ort crate for ONNX inference. It uses the nomic-embed-text-v1.5 model. Note that it requires adding search_query: or search_document: prefixes to text per the model's requirements.
    • store_vector(db, node_id, embedding, model): Stores an embedding as a BLOB in the database associated with a specific node_id.
    • get_vector(db, node_id): Retrieves and decodes the stored embedding.
    • brute_force_search(db, query, limit): Performs a similarity search by loading all vectors and computing cosine similarity against the query vector, returning the top-k results.
    • create_node_text(node): Generates a searchable text representation of a code node (including name, kind, and docstrings) to be embedded.
  12. Improve search results with agent-driven keyword expansion

    master

    Tokensave uses FTS5 with BM25 scoring rather than embedding models. While FTS5 is highly efficient, it relies on literal matches in names, signatures, or docstrings. To bridge the gap between conceptual queries (e.g., "authentication") and specific code (e.g., login()), agents should provide a keywords array to the tokensave_context MCP tool.

    Each keyword acts as an independent FTS5 query, and the results are merged and deduplicated by node ID. This approach avoids the high indexing cost, model dependencies, and latency associated with local embeddings.