Skip to main content

Lightweight code indexing for AI assistants — build a searchable codegraph and grounded context

Project description

CortexCode

Lightweight code indexing for AI assistants
Build a searchable codegraph, generate documentation, and give AI assistants grounded context.


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:

  • Noisy — Important signals are buried inside large files
  • Fragile — Assistants miss architecture, relationships, and runtime surface area
  • Hard to reuse — Raw file dumps do not become a durable project map

The Solution

CortexCode indexes your codebase using AST parsing (tree-sitter) and builds a structured, searchable codegraph. You can explore symbols, trace flows, generate docs and diagrams, produce CodeWiki pages, and connect AI tools through MCP.

┌─────────────────────────────────────────────────┐
│  Without CortexCode          With CortexCode    │
│                                                  │
│  Raw files only    →         Searchable codegraph │
│  Manual digging    →         Linked symbols       │
│  Ad-hoc prompts    →         Reusable context     │
│  No project map    →         Docs + diagrams      │
└─────────────────────────────────────────────────┘

Run cortexcode index on your project to generate the codegraph and start exploring.

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

# Get context for AI
cortexcode context "handleAuth"

# Generate interactive docs
cortexcode docs --open

Post-Index Wizard

After running cortexcode index, an interactive wizard can guide you through generating outputs:

cortexcode index              # Run index, then wizard prompts
cortexcode index --force-wizard   # Force wizard in non-TTY mode
cortexcode index --no-post-index-wizard  # Skip wizard

Wizard features:

  • Multi-select checkbox for docs, diagrams, AI docs, CodeWiki, reports, visualization, dashboard, MCP setup
  • Smart recommendations based on detected project shape
  • Follow-up prompts for diagram types, AI doc types, wiki options
  • Preference persistence — saves your choices for future runs

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.

Project Exploration & Context

Use CortexCode to inspect structure and answer practical questions about a codebase:

  • Context lookup — Pull relevant symbols and files for a query
  • Call graph tracing — Follow how behavior moves across modules
  • Architecture visibility — Inspect routes, entities, dependencies, and layers
  • Reusable index — Keep a structured project map that tools can build on

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

CodeWiki — AI-Powered Documentation Site

Generate a multi-page CodeWiki documentation site powered by AI (Gemini, OpenAI, Anthropic, or Ollama):

cortexcode wiki                    # Generate with default AI provider
cortexcode wiki --provider google  # Use Gemini
cortexcode wiki --open             # Generate and open in browser
cortexcode wiki --no-modules       # Skip per-module pages (faster)

Features:

  • AI-generated pages — Overview, Architecture, Code Flows, API Reference, Concepts Guide
  • Per-module docs — Each Python/JS file gets AI-generated documentation
  • Mermaid diagrams — Auto-generated flow diagrams
  • Concept mapping — Maps technical concepts to symbols and files
  • Concept search — Ask "how does authentication work?" and get grounded answers

Output: .cortexcode/wiki/index.html — Open directly or serve locally.

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

CortexCode supports both a short form (cc) and full form (cortexcode). Commands are organized into logical groups.

Core Commands

Command Description
cc index [path] Index a directory
cc index -i Incremental index (changed files only)
cc config Manage CortexCode configuration
cc workspace init Initialize a multi-repo workspace
cc workspace add <path> Add a repo to the workspace
cc workspace list List repos in workspace
cc workspace index Index all workspace repos
cc workspace search <q> Search symbols across all repos

Analyze — Code Exploration & Analysis

Command Description
cc analyze context [query] Get relevant context for AI
cc analyze context [query] --tokens Show context size estimates for a query
cc analyze search [query] Grep-like symbol search with type/file filters
cc analyze find [query] Semantic search by meaning ("auth handler")
cc analyze diff Show changed symbols since last commit
cc analyze diff --ref HEAD~3 Compare against any git ref
cc analyze stats Show project index and analysis stats
cc analyze scan Scan dependencies for security warnings
cc analyze trace <symbol> Trace code flow through call graph
cc analyze flow <concept> Analyze code flow grouped by file
cc analyze dead-code Detect potentially unused symbols
cc analyze complexity Analyze code complexity (cyclomatic, nesting, line count)
cc analyze complexity --min-score 50 Show only high-complexity functions
cc analyze impact <symbol> Change impact analysis — what breaks if you modify a symbol
cc analyze explain <symbol> Explain a symbol using AI

