Skip to main content

Lightweight code indexing for AI assistants — save 90%+ tokens with structured context

Project description

CortexCode

Lightweight code indexing for AI assistants
Save 90%+ tokens by giving AI agents structured context instead of raw source files.

PyPI Python License Stars VS Code


The Problem

AI coding assistants (Copilot, Cursor, Windsurf, etc.) need to understand your codebase. The current approach: dump entire source files into the context window. This is:

  • Expensive — A 150-file project can cost 200K+ tokens per query
  • Slow — More tokens = slower responses
  • Wasteful — Most of those tokens are irrelevant to the question

The Solution

CortexCode indexes your codebase using AST parsing (tree-sitter) and provides a structured, searchable index. Instead of feeding 200K tokens of raw code, you feed ~500 tokens of relevant context.

┌─────────────────────────────────────────────────┐
│  Without CortexCode          With CortexCode    │
│                                                  │
│  200,000 tokens    →         500 tokens          │
│  $0.006/query      →         $0.00002/query      │
│  All files dumped  →         Only relevant syms  │
│  No structure      →         Call graph + types   │
└─────────────────────────────────────────────────┘

Run cortexcode stats on your project to see your actual savings.

Quick Start

# Install from PyPI
pip install cortexcode

# Or install from source
git clone https://github.com/cortexcode/cortexcode.git
cd cortexcode && pip install -e .

# Index your project
cd your-project
cortexcode index

# See token savings
cortexcode stats

# Get context for AI
cortexcode context "handleAuth"

# Generate interactive docs
cortexcode docs --open

Features

Multi-Language AST Indexing

Parses source code into structured symbols using tree-sitter grammars.

Language Extensions Frameworks Detected
Python .py FastAPI, Django
JavaScript .js, .jsx React, Express, Angular
TypeScript .ts, .tsx Next.js, NestJS, Angular
Go .go
Rust .rs
Java .java Spring Boot
C# .cs ASP.NET

What Gets Indexed

  • Symbols — Functions, classes, methods with parameters and return types
  • Call Graph — Which functions call which (and who calls them)
  • Imports/Exports — Module dependencies
  • API Routes — Express, FastAPI, NestJS, Spring Boot endpoints
  • Entities — Database models and ORM definitions
  • Framework Detection — React components, Angular services, etc.

Token Savings

CortexCode dramatically reduces the tokens needed to give AI assistants useful context:

$ cortexcode stats

╭──────── Token Savings Analysis ────────╮
│ Source files         154 files          │
│ Raw project tokens   203,847            │
│ Full index tokens    45,291             │
│ Context query tokens 487                │
│                                         │
│ Tokens saved         203,360            │
│ Savings              99.8%              │
│ Compression ratio    418.6x             │
╰─────────────────────────────────────────╯

Interactive HTML Documentation

Generate a full interactive documentation site with:

  • File tree browser
  • Symbol list with filtering
  • D3.js call graph visualization (draggable nodes)
  • Global search across all symbols
  • Import/Export browser
  • API route listing
  • Framework detection summary
cortexcode docs --open

Incremental Indexing

Only re-index files that changed since last run:

cortexcode index -i    # Skip unchanged files

VS Code Extension

Install from: VS Code Marketplace

The bundled VS Code extension provides:

  • Hover tooltips — Hover any symbol to see type, params, callers
  • Go to definition — Ctrl+Click using indexed data
  • Context panel — View symbol details in a side panel
  • Status bar — Shows indexed symbol count
cd cortexcode-vscode
npm install && npm run compile
# Press F5 to launch in VS Code

Commands

Command Description
cortexcode index [path] Index a directory
cortexcode index -i Incremental index (changed files only)
cortexcode context [query] Get relevant context for AI
cortexcode context [query] --tokens Show token savings for query
cortexcode search [query] Grep-like symbol search with type/file filters
cortexcode find [query] Semantic search by meaning ("auth handler")
cortexcode diff Show changed symbols since last commit
cortexcode diff --ref HEAD~3 Compare against any git ref
cortexcode stats Show project stats and token savings
cortexcode scan Scan dependencies for security warnings
cortexcode docs --open Generate and open interactive docs
cortexcode dead-code Detect potentially unused symbols
cortexcode complexity Analyze code complexity (cyclomatic, nesting, line count)
cortexcode complexity --min-score 50 Show only high-complexity functions
cortexcode impact <symbol> Change impact analysis — what breaks if you modify a symbol
cortexcode dashboard Launch live dashboard with auto-refresh on index changes
cortexcode workspace init Initialize a multi-repo workspace
cortexcode workspace add <path> Add a repo to the workspace
cortexcode workspace list List repos in workspace
cortexcode workspace index Index all workspace repos
cortexcode workspace search <q> Search symbols across all repos
cortexcode watch Auto-reindex on file changes
cortexcode mcp Start MCP server for AI agent integration
cortexcode lsp Start Language Server Protocol server

How AI Agents Use This

1. Context Command (simplest)

# Paste this output into your AI chat
cortexcode context "useAuth" --tokens

2. JSON Index (programmatic)

import json

index = json.load(open('.cortexcode/index.json'))

# Get all functions
for path, data in index['files'].items():
    for sym in data['symbols']:
        print(f"{sym['type']}: {sym['name']} in {path}:{sym['line']}")

# Trace call graph
for caller, callees in index['call_graph'].items():
    for callee in callees:
        print(f"{caller} -> {callee}")

3. MCP Server

AI agents can query the index directly via the Model Context Protocol:

# Start the MCP server (stdin/stdout)
cortexcode mcp

