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
Using Cargo Install (Recommended)
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
# Or 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-featuresFrom 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 mcpVerify Installation
ctx --version
# ctx 0.3.0Part 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
ctxThis outputs all source files in XML format (the default), ready to paste into an LLM.
Copy to Clipboard
macOS:
ctx src/ | pbcopyLinux:
ctx src/ | xclip -selection clipboardWSL:
ctx src/ | clip.exeSelect 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.jsonChoose 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 indexctx 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: 2664The indexer accepts include patterns (-p/--pattern), ignore patterns
(-i/--ignore), and a flag to enable parallel parsing (-j/--parallel):
# Only index TypeScript sources, with parallel parsing
ctx index -p "src/**/*.ts" --parallelSearch 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 processPaymentOutput:
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 validateInputOutput:
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 authenticateOutput:
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 affectedVisualize 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 jsonctx query graph accepts --output <text|json|dot> and defaults to a depth of 5.
Get Detailed Symbol Information
ctx explain handleAuthOutput:
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 handleAuthOutput:
// 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-onlyOutput:
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 attentionDuplicate 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 duplicatesOutput:
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 mermaidPart 4: Watch Mode
Keep the index fresh during development:
Terminal 1 - Watch for file changes:
ctx index --watchTerminal 2 - Auto-embed new symbols:
ctx embed --watchNow 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
*.csvWhat'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" --explainSmart 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 --summaryPart 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 --summaryNote: 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 jsonPart 10: Interactive Shell
Explore your codebase interactively:
ctx shellShell commands:
find <pattern>- Find symbolssearch <query>- Hybrid searchcallers <fn>- Show callerscallees <fn>- Show calleessource <symbol>- Show sourceexplain <symbol>- Explain symbolimpact <symbol>- Impact analysisstats- Codebase statisticshelp- 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 --mcpConfigure 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 4Workflow 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 indexWorkflow 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 mermaidWorkflow 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 --explainWorkflow 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-onlyWorkflow 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 1Note:
ctx audit --incremental(auditing only changed files) is not yet implemented; the audit always analyzes the full indexed codebase.
Next Steps
- Context Generation - All output formats and filtering options
- Code Intelligence - Deep dive into indexing and querying
- Configuration - .contextignore and environment variables
- Language Support - What's extracted from each language
- Architecture - How ctx works under the hood