Skip to main content

Getting Started

This guide walks you through installing ctx and using it to generate context for LLMs and build a searchable code intelligence index.

Installation​

The crate is published as agentis-ctx, but it installs a binary named ctx:

# From crates.io (installs the `ctx` binary)
cargo install agentis-ctx
cargo binstall agentis-ctx
brew install agentis-tools/tap/ctx
yay -S ctx-bin

On Windows with Scoop:

scoop bucket add agentis-tools https://github.com/agentis-tools/scoop-bucket
scoop install ctx

Debian and RPM packages are attached to GitHub Releases:

sudo apt install ./ctx_VERSION_amd64.deb
sudo dnf install ./ctx-VERSION-1.x86_64.rpm

The Homebrew tap, AUR package, and Scoop bucket live in separate package-index repositories. Prebuilt releases currently support Linux GNU x86-64, macOS Intel and Apple Silicon, and Windows x86-64. Linux ARM64 and musl are not currently published.

Only direct GitHub binary installations should use ctx self-update. Cargo, Homebrew, Arch, Scoop, Debian, and RPM installations must be upgraded through their package manager.

From a local checkout​

cargo install --path .

On Windows without the MSVC C++ build tools, disable the default DuckDB analytics feature (call graphs, impact analysis, and complexity then return empty results):

cargo install agentis-ctx --no-default-features

From Source​

git clone https://github.com/agentis-tools/ctx
cd ctx
cargo build --release

# Add to your PATH (choose one):
cp target/release/ctx /usr/local/bin/
# or
export PATH="$PATH:$(pwd)/target/release"

To build with the MCP server (ctx serve --mcp) enabled:

cargo build --release --features mcp

Verify Installation​

ctx --version
# ctx 0.4.0

Part 1: Context Generation​

The primary use case for ctx is generating formatted context for LLMs.

Your First Context​

Navigate to any project and generate context:

cd my-project
ctx

This outputs all source files in XML format (the default), ready to paste into an LLM.

Copy to Clipboard​

macOS:

ctx src/ | pbcopy

Linux:

ctx src/ | xclip -selection clipboard

WSL:

ctx src/ | clip.exe

Select Specific Files​

# Just Rust files
ctx "**/*.rs"

# Multiple patterns
ctx "src/**/*.ts" "lib/**/*.ts"

# Specific directories
ctx src/ lib/ tests/

# Mix of patterns and paths
ctx src/ "tests/**/*.test.ts" package.json

Choose Output Format​

# XML (default) - best for most LLMs
ctx src/

# Markdown - good for chat interfaces
ctx --format markdown src/
ctx --format md src/       # alias

# Plain text - minimal formatting
ctx --format plain src/

# JSON - structured output for tooling
ctx --format json src/

View Statistics​

ctx --stats src/
# Generated context: 42 files, 156.3 KB, ~38,900 tokens in 23ms

--stats reports the file count, total size, elapsed time, and a token estimate.

Count Tokens and Budget Context​

New in the 0.2.x line, ctx can count tokens and fit context to a budget:

# Count tokens only, without printing file contents
ctx --count-only src/

# Omit whole files to stay within a token budget
# (files are dropped as a unit; they are never truncated)
ctx --max-tokens 8000 src/

# Choose the tokenizer encoding (default: cl100k_base)
ctx --encoding o200k_base --count-only src/

Available encodings are cl100k_base (default), o200k_base, and p50k_base.

Part 2: Code Intelligence​

ctx includes a powerful code intelligence system for understanding your codebase.

Build the Index​

ctx index

:::tip Run this first — everything below needs it ctx index is the prerequisite for every intelligence and governance command (query, search, map, check, score, …). Run it once; re-runs are incremental. Keep it live in the background with ctx index --watch (and ctx embed --watch for semantic search). See Index & embed first for the full workflow. :::

This creates .ctx/codebase.sqlite containing:

  • Symbols - Functions, classes, interfaces, structs, enums, traits
  • Edges - Call relationships, imports, extends, implements
  • Files - Metadata and compressed source code
  • FTS Index - Full-text search across symbol names and documentation

Example output:

Indexing codebase...
Indexed 20 files (46 skipped, 0 failed)
Extracted 548 symbols, 2664 edges in 890ms

Codebase statistics:
  Files:     20
  Symbols:   548
  Functions: 446
  Structs:   35
  Enums:     11
  Traits:    3
  Edges:     2664

The indexer parses in parallel across CPU cores by default; pass --serial for single-threaded parsing. It also accepts include patterns (-p/--pattern) and ignore patterns (-i/--ignore):

# Only index TypeScript sources
ctx index -p "src/**/*.ts"

Search Your Code​