Configuration Examples:

// Claude Desktop (claude_desktop_config.json)
{
  "mcpServers": {
    "cortexcode": {
      "command": "cortexcode",
      "args": ["mcp"]
    }
  }
}

// Cursor / Windsurf
{
  "mcpServers": {
    "cortexcode": {
      "command": "cortexcode",
      "args": ["mcp"]
    }
  }
}

// Open WebUI / AnythingLLM
{
  "mcpServers": {
    "cortexcode": {
      "command": "cortexcode",
      "args": ["mcp"]
    }
  }
}

Available MCP tools:

  • cortexcode_search — Search symbols by name
  • cortexcode_context — Get rich context with callers/callees
  • cortexcode_file_symbols — List all symbols in a file
  • cortexcode_call_graph — Trace call graph for a symbol
  • cortexcode_diff — Get changed symbols since last commit
  • cortexcode_stats — Get project statistics
  • cortexcode_deadcode — Find potentially unused symbols
  • cortexcode_complexity — Find most complex functions
  • cortexcode_impact — Analyze change impact of a symbol
  • cortexcode_file_deps — Get file dependency graph

4. LSP Server

Any LSP-compatible editor can use CortexCode for hover, go-to-definition, and document symbols:

cortexcode lsp

5. Git Diff Context

See only what changed — perfect for code review:

# What symbols changed since last commit?
cortexcode diff

# Compare against a branch
cortexcode diff --ref main

6. Copilot Chat (@cortexcode)

In VS Code with the CortexCode extension, use @cortexcode in Copilot Chat:

@cortexcode search handleAuth
@cortexcode /context authentication
@cortexcode /impact createUser
@cortexcode /deadcode
@cortexcode /complexity

Commands:

  • /search — Find symbols by name
  • /context — Get ranked context for a query (relevance + call graph connectivity)
  • /impact — Change impact analysis (direct/indirect callers, affected files/tests)
  • /deadcode — List potentially unused symbols
  • /complexity — Show most complex functions by params + outgoing calls

7. Semantic Search

Find symbols by meaning, not just name:

cortexcode find "authentication handler"
cortexcode find "database models"
cortexcode find "user login flow"

8. Code Analysis

# Find unused symbols
cortexcode dead-code

# Show top 10 most complex functions
cortexcode complexity --top 10

# What breaks if I change createUser?
cortexcode impact createUser

Index Format

The index is stored at .cortexcode/index.json:

{
  "project_root": "/path/to/project",
  "last_indexed": "2024-03-01T12:00:00",
  "languages": ["javascript", "typescript", "python"],
  "files": {
    "src/auth.ts": {
      "symbols": [
        {
          "name": "AuthService",
          "type": "class",
          "line": 10,
          "params": [],
          "calls": ["validateToken", "hashPassword"]
        }
      ],
      "imports": [{ "module": "bcrypt", "imported": ["hash", "compare"] }],
      "exports": [{ "name": "AuthService", "type": "class" }],
      "api_routes": [{ "method": "POST", "path": "/auth/login" }]
    }
  },
  "call_graph": {
    "AuthService": ["validateToken", "hashPassword"],
    "validateToken": ["jwt.verify"]
  }
}

Configuration

CortexCode respects .gitignore files (including nested ones) and has built-in ignore patterns for:

  • node_modules/, __pycache__/, .git/
  • Build directories (dist/, build/, .next/)
  • IDE files (.idea/, .vscode/)
  • Package manager files (vendor/, .venv/)

Roadmap

  • MCP server for direct AI agent integration
  • Tiktoken-based accurate token counting
  • Semantic search over symbols (TF-IDF + synonym expansion)
  • Cross-file type inference
  • Git diff-aware context (show only changed symbols)
  • Language server protocol (LSP) support
  • Dependency vulnerability scanning
  • CI/CD integration (GitHub Action)
  • Multi-repo workspace support
  • Custom plugin system for framework-specific extractors
  • Web dashboard for index visualization
  • Flutter/Dart language support (regex-based)
  • React Native / Expo framework detection
  • Native Android (Kotlin/Java) framework detection
  • Native iOS (Swift/SwiftUI/UIKit) framework detection
  • Django / Flask framework detection
  • VS Code Marketplace publishing

Contributing

See CONTRIBUTING.md for guidelines.

# Development install
pip install -e ".[dev]"

# Run tests
pytest

# Lint
ruff check cortexcode/

License

MIT — See LICENSE

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cortexcode-0.2.2.tar.gz (70.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cortexcode-0.2.2-py3-none-any.whl (70.6 kB view details)

Uploaded Python 3

File details

Details for the file cortexcode-0.2.2.tar.gz.

File metadata

  • Download URL: cortexcode-0.2.2.tar.gz
  • Upload date:
  • Size: 70.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for cortexcode-0.2.2.tar.gz
Algorithm Hash digest
SHA256 71112032a4f73e277642315059c5a5fb8b4449cf680a07848806b862f219b919
MD5 232b5f28dc9abc076734dea2c9813c61
BLAKE2b-256 52ec0717b96e76dae79366e3da84c4db3f02995f22beace52945786da0014657

See more details on using hashes here.

File details

Details for the file cortexcode-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: cortexcode-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 70.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for cortexcode-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 3c23fce851789a2ad19fb0f330c5cf11a7ec4c47cfe3a855980d603d1e037f0a
MD5 8ff40574c89fb08755200f75d69a811b
BLAKE2b-256 ec187c1dacd6f0269245add407ea18bc2ee94106db9622232c0a974412d14d8e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page