
Security News
GPT-6 Astra Attempts Supply Chain Attacks Against Open Source Maintainers in Testing
GPT-6 Astra hits 100% on ExploitBench and finds zero-days autonomously, while independent tests reveal scope violations and monitoring gaps.
opencode-codebase-index
Advanced tools
Semantic codebase indexing and search for OpenCode - find code by meaning, not just keywords
Stop grepping for concepts. Start searching for meaning.
opencode-codebase-index brings semantic understanding to your OpenCode workflow ā and now to any MCP-compatible client like Cursor, Claude Code, and Windsurf. Instead of guessing function names or grepping for keywords, ask your codebase questions in plain English.
check_creds.tree-sitter and usearch. Incremental updates take milliseconds.Install the plugin
npm install opencode-codebase-index
Add to opencode.json
{
"plugin": ["opencode-codebase-index"]
}
Index your codebase
Run /index or ask the agent to index your codebase. This only needs to be done once ā subsequent updates are incremental.
Start Searching Ask:
"Find the function that handles credit card validation errors"
Use the same semantic search from any MCP-compatible client. Index once, search from anywhere.
Install dependencies
npm install opencode-codebase-index @modelcontextprotocol/sdk zod
Configure your MCP client
Cursor (.cursor/mcp.json):
{
"mcpServers": {
"codebase-index": {
"command": "npx",
"args": ["opencode-codebase-index-mcp", "--project", "/path/to/your/project"]
}
}
}
Claude Code (claude_desktop_config.json):
{
"mcpServers": {
"codebase-index": {
"command": "npx",
"args": ["opencode-codebase-index-mcp", "--project", "/path/to/your/project"]
}
}
}
CLI options
npx opencode-codebase-index-mcp --project /path/to/repo # specify project root
npx opencode-codebase-index-mcp --config /path/to/config # custom config file
npx opencode-codebase-index-mcp # uses current directory
The MCP server exposes all 9 tools (codebase_search, codebase_peek, find_similar, call_graph, index_codebase, index_status, index_health_check, index_metrics, index_logs) and 4 prompts (search, find, index, status).
The MCP dependencies (@modelcontextprotocol/sdk, zod) are optional peer dependencies ā they're only needed if you use the MCP server.
Scenario: You're new to a codebase and need to fix a bug in the payment flow.
Without Plugin (grep):
grep "payment" . ā 500 results (too many)grep "card" . ā 200 results (mostly UI)grep "stripe" . ā 50 results (maybe?)With opencode-codebase-index:
You ask: "Where is the payment validation logic?"
Plugin returns:
src/services/billing.ts:45 (Class PaymentValidator)
src/utils/stripe.ts:12 (Function validateCardToken)
src/api/checkout.ts:89 (Route handler for /pay)
| Scenario | Tool | Why |
|---|---|---|
| Don't know the function name | codebase_search | Semantic search finds by meaning |
| Exploring unfamiliar codebase | codebase_search | Discovers related code across files |
| Just need to find locations | codebase_peek | Returns metadata only, saves ~90% tokens |
| Understand code flow | call_graph | Find callers/callees of any function |
| Know exact identifier | grep | Faster, finds all occurrences |
| Need ALL matches | grep | Semantic returns top N only |
| Mixed discovery + precision | /find (hybrid) | Best of both worlds |
Rule of thumb: codebase_peek to find locations ā Read to examine ā grep for precision.
In our testing across open-source codebases (axios, express), we observed up to 90% reduction in token usage for conceptual queries like "find the error handling middleware".
graph TD
subgraph Indexing
A[Source Code] -->|Tree-sitter| B[Semantic Chunks]
B -->|Embedding Model| C[Vectors]
C -->|uSearch| D[(Vector Store)]
C -->|SQLite| G[(Embeddings DB)]
B -->|BM25| E[(Inverted Index)]
B -->|Branch Catalog| G
end
subgraph Searching
Q[User Query] -->|Embedding Model| V[Query Vector]
V -->|Cosine Similarity| D
Q -->|BM25| E
D --> F[Hybrid Fusion RRF/Weighted]
E --> F
F --> X[Deterministic Rerank]
G -->|Branch + Metadata Filters| X
X --> R[Ranked Results]
end
tree-sitter to intelligently parse your code into meaningful blocks (functions, classes, interfaces). JSDoc comments and docstrings are automatically included with their associated code.Supported Languages: TypeScript, JavaScript, Python, Rust, Go, Java, C#, Ruby, PHP, Bash, C, C++, JSON, TOML, YAML
2. Chunking: Large blocks are split with overlapping windows to preserve context across chunk boundaries.
3. Embedding: These blocks are converted into vector representations using your configured AI provider.
4. Storage: Embeddings are stored in SQLite (deduplicated by content hash) and vectors in usearch with F16 quantization for 50% memory savings. A branch catalog tracks which chunks exist on each branch.
5. Hybrid Search: Combines semantic similarity (vectors) with BM25 keyword matching, fuses (rrf default, weighted fallback), applies deterministic rerank, then filters by current branch/metadata.
Performance characteristics:
The plugin automatically detects git branches and optimizes indexing across branch switches.
When you switch branches, code changes but embeddings for unchanged content remain the same. The plugin:
| Scenario | Without Branch Awareness | With Branch Awareness |
|---|---|---|
| Switch to feature branch | Re-index everything | Instant ā reuse existing embeddings |
| Return to main | Re-index everything | Instant ā catalog already exists |
| Search on branch | May return stale results | Only returns current branch's code |
.git/HEAD.opencode/index/
āāā codebase.db # SQLite: embeddings, chunks, branch catalog, symbols, call edges
āāā vectors.usearch # Vector index (uSearch)
āāā inverted-index.json # BM25 keyword index
āāā file-hashes.json # File change detection
The plugin exposes these tools to the OpenCode agent:
codebase_searchThe primary tool. Searches code by describing behavior.
"find the middleware that sanitizes input"search.fusionStrategy) ā deterministic rerank (search.rerankTopN) ā filtersWriting good queries:
| ā Good queries (describe behavior) | ā Bad queries (too vague) |
|---|---|
| "function that validates email format" | "email" |
| "error handling for failed API calls" | "error" |
| "middleware that checks authentication" | "auth middleware" |
| "code that calculates shipping costs" | "shipping" |
| "where user permissions are checked" | "permissions" |
codebase_peekToken-efficient discovery. Returns only metadata (file, line, name, type) without code content.
codebase_search.codebase_search (metadata-only output)[1] function "validatePayment" at src/billing.ts:45-67 (score: 0.92)
[2] class "PaymentProcessor" at src/processor.ts:12-89 (score: 0.87)
Use Read tool to examine specific files.
codebase_peek ā find locations ā Read specific filesfind_similarFind code similar to a provided snippet.
index_codebaseManually trigger indexing.
force (rebuild all), estimateOnly (check costs), verbose (show skipped files and parse failures).index_statusChecks if the index is ready and healthy.
index_health_checkMaintenance tool to remove stale entries from deleted files and orphaned embeddings/chunks from the database.
index_metricsReturns collected metrics about indexing and search performance. Requires debug.enabled and debug.metrics to be true.
index_logsReturns recent debug logs with optional filtering.
category (optional: search, embedding, cache, gc, branch), level (optional: error, warn, info, debug), limit (default: 50).call_graphQuery the call graph to find callers or callees of a function/method. Automatically built during indexing for TypeScript, JavaScript, Python, Go, and Rust.
name (function name), direction (callers or callees), symbolId (required for callees, returned by previous queries).validateToken ā call_graph(name="validateToken", direction="callers")The plugin automatically registers these slash commands:
| Command | Description |
|---|---|
/search <query> | Pure Semantic Search. Best for "How does X work?" |
/find <query> | Hybrid Search. Combines semantic search + grep. Best for "Find usage of X". |
/call-graph <query> | Call Graph Trace. Find callers/callees to understand execution flow. |
/index | Update Index. Forces a refresh of the codebase index. |
/status | Check Status. Shows if indexed, chunk count, and provider info. |
Zero-config by default (uses auto mode). Customize in .opencode/codebase-index.json:
{
"embeddingProvider": "auto",
"scope": "project",
"indexing": {
"autoIndex": false,
"watchFiles": true,
"maxFileSize": 1048576,
"maxChunksPerFile": 100,
"semanticOnly": false,
"autoGc": true,
"gcIntervalDays": 7,
"gcOrphanThreshold": 100,
"requireProjectMarker": true
},
"search": {
"maxResults": 20,
"minScore": 0.1,
"hybridWeight": 0.5,
"fusionStrategy": "rrf",
"rrfK": 60,
"rerankTopN": 20,
"contextLines": 0
},
"debug": {
"enabled": false,
"logLevel": "info",
"metrics": false
}
}
String values in codebase-index.json can reference environment variables with {env:VAR_NAME} when the placeholder is the entire string value. Variable names must match [A-Z_][A-Z0-9_]*. This is useful for secrets such as custom provider API keys so they do not need to be committed to the config file.
{
"embeddingProvider": "custom",
"customProvider": {
"baseUrl": "{env:EMBED_BASE_URL}",
"model": "nomic-embed-text",
"dimensions": 768,
"apiKey": "{env:EMBED_API_KEY}"
}
}
| Option | Default | Description |
|---|---|---|
embeddingProvider | "auto" | Which AI to use: auto, github-copilot, openai, google, ollama, custom |
scope | "project" | project = index per repo, global = shared index across repos |
| indexing | ||
autoIndex | false | Automatically index on plugin load |
watchFiles | true | Re-index when files change |
maxFileSize | 1048576 | Skip files larger than this (bytes). Default: 1MB |
maxChunksPerFile | 100 | Maximum chunks to index per file (controls token costs for large files) |
semanticOnly | false | When true, only index semantic nodes (functions, classes) and skip generic blocks |
retries | 3 | Number of retry attempts for failed embedding API calls |
retryDelayMs | 1000 | Delay between retries in milliseconds |
autoGc | true | Automatically run garbage collection to remove orphaned embeddings/chunks |
gcIntervalDays | 7 | Run GC on initialization if last GC was more than N days ago |
gcOrphanThreshold | 100 | Run GC after indexing if orphan count exceeds this threshold |
requireProjectMarker | true | Require a project marker (.git, package.json, etc.) to enable file watching and auto-indexing. Prevents accidentally indexing large directories like home. Set to false to index any directory. |
| search | ||
maxResults | 20 | Maximum results to return |
minScore | 0.1 | Minimum similarity score (0-1). Lower = more results |
hybridWeight | 0.5 | Balance between keyword (1.0) and semantic (0.0) search |
fusionStrategy | "rrf" | Hybrid fusion mode: "rrf" (rank-based reciprocal rank fusion) or "weighted" (legacy score blending fallback) |
rrfK | 60 | RRF smoothing constant. Higher values flatten rank impact, lower values prioritize top-ranked candidates more strongly |
rerankTopN | 20 | Deterministic rerank depth cap. Applies lightweight name/path/chunk-type rerank to top-N only |
contextLines | 0 | Extra lines to include before/after each match |
| debug | ||
enabled | false | Enable debug logging and metrics collection |
logLevel | "info" | Log level: error, warn, info, debug |
logSearch | true | Log search operations with timing breakdown |
logEmbedding | true | Log embedding API calls (success, error, rate-limit) |
logCache | true | Log cache hits and misses |
logGc | true | Log garbage collection operations |
logBranch | true | Log branch detection and switches |
metrics | false | Enable metrics collection (indexing stats, search timing, cache performance) |
codebase_search and codebase_peek use the hybrid path: semantic + keyword retrieval ā fusion (fusionStrategy) ā deterministic rerank (rerankTopN) ā filtering.find_similar stays semantic-only: semantic retrieval + deterministic rerank only (no keyword retrieval, no RRF).search.fusionStrategy to "weighted" to use the legacy weighted fusion path.benchmarks/baselines/retrieval-baseline.jsonbenchmark-results/retrieval-candidate.jsonThis repository includes a first-class eval system for retrieval quality with versioned golden sets, compare mode, parameter sweeps, CI budgets, and run artifacts.
npm run eval
npm run eval:ci
npm run eval:ci:ollama
npm run eval:compare -- --against benchmarks/baselines/eval-baseline-summary.json
CI usage split:
npm run eval:smoke: harness smoke check with local mock embeddings (used in main CI)npm run eval:ci: real quality gate against baseline/budget (for scheduled/manual quality workflow)For eval-quality.yml, the default CI path uses GitHub Models with the workflow GITHUB_TOKEN plus models: read, so you do not need a separate OpenAI API key just to run the scheduled gate.
That default GitHub Models path uses benchmarks/budgets/github-models.json, which applies stable absolute thresholds instead of the stricter baseline-regression budget used for explicit external providers.
Optional override secrets for another OpenAI-compatible endpoint:
EVAL_EMBED_BASE_URLEVAL_EMBED_API_KEYEVAL_EMBED_MODEL (optional, default text-embedding-3-small)EVAL_EMBED_DIMENSIONS (optional, default 1536)If you override the provider, set both EVAL_EMBED_BASE_URL and EVAL_EMBED_API_KEY. Otherwise the workflow falls back to GitHub Models automatically. Override providers continue to use the baseline-driven budget in benchmarks/budgets/default.json.
No OpenAI API access? Use Ollama quality gate locally:
.github/eval-ollama-config.jsonnpm run eval:ci:ollamaPrerequisites: Ollama installed, ollama serve running on 127.0.0.1:11434, and nomic-embed-text pulled.
Examples:
# Run against small golden set
npm run eval -- --dataset benchmarks/golden/small.json
# Compare against baseline
npm run eval:compare -- --against benchmarks/baselines/eval-baseline-summary.json --dataset benchmarks/golden/medium.json
# Sweep retrieval parameters
npm run eval -- --dataset benchmarks/golden/small.json --sweepFusionStrategy rrf,weighted --sweepHybridWeight 0.3,0.5,0.7 --sweepRrfK 30,60 --sweepRerankTopN 10,20
wrong-file, wrong-symbol, docs-tests-outranking-source, no-relevant-hit-top-k)Each run writes:
benchmarks/results/<timestamp>/
summary.jsonsummary.mdper-query.jsoncompare.json (when baseline/sweep used)benchmarks/golden/small.jsonbenchmarks/golden/medium.jsonbenchmarks/golden/large.jsonbenchmarks/budgets/github-models.json for the default GitHub Models workflow pathbenchmarks/budgets/default.json for explicit external provider overrides with baseline comparisonFull docs: docs/evaluation.md
Recent representative runs (plugin vs ripgrep vs ast-grep) on two medium repos:
Methodology for the snapshot below:
axios + expressdefinition, keyword-heavy) with scoped denominators shown in run reports--no-reindex, default)| Metric | Plugin | ripgrep | ast-grep (5/10 queries) |
|---|---|---|---|
| Hit@5 | 50% | 5% | 100% |
| MRR@10 | 0.48 | 0.04 | 0.90 |
| nDCG@10 | 0.48 | 0.08 | 0.93 |
| Latency p50 (ms) | 17.5 | 36.9 | 66.6 |
| Latency p95 (ms) | 30.9 | 44.1 | 70.7 |
--reindex)| Metric | Plugin | ripgrep | ast-grep (5/10 queries) |
|---|---|---|---|
| Hit@5 | 50% | 5% | 100% |
| MRR@10 | 0.48 | 0.04 | 0.98 |
| nDCG@10 | 0.48 | 0.07 | 0.98 |
| Latency p50 (ms) | 17.1 | 35.9 | 69.1 |
| Latency p95 (ms) | 30.4 | 43.7 | 75.1 |
ast-grep metrics are computed on its compatible query subset only (definition + keyword-heavy, 5/10 queries per repo). Plugin and ripgrep are scored on all 10 queries.
Interpretation:
For reproducible setup and commands (including with/without reindex), see:
docs/benchmarking-cross-repo.mdThe plugin automatically detects available credentials in this order:
nomic-embed-text)You can also use Custom to connect any OpenAI-compatible embedding endpoint (llama.cpp, vLLM, text-embeddings-inference, LiteLLM, etc.).
Each provider has different rate limits. The plugin automatically adjusts concurrency and delays:
| Provider | Concurrency | Delay | Best For |
|---|---|---|---|
| GitHub Copilot | 1 | 4s | Small codebases (<1k files) |
| OpenAI | 3 | 500ms | Medium codebases |
| 5 | 200ms | Medium-large codebases | |
| Ollama | 5 | None | Large codebases (10k+ files) |
| Custom | 3 | 1s | Any OpenAI-compatible endpoint |
For large codebases, use Ollama locally to avoid rate limits:
# Install the embedding model
ollama pull nomic-embed-text
// .opencode/codebase-index.json
{
"embeddingProvider": "ollama"
}
The plugin is built for speed with a Rust native module (tree-sitter, usearch, SQLite). In practice, indexing and retrieval remain fast enough for interactive use on medium/large repositories.
For reproducible measurements on your machine, run: npx tsx benchmarks/run.ts.
Quick recommendation:
| Provider | Speed | Cost | Privacy | Best For |
|---|---|---|---|---|
| Ollama | Fastest | Free | Full | Large codebases, privacy-sensitive |
| GitHub Copilot | Slow (rate limited) | Free* | Cloud | Small codebases, existing subscribers |
| OpenAI | Medium | ~$0.0001/1K tokens | Cloud | General use |
| Fast | Free tier available | Cloud | Medium-large codebases | |
| Custom | Varies | Varies | Varies | Self-hosted or third-party endpoints |
*Requires active Copilot subscription
Set the provider in .opencode/codebase-index.json:
{ "embeddingProvider": "ollama" }
Credentials (if required) are read from environment variables (for example OPENAI_API_KEY or GOOGLE_API_KEY).
Custom (OpenAI-compatible)
Works with any server that implements the OpenAI /v1/embeddings API format (llama.cpp, vLLM, text-embeddings-inference, LiteLLM, etc.).
{
"embeddingProvider": "custom",
"customProvider": {
"baseUrl": "{env:EMBED_BASE_URL}",
"model": "nomic-embed-text",
"dimensions": 768,
"apiKey": "{env:EMBED_API_KEY}",
"maxTokens": 8192,
"timeoutMs": 30000,
"maxBatchSize": 64
}
}
Required fields: baseUrl, model, dimensions (positive integer). Optional: apiKey, maxTokens, timeoutMs (default: 30000), maxBatchSize (or max_batch_size) to cap inputs per /embeddings request for servers like text-embeddings-inference. {env:VAR_NAME} placeholders are resolved before config validation for fields that are actually used and throw if the referenced environment variable is missing or malformed.
Be aware of these characteristics:
| Aspect | Reality |
|---|---|
| Search latency | ~800-1000ms per query (embedding API call) |
| First index | Takes time depending on codebase size (e.g., ~30s for 500 chunks) |
| Requires API | Needs an embedding provider (Copilot, OpenAI, Google, or local Ollama) |
| Token costs | Uses embedding tokens (free with Copilot, minimal with others) |
| Best for | Discovery and exploration, not exhaustive matching |
Build:
npm run build
Register in Test Project (use file:// URL in opencode.json):
{
"plugin": [
"file:///path/to/opencode-codebase-index"
]
}
This loads directly from your source directory, so changes take effect after rebuilding.
For contribution workflow, standards, and release-label requirements, see CONTRIBUTING.md.
If you want to add support for a new language, see docs/adding-language-support.md for the full Rust + TypeScript checklist.
Quick path:
npm run build && npm run typecheck && npm run lint && npm run test:runTo ensure release notes reflect all merged work, this repo uses a draft-release workflow.
feature, bug, performance, documentation, dependencies, refactor, test, choresemver:major, semver:minor, or semver:patchRelease Label Check) and fail if no release category label is presentmain.CHANGELOG.mdpackage.json versionnpm run build && npm run typecheck && npm run lint && npm run test:rungh release create after reviewing draft content).PRs labeled skip-changelog are intentionally excluded from release notes.
āāā src/
ā āāā index.ts # Plugin entry point
ā āāā mcp-server.ts # MCP server (Cursor, Claude Code, Windsurf)
ā āāā cli.ts # CLI entry for MCP stdio transport
ā āāā config/ # Configuration schema
ā āāā embeddings/ # Provider detection and API calls
ā āāā indexer/ # Core indexing logic + inverted index
ā āāā git/ # Git utilities (branch detection)
ā āāā tools/ # OpenCode tool definitions
ā āāā utils/ # File collection, cost estimation
ā āāā native/ # Rust native module wrapper
ā āāā watcher/ # File/git change watcher
āāā native/
ā āāā src/ # Rust: tree-sitter, usearch, xxhash, SQLite
āāā tests/ # Unit tests (vitest)
āāā commands/ # Slash command definitions
āāā skill/ # Agent skill guidance
āāā .github/workflows/ # CI/CD (test, build, publish)
The Rust native module handles performance-critical operations:
Rebuild with: npm run build:native (requires Rust toolchain)
Pre-built native binaries are published for:
| Platform | Architecture | SIMD Acceleration |
|---|---|---|
| macOS | x86_64 | ā simsimd |
| macOS | ARM64 (Apple Silicon) | ā simsimd |
| Linux | x86_64 (GNU) | ā simsimd |
| Linux | ARM64 (GNU) | ā simsimd |
| Windows | x86_64 (MSVC) | ā scalar fallback |
Windows builds use scalar distance functions instead of SIMD ā functionally identical, marginally slower for very large indexes. This is due to MSVC lacking support for certain AVX-512 intrinsics used by simsimd.
MIT
FAQs
Host-neutral semantic codebase search with embeddings, symbol discovery, and call-graph tooling
The npm package opencode-codebase-index receives a total of 755 weekly downloads. As such, opencode-codebase-index popularity was classified as not popular.
We found that opencode-codebase-index demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 1 open source maintainer collaborating on the project.

Security News
GPT-6 Astra hits 100% on ExploitBench and finds zero-days autonomously, while independent tests reveal scope violations and monitoring gaps.

Product
Socket can now send alerts and supply chain attack notifications to Microsoft Teams, with filters that route the right updates to each channel.

Security News
pnpm 12 rewrites the package manager in Rust, cutting install times by up to 90% while preserving pnpm 11 workflows and lockfiles.