Generate — Documentation & Visualization

Command Description
cc generate docs --open Generate and open interactive docs
cc generate diagrams Generate Mermaid diagrams
cc generate diagrams --viz Interactive D3.js visualization
cc generate report Show interactive project report in terminal
cc generate ai-docs Generate AI-powered documentation
cc generate wiki Generate CodeWiki documentation site with AI

AI — Natural Language Code Understanding

Command Description
cc ai ask "question" Ask a natural language question about the codebase
cc ai explain <symbol> Explain a symbol using AI
cc ai docs Generate AI-powered documentation
cc ai wiki Generate CodeWiki documentation site with AI

Serve — Long-Running Services

Command Description
cc serve watch Auto-reindex on file changes
cc serve dashboard Launch live dashboard with auto-refresh
cc serve lsp Start Language Server Protocol server

Integration & Automation

Command Description
cc mcp start Start MCP server for AI agent integration
cc mcp setup Configure MCP for IDEs (auto-detect)
cc githook install Install git hook for auto-indexing
cc githook precommit Install pre-commit hook for security scanning
cc bundle export Export index as shareable .ccb bundle
cc bundle import <file> Import a .ccb bundle
cc bundle info <file> Show bundle info without importing
cc package index <name> Index an external package (pip, npm)
cc jobs list List background jobs
cc completion install Install shell completion

Shortcuts (Legacy)

These commands still work but show a tip to use the grouped form:

cc trace <symbol>      # Tip: use cc analyze trace
cc wiki                # Tip: use cc ai wiki
cc ask "question"     # Tip: use cc ai ask

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"

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
  • 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
  • Interactive graph visualization (cc generate diagrams --viz)
  • MCP setup wizard (cc mcp setup)
  • Pre-indexed bundles (.ccb files)
  • Package indexing (cc package index)
  • Background job tracking (cc jobs)
  • AI-powered CodeWiki documentation site
  • Natural language code Q&A (cc ai ask)
  • Flow tracing & concept analysis (cc analyze trace, cc analyze flow)
  • Git hook integration (auto-index, pre-commit security scan)
  • Shell completion (bash, zsh, fish, PowerShell)
  • Short CLI alias (cc)
  • Grouped CLI commands (analyze, generate, serve, ai)
  • Config file (.cortexcode.yaml) for project settings
  • Bug detection (pattern matching for security, quality, performance)
  • Project website (Astro + Tailwind, Vercel)
  • Cookbook with practical recipes

Future Improvements

Features

  • More language support (Ruby, PHP, C++)
  • Cloud index for team sharing
  • Index versioning (compare across commits)
  • Codebase chatbot (conversational Q&A over index)

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
  • AI-suggested refactoring

Performance

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

Cookbook

See COOKBOOK.md for practical recipes — from first-time setup to CI/CD integration, team collaboration, and advanced workflows.

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.10.0.tar.gz (180.0 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.10.0-py3-none-any.whl (230.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for cortexcode-0.10.0.tar.gz
Algorithm Hash digest
SHA256 d5822451fa67ede71da99fc2494655c271cec741de4678d40e00e74edbc75f6e
MD5 c8d080cb4979e442af6306fd7af50009
BLAKE2b-256 600899ee66907af451ee0a62211b55de3d7c50adad9c7d8f657a7ddee41e92f7

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for cortexcode-0.10.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b034fe958ea9ac8c215eca9552fab3f6e42bb65f20692d9a65bec079a7ba5792
MD5 2cc341b1971ccd4daa389fb0061babd9
BLAKE2b-256 652ff374f82e881a9401266fdb232781aed2cc4e8ca1a2b74d01ce14f1ea8131

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