ctx
A fast CLI tool that generates AI-ready context from your codebase, with built-in code intelligence for understanding symbol relationships.
📖 Documentation: https://docs.agentis.tools/
Two Tools in One
Context Generation - Select files using glob patterns and get formatted output perfect for LLMs:
|
Code Intelligence - Build a searchable index of your codebase with call graphs and impact analysis:
Features
Context Generation
- Glob pattern support - Select files with patterns like
"src/**/*.rs"or"**/*.ts" - Smart ignore system - Respects
.gitignoreand.contextignore - Built-in filtering - Excludes binary files,
node_modules, build artifacts, and 170+ patterns - Multiple output formats - XML (default), Markdown, JSON, or plain text
- Project tree visualization - ASCII tree showing file structure
- Streaming output - Files output as processed, pipeable to clipboard
- Token counting - Count tokens for LLM context window management
Code Intelligence
- Multi-language parsing - Rust, TypeScript, JavaScript, JSX/TSX, Python, Go, Solidity, YAML
- Symbol extraction - Functions, classes, interfaces, structs, enums, traits
- Rich relationship tracking - Calls, extends, implements, and imports edges
- Call graph analysis - Track function calls and dependencies
- Impact analysis - See what would be affected by changing a symbol
- Keyword search - FTS5-powered search across symbols and documentation
- Semantic search - Embedding-based natural language search (local or OpenAI)
- Watch mode - Automatic reindexing on file changes
Advanced Features
- Smart context selection - AI-powered file selection based on task description
- Diff-aware context - Generate context focused on git changes
- PR review context - GitHub integration for pull request analysis
- Code quality audit - Automated quality analysis with CI integration
- Quality gates - Architecture rules (
ctx check) and change scoring (ctx score) with a 0/1/2 exit-code convention for CI and AI agents - Interactive shell - REPL for codebase exploration
- MCP server - Claude Desktop integration via Model Context Protocol
Feature Flags
duckdb(enabled by default) — Enables DuckDB-powered analytics (call graphs, impact analysis, complexity analysis). Disable with--no-default-featureson platforms where DuckDB cannot compile (e.g. Windows MSVC without C++ build tools).mcp— Enable Model Context Protocol server support for Claude Desktop integration.
Installation
From crates.io (the package is agentis-ctx; it installs the ctx binary):
# On Windows (MSVC without C++ build tools), skip the DuckDB feature:
From a local checkout:
Or build from source:
# Binary at ./target/release/ctx
With MCP Support (for Claude Desktop)
Updating
If you installed a release binary, ctx can update itself from GitHub releases:
Every download is verified against the release's SHA256SUMS file before the
binary is replaced; on mismatch the update aborts (exit 2) and the installed
binary is untouched. Cargo installs should update with
cargo install agentis-ctx instead.
ctx never updates itself automatically. On interactive runs it checks for
a newer release at most once per 24h (1s timeout, silent failure) and prints a
one-line notice to stderr — nothing more. Set CTX_NO_UPDATE_CHECK=1 to
silence the notice entirely; it is also suppressed in --json mode, when
stderr is not a terminal, and inside Claude Code hooks.
The Claude Code plugin generated by ctx harness init --mode plugin is
versioned in lockstep with the binary and updates through Claude Code itself
via /plugin update ctx. For frozen, reproducible installs, pin the
marketplace entry to a commit SHA when adding it
(/plugin marketplace add agentis-tools/ctx@<commit-sha>) — the plugin
then never moves until you re-pin, and the generated permissions deny
Bash(ctx self-update*) so agents cannot update the binary either. See
docs/commands/self-update.md.
Using ctx as a Library
Everything the CLI does is available as a Rust library, so you can embed
indexing, search, and context generation in your own tools. The package is
agentis-ctx, but the library target is named ctx:
[]
= "0.2"
# On Windows (or to skip DuckDB analytics):
# agentis-ctx = { version = "0.2", default-features = false }
use *;
use Path;
The API documentation covers the full surface:
smart context selection (smart), diff-aware context (diff), semantic
search via local or OpenAI embeddings (embeddings), call-graph analytics
(analytics), token counting (tokens), and output formatting
(formatter/output).
Quick Start
Generate Context for LLMs
# All files in current directory
# Specific patterns
# Copy to clipboard (macOS)
|
# Markdown format
# JSON format
# Count tokens only
# Limit output to token budget
Code Intelligence
# Build the index (creates .ctx/codebase.sqlite)
# Search for symbols (keyword matching)
# Generate embeddings for semantic search
# Semantic search (natural language)
# Find all callers of a function
# See what a function depends on
# Visualize call graph
# Impact analysis - what breaks if I change this?
# Watch for changes and auto-reindex
Output Formats
XML (default)
my-project/
├── src/
│ ├── main.rs
│ └── lib.rs
└── Cargo.toml
fn main() {
println!("Hello, world!");
}
Markdown
my-project/ ├── src/ │ └── main.rs └── Cargo.toml
## /src/main.rs
```rust
fn main() {
println!("Hello, world!");
}
### JSON
```json
{
"project_tree": "my-project/\n├── src/\n│ └── main.rs\n└── Cargo.toml",
"files": [
{
"name": "main.rs",
"path": "/src/main.rs",
"content": "fn main() {\n println!(\"Hello, world!\");\n}"
}
]
}
Code Intelligence Commands
ctx index
Build or update the code intelligence database.
ctx search <query>
Search for symbols using keyword matching (FTS5).
ctx semantic <query>
Search using embeddings for natural language queries.
ctx similar <description>
Find existing functions similar to a description — reuse before you write. Before writing a new function, run ctx similar with its intended purpose; if a strong match exists (high similarity and fan-in), extend or reuse it instead.
Each hit shows the symbol, similarity score, fan-in (how many callers it already has), and a one-line doc. Requires ctx embed first (exits with code 2 otherwise); --keyword works without embeddings.
ctx embed
Generate embeddings for semantic search.
ctx query
Query the code intelligence database.
# Find symbols by name pattern
# Show callers of a function
# Show dependencies of a symbol
# Visualize call graph (text, json, or dot format)
# Impact analysis
# Codebase statistics
# List all indexed files
ctx sql
Run read-only SQL against the code intelligence index through DuckDB, over a
stable v1 view layer (v1.symbols, v1.edges, v1.files, v1.meta). Reach
for ctx sql instead of the canned ctx query subcommands whenever you need an
aggregation, a join, or a custom WHERE condition. Query v1.* only — anything
else (e.g. code.*) is internal and unstable. For agents and scripts, use
--json with --max-rows. Run ctx sql --schema for the full column reference.
# Ten most complex symbols
# Symbol counts by kind
# Public functions that nothing calls (dead-code candidates)
Use --fail-on-rows to turn a query into a gate: any returned row is a
violation, and the command exits 1.
# Fails (exit 1) if the query returns any row
Access is read-only and engine-hardened (filesystem access, extension loading,
and file-based ATTACH are disabled; the index cannot be modified), so
Bash(ctx sql *) is safe to add to a Claude Code allow-list.
ctx explain <symbol>
Get detailed information about a symbol including its relationships.
ctx source <symbol>
Retrieve the source code for a symbol.
Smart Context Selection
Intelligently select files relevant to a task using semantic search and call graph analysis:
Options:
--max-tokens <N>- Maximum tokens in output (default: 8000)--depth <N>- Call graph expansion depth (default: 2)--top <N>- Number of initial semantic matches (default: 10)--explain- Show selection reasoning for each file--dry-run- Preview selection without generating context--openai- Use OpenAI embeddings instead of local model
Diff-Aware Context
Get context for changed files with automatic dependency expansion:
PR Review Context
Generate context for GitHub pull request review:
Requirements: GitHub CLI (gh) must be installed and authenticated.
Quality Gates
A suite of quality commands designed to be composed into CI pipelines and AI
agent hooks: ctx check (architecture rules from .ctx/rules.toml),
ctx score (quality delta of your changes vs. a git reference),
ctx duplicates (MinHash near-duplicate detection), ctx hotspots
(churn x complexity refactoring targets), ctx similar (find existing
functions before writing new ones), and ctx map (token-budgeted codebase
overview for LLM sessions).
All of them share a three-way exit-code convention -- that convention is the integration API:
| Code | Meaning |
|---|---|
| 0 | Success, nothing to report |
| 1 | Ran successfully but produced findings |
| 2 | Operational error (bad arguments, missing index, git failure, ...) |
# Enforce architecture rules; --against reports only new violations
# Score your changes: complexity/fan-out deltas, new duplication,
# rule violations, symbol churn -- with CI gate conditions
# Wire the whole suite into Claude Code (hooks, permissions, plugin scaffold)
See the Quality Gates guide
for the full suite, CI recipes, and the reference Claude Code hook
configuration, and docs/json-output.md for the
machine-readable --json contract.
Code Quality Audit
Automated quality analysis with CI integration:
Categories:
complexity- Function complexity (fan-out/fan-in analysis)duplication- Potential code duplicationcoverage- Documentation coveragemodularity- Module coupling analysisnaming- Naming convention checks
Complexity Analysis
Analyze code complexity and identify high fan-out functions:
Duplicate Detection
Detect structurally similar functions with MinHash fingerprints built during
ctx index. Functions are compared by the Jaccard similarity of their
normalized token shingles (identifiers -> ID, literals -> LIT, comments
dropped), so renamed variables and changed string literals still match.
Solidity functions are skipped (no tree-sitter grammar).
Breaking change: the old line-based
--similarity <PERCENT>/--min-lines <N>flags are gone.--thresholdis a 0.0-1.0 Jaccard similarity over 5-token shingles, not a percentage of matching lines. Rebuild the index once withctx index --forceafter upgrading.
Change Scoring
Score the quality delta of your working tree (or branch) against a git reference. Baselines are parsed in memory at the reference with the same parser, so the deltas compare like with like:
Metrics (usable in --fail-on as metric OP value with >=, <=, >, <):
complexity_delta, fan_out_delta, new_duplication, check_violations,
symbols_added, symbols_removed, files_changed.
The index is refreshed incrementally before scoring; exit codes are 0 (clean),
1 (a --fail-on condition was met), 2 (operational error).
Dependency Graph
Generate dependency graph visualizations:
Interactive Shell
REPL for codebase exploration:
Shell Commands:
find <pattern>- Find symbols by namesearch <query>- Hybrid search (text + semantic)source <symbol>- Show source codeexplain <symbol>- Explain symbol with relationshipscallers <fn>- Show function callerscallees <fn>- Show function calleesimpact <symbol>- Impact analysiscomplexity- Show high-complexity functionsstats- Codebase statisticsaudit- Run code quality auditcd <path>- Set file path contextpwd- Show current contextclear- Clear screenhelp- Show helpexit- Exit shell
MCP Server (Claude Desktop)
Expose ctx to AI assistants via Model Context Protocol:
# Build with MCP support
# Run MCP server
Configure Claude Desktop (claude_desktop_config.json):
Available MCP Tools:
search_symbols- Search for symbols by name patternget_definition- Get the source code for a symbolfind_references- Find all references to a symbolget_callers- Get functions that call a given functionget_callees- Get functions called by a given functionget_file- Read a file's contentsget_file_tree- List files in the projectsmart_context- Intelligently select files for a task
Ignore System
Three-tier ignore system:
.gitignore- Respected by default (disable with--no-gitignore).contextignore- Project-specific ignores, same syntax as.gitignore- Built-in patterns - Common non-source files (disable with
--no-default-ignores)
Example .contextignore
# Exclude test fixtures
fixtures/
__mocks__/
# Exclude generated code
*.generated.ts
*.pb.go
# Exclude vendored dependencies
vendor/
third_party/
Built-in Ignore Patterns
The tool automatically ignores:
- Version control (
.git/,.svn/,.hg/) - IDE directories (
.vscode/,.idea/) - Lock files (
package-lock.json,yarn.lock,Cargo.lock) - Dependencies (
node_modules/,vendor/,Pods/) - Build outputs (
dist/,build/,target/,.next/) - Cache directories (
.cache/,tmp/) - Binary files and media
Supported Languages
| Language | Extensions | Symbol Extraction | Edge Types |
|---|---|---|---|
| Rust | .rs |
Functions, structs, enums, traits, impls | Calls, Implements, Imports |
| TypeScript | .ts |
Functions, classes, interfaces, types, enums | Calls, Extends, Implements, Imports |
| TSX | .tsx |
Functions, components, interfaces | Calls, Extends, Implements, Imports |
| JavaScript | .js, .mjs, .cjs |
Functions, classes, arrow functions | Calls, Extends, Imports |
| JSX | .jsx |
Functions, components | Calls, Extends, Imports |
| Python | .py, .pyi |
Functions, classes, methods, constants | Calls, Extends, Imports |
| Go | .go |
Functions, structs, interfaces, methods | Calls, Implements, Imports |
| Solidity | .sol |
Contracts, functions, events, structs | Calls |
| YAML | .yaml, .yml |
File tracking (no symbols) | N/A |
Architecture
.ctx/
└── codebase.sqlite # SQLite database with FTS5 search and embeddings
- SQLite - Persistent storage for symbols, edges, embeddings, and compressed source
- DuckDB - In-memory analytical engine for recursive graph queries
- Tree-sitter - Fast, accurate parsing for all supported languages
- fastembed - Local embedding generation (all-MiniLM-L6-v2, 384 dimensions)
- OpenAI - Optional embedding generation (text-embedding-3-small, 1536 dimensions)
- sqlite-vec - Fast vector similarity search
CLI Reference
ctx - Generate AI-ready context from your codebase
USAGE:
ctx [OPTIONS] [PATTERNS]...
ctx <COMMAND>
COMMANDS:
index Build or update the code intelligence index
query Query the code intelligence database
sql Run read-only SQL against the index (v1 schema)
search Search for symbols using keyword matching
semantic Search using embeddings (natural language)
embed Generate embeddings for semantic search
source Get the source code for a symbol
explain Explain a symbol with its relationships
smart Intelligently select files for a task
diff Generate context for changed files
review Generate context for PR review (GitHub)
audit Run code quality analysis
check Check architecture rules from .ctx/rules.toml
score Score the quality delta of changes vs a git reference
complexity Analyze code complexity
duplicates Detect structurally similar functions (MinHash)
graph Generate dependency graph
shell Interactive codebase explorer
serve Start MCP server (with --mcp flag, requires mcp feature)
CONTEXT OPTIONS:
-f, --format <FORMAT> Output format [default: xml] [values: xml, markdown, md, plain, json]
--no-gitignore Disable .gitignore pattern matching
-i, --ignore <PATTERN> Additional ignore patterns
--no-default-ignores Disable built-in ignore patterns
--show-sizes Show file sizes in project tree
--no-tree Disable project tree in output
--no-stream Buffer output instead of streaming
--stats Print stats after completion
--count-only Only count tokens, don't output
--max-tokens <N> Limit output to N tokens
--encoding <ENC> Tokenizer encoding [default: cl100k_base]
INDEX OPTIONS:
-w, --watch Watch for changes and reindex automatically
-v, --verbose Show verbose output
--force Force full reindex (clears existing database)
-j, --parallel Use parallel parsing (faster on multi-core)
--no-gitignore Disable .gitignore pattern matching
--no-default-ignores Disable built-in ignore patterns
-i, --ignore <PATTERN> Additional ignore patterns
-p, --pattern <PATTERN> File patterns to include
Performance
- Indexes ~2000 files in under 10 seconds
- Parallel indexing with
--parallelflag (~1.7x speedup) - Incremental updates only reindex changed files
- Fast vector search with sqlite-vec
- Compressed source storage (~70% size reduction)
- In-memory DuckDB for fast analytical queries
- Local embeddings with fastembed (~90MB model, runs offline)
Environment Variables
| Variable | Description |
|---|---|
OPENAI_API_KEY |
Required for --openai flag with embed and semantic commands |
GITHUB_TOKEN |
Optional for review command (uses gh CLI auth by default) |
Examples
Generate context for a bug fix
# Find relevant code and generate context
|
Review a pull request
# Get context for PR review
Pre-commit quality check
# Add to .git/hooks/pre-commit
||
CI/CD integration
# In your CI pipeline
||
Explore codebase interactively
Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines on development setup, coding style, and the pull request process.
Security
To report a security vulnerability, see SECURITY.md.
License
This project is licensed under either of:
at your option.