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

Windsurf / Cursor Configuration

To make AI agents in Windsurf or Cursor automatically use CortexCode:

Option 1: Auto-detect prompt file

Create .cortexcode/prompt.md in your project root. AI agents will automatically read this file and use the CortexCode index for code understanding.

Option 2: Add to agent rules

Add to your project's .windsurf/rules.md or Cursor rules:

Always use CortexCode index (.cortexcode/index.json) to understand the codebase before making changes. Use:
- cortexcode search <symbol> to find symbols
- cortexcode impact <symbol> to see what uses a function
- cortexcode context <query> to get relevant code context

Run 'cortexcode index' first if the index doesn't exist.

Option 3: Configure MCP in Windsurf

Add to ~/.windsurf/config.json:

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

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 (17 tools):

Search & Navigation:

  • cortexcode_search — Search symbols by name
  • cortexcode_fuzzy_search — Fuzzy/approximate search (handles typos)
  • cortexcode_regex_search — Regex pattern search (e.g. ^get.*)
  • 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

Analysis:

  • cortexcode_deadcode — Find potentially unused symbols
  • cortexcode_complexity — Find most complex functions
  • cortexcode_impact — Analyze change impact of a symbol
  • cortexcode_duplicates — Detect duplicate/copy-paste code
  • cortexcode_circular_deps — Find circular dependencies

Security & Quality:

  • cortexcode_security_scan — Scan for hardcoded secrets, SQL injection, XSS
  • cortexcode_endpoints — Extract API endpoints (Express, Flask, Django, Next.js, etc.)
  • cortexcode_api_docs — Auto-generate API docs from signatures

Project Info:

  • cortexcode_stats — Get project statistics
  • cortexcode_diff — Get changed symbols since last commit
  • 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

Future Improvements

Features

  • More language support (Ruby, PHP, C++)
  • Cloud index for team sharing
  • Graph visualization for call chains
  • Auto-indexing on git push
  • Index versioning (compare across commits)
  • Config file (.cortexcode.yaml) for project settings

Integrations

  • JetBrains IDEs plugin (IntelliJ, PyCharm)
  • GitHub Copilot native integration
  • Claude Code integration

AI/Search

  • Semantic embeddings for meaning-based search
  • AI-powered code review
  • Bug detection (pattern matching)

Performance

  • Compressed index format
  • Faster search with caching
  • Parallel multi-threaded indexing

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.5.0.tar.gz (80.2 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.5.0-py3-none-any.whl (82.4 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for cortexcode-0.5.0.tar.gz
Algorithm Hash digest
SHA256 76bf41721d2ad907b142dbf9a5039fe25763213b2870d1cc3a3bdc0b410b4618
MD5 34f4f6077a357bc26c87e0aff9721972
BLAKE2b-256 49ee82216c89b9cb5b1b7f9cd8d3ff36682cfc9195d5b71faea926c9662995cd

See more details on using hashes here.

File details

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

File metadata

  • Download URL: cortexcode-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 82.4 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.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7c3605cb9d99e21d7f06c4b552dc3dcc0538077213ce67146cd81e0852c2a39c
MD5 54b6a9df07c3adb9a3d09e7d0f06d422
BLAKE2b-256 40c73633c025e701a6450e048a1e5a47c41185a0e8dacf265d6dd1b0f08f0dcd

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