Keyword search:

ctx search "handleRequest"
ctx search "auth"
ctx search "parse config"

Semantic search (requires embeddings):

# Generate embeddings first (one-time, uses local model ~90MB)
ctx embed

# Then search with natural language
ctx semantic "error handling and recovery"
ctx semantic "functions that validate user input"
ctx semantic "database connection management"

Explore Relationships​

Who calls this function?

ctx query callers processPayment

Output:

Functions that call 'processPayment':
------------------------------------------------------------
  handleOrder (src/orders/handler.ts:45)
    > await processPayment(order.total)
  retryTransaction (src/payments/retry.ts:23)
    > return processPayment(amount)

What does this function call?

ctx query deps validateInput

Output:

Dependencies of 'validateInput':
------------------------------------------------------------
  calls checkRequired (line 12)
  calls sanitize (line 15)
  calls validateSchema (line 18)

What would break if I change this?

ctx query impact authenticate

Output:

Impact analysis for 'authenticate' (depth=5):
The following would be affected by changes:
----------------------------------------------------------------------

Distance 1:
  handleLogin (src/auth/login.ts) [function]
  protectedRoute (src/middleware/auth.ts) [function]

Distance 2:
  UserController (src/controllers/user.ts) [class]
  AdminController (src/controllers/admin.ts) [class]

Total: 4 symbols affected

Visualize Call Graphs​

# Text format (default)
ctx query graph main --depth 3

# GraphViz DOT format (for visualization)
ctx query graph main --depth 3 --output dot > graph.dot
dot -Tpng graph.dot -o graph.png

# JSON format (for programmatic use)
ctx query graph main --depth 3 --output json

ctx query graph accepts --output <text|json|dot> and defaults to a depth of 5.

Get Detailed Symbol Information​

ctx explain handleAuth

Output:

Symbol: handleAuth
============================================================
Kind:       function
File:       src/auth/handler.ts:45
Visibility: public

Signature:
  async function handleAuth(req: Request): Promise<Response>

Description:
  Handles authentication requests and returns JWT tokens.

Called by (3):
  loginRoute (src/routes/auth.ts:12)
  refreshRoute (src/routes/auth.ts:34)
  apiMiddleware (src/middleware/api.ts:8)

Calls (5):
  validateCredentials [function]
  generateToken [function]
  hashPassword [function]
  ...

Retrieve Source Code​

ctx source handleAuth

Output:

// Source: src/auth/handler.ts::handleAuth::45
async function handleAuth(req: Request): Promise<Response> {
  const { username, password } = req.body;
  
  const user = await validateCredentials(username, password);
  if (!user) {
    return new Response("Unauthorized", { status: 401 });
  }
  
  const token = generateToken(user);
  return Response.json({ token });
}

Part 3: Code Analysis​

ctx includes tools for analyzing code quality.

Complexity Analysis​

Find functions that call too many other functions (high fan-out):

ctx complexity --warnings-only

Output:

Code Complexity Analysis (threshold: 10)
==========================================================================================
FUNCTION                             FAN-OUT   FAN-IN    SCORE SEVERITY   FILE
------------------------------------------------------------------------------------------
extract_symbols                           48        4      100 HIGH     src/parser/typescript.rs:310
discover_files                            46        2       94 HIGH     src/walker.rs:67
------------------------------------------------------------------------------------------
Total: 94 functions analyzed
  0 critical, 2 high complexity functions need attention

Duplicate Detection​

Find copy-pasted code, even when variables were renamed or literals changed (functions are compared structurally with MinHash fingerprints built during ctx index):

ctx duplicates

Output:

Near-duplicate functions (Jaccard similarity of 5-token shingles >= 0.85, >= 50 tokens)
====================================================================================================

1. similarity 0.938
   src/parser/python.rs:318 extract_edges (74 tokens)
   src/parser/typescript.rs:430 extract_edges (76 tokens)
----------------------------------------------------------------------------------------------------
Found 1 near-duplicate pair(s).

Tune it with --threshold <0.0-1.0> (Jaccard similarity, default 0.85) and --min-tokens <N> (default 50, raise it to filter idiomatic boilerplate). Use --against main to only check functions in changed files, and --fail-on-found to exit 1 in CI when a pair is reported.

Dependency Graph​

Visualize how files depend on each other:

# DOT format (GraphViz)
ctx graph --by-file > deps.dot
dot -Tpng deps.dot -o deps.png

# Mermaid format (for markdown)
ctx graph --by-file --output mermaid

Part 4: Watch Mode​

Keep the index fresh during development:

Terminal 1 - Watch for file changes:

ctx index --watch

Terminal 2 - Auto-embed new symbols:

ctx embed --watch

Now any file changes are automatically indexed and embedded.

Filtered Watch Mode​

Watch only specific files or exclude patterns:

# Only watch TypeScript files in src/
ctx index --watch -p "src/**/*.ts"

# Watch everything except test files
ctx index --watch -i "**/*.test.ts" -i "**/*.spec.ts"

# Combine include and ignore patterns
ctx index --watch -p "src/" -i "src/generated/"

Watch mode respects all the same filtering as initial indexing, including .gitignore, .contextignore, and built-in ignores.

Part 5: Project Configuration​

Create .contextignore​

Create a .contextignore file for project-specific exclusions:

# Test fixtures
fixtures/
__snapshots__/

# Generated code
*.generated.ts
dist/

# Large data files
*.sql
*.csv

What's Automatically Ignored​

ctx automatically excludes:

  • Everything in .gitignore
  • 170+ built-in patterns (binaries, node_modules, build outputs, etc.)
  • Files matching .contextignore

Custom Ignores on Command Line​

ctx -i "*.test.ts" -i "fixtures/" src/

Part 6: Smart Context Selection​

Let ctx intelligently select files based on your task:

# Describe what you're working on
ctx smart "add user authentication" --max-tokens 8000

# Preview what would be selected
ctx smart "fix login bug" --dry-run

# See why each file was selected
ctx smart "refactor parser" --explain

Smart selection requires an index (ctx index) and embeddings (ctx embed).

Part 7: Diff-Aware Context​

Generate context focused on code changes:

# Changes since the previous commit (default revision: HEAD~1)
ctx diff

# Changes vs main branch
ctx diff main

# Only staged changes
ctx diff --staged

# Include change summary
ctx diff --summary

Part 8: PR Review Context​

Generate context for GitHub pull request review:

# Review PR #123
ctx review 123

# Include PR comments
ctx review 123 --include-comments

# With change summary
ctx review 123 --summary

Note: Requires GitHub CLI (gh) to be installed and authenticated.

Part 9: Code Quality Audit​

Run automated quality analysis:

# Full quality report
ctx audit

# Quality gate for CI
ctx audit --min-score 7.0

# JSON output for automation
ctx audit --output json

Part 10: Interactive Shell​

Explore your codebase interactively:

ctx shell

Shell commands:

  • find <pattern> - Find symbols
  • search <query> - Hybrid search
  • callers <fn> - Show callers
  • callees <fn> - Show callees
  • source <symbol> - Show source
  • explain <symbol> - Explain symbol
  • impact <symbol> - Impact analysis
  • stats - Codebase statistics
  • help - Show all commands

Part 11: MCP Server (Claude Desktop)​

Integrate ctx with Claude Desktop. The MCP server is only available when ctx is built with the mcp feature:

# Build with MCP support
cargo build --release --features mcp

# Run MCP server
ctx serve --mcp

Configure Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "ctx": {
      "command": "ctx",
      "args": ["serve", "--mcp"],
      "cwd": "/path/to/project"
    }
  }
}

Common Workflows​

Workflow 1: Quick LLM Context​

# Generate context for current bug/feature
ctx "src/auth/**/*.ts" | pbcopy

# Paste into ChatGPT, Claude, etc.

Workflow 2: Understanding New Codebase​

# Index the codebase
ctx index

# Get an overview
ctx query stats

# Find entry points
ctx search "main"
ctx search "app"

# Trace the call flow
ctx query graph main --depth 4

Workflow 3: Safe Refactoring​

# Before changing a function, check impact
ctx query impact authenticate --depth 5

# See who calls it
ctx query callers authenticate

# Make changes, then reindex
ctx index

Workflow 4: Code Review Prep​

# Find complex functions that might need review
ctx complexity --warnings-only

# Find near-duplicate functions (structural match, renames ignored)
ctx duplicates --threshold 0.9

# Understand file dependencies
ctx graph --by-file --output mermaid

Workflow 5: Smart Context for Tasks​

# Let ctx select relevant files for your task
ctx smart "add caching to the database layer" --max-tokens 10000 | pbcopy

# Preview selection first
ctx smart "fix authentication bug" --dry-run --explain

Workflow 6: PR Review​

# Get context for reviewing a PR
ctx review 42 --summary --include-comments

# Focus on just the changed files
ctx review 42 --changes-only

Workflow 7: CI/CD Integration​

# Quality gate in CI pipeline
ctx audit --min-score 7.0 --output json > quality-report.json

# Pre-commit hook
ctx audit --min-score 7.0 || exit 1

Note: ctx audit --incremental (auditing only changed files) is not yet implemented; the audit always analyzes the full indexed codebase.

Next Steps​