
Open Context Engine
io.github.Dhaxor由 GitHub 帳號 Dhaxor 發布v0.7.1更新於 Nov 8, 2026
Local-first code retrieval: hybrid search over an AST-aware index of your codebase. Fully offline.
概覽
本地優先的 MCP 伺服器,為程式碼庫建立索引,讓助理取得語意與關鍵字混合的程式碼檢索、檔案瀏覽與符號查找能力。
- 可以做什麼
- 以自然語言對已索引的程式碼庫做向量與關鍵字混合檢索
- 瀏覽並讀取已索引檔案,可指定行範圍
- 查找函式、類別或型別的定義位置,並列出識別字的所有引用點
- 查看索引狀態:分塊數、檔案數、檢索模式與嵌入模型
- 啟動時監看工作區變動,讓索引保持即時更新
- 適用情境
- 適合讓助理回答關於本機程式碼庫的問題、在陌生程式碼中導覽,或讓編碼工作依據檢索到的原始碼而非猜測。也適合希望檢索完全留在自己機器上的團隊。
- 執行需求
- 以本機程序方式執行,透過 npm 套件 @dhaxor/open-context 的 oce mcp 指令並指定工作區路徑啟動,需要 Node.js 22 或更新版本。嵌入為選用:未設定時僅做關鍵字檢索;語意排序需要 Ollama、選用的本機 transformers 套件,或 Voyage、OpenAI 的金鑰。HTTP 模式可透過 OCE_MCP_AUTH_TOKEN 要求 bearer 權杖。
安裝
在 SourceWeft 中
- 開啟 儀表板中的 Open Context Engine,將其新增到工作區。
- 為需要使用其工具的對話啟用該服務。
Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。
其他 MCP 客戶端
參照 儲存庫 中的啟動說明。
README
Open Context Engine
[TypeScript] [SQLite] [MCP] [License]
Local. Semantic. Instant.
Turn any codebase into a searchable knowledge base for AI.
Open Context Engine (OCE) is a local-first, high-performance retrieval engine that indexes your entire codebase, embeds it into vectors, and serves it up to LLMs via semantic search, keyword search, and the Model Context Protocol (MCP). No cloud required. No code leaves your machine.
Whether you're building a coding assistant, automating PR reviews, or just want to ask natural-language questions about your own code—OCE gives your AI ground truth.
📘 Docs, benchmarks & guides: opencontextengine.com — MCP setup for Claude Code & Cursor, the agentic-workflow guide, and measured retrieval benchmarks.
✨ What Makes It Special
🚀 Quick Start
1. Install
2. Pick a model — free options included
oce setup checks what you already have (a running Ollama, keys in your
environment) and lists every way to get a working model, free ones first:
oce setup -p google records your choice; after that oce trace just works.
Hybrid search out of the box — no key, no account. The first index embeds
with local MiniLM (in-process, on-device, nothing sent anywhere), so semantic +
keyword search works immediately. Want the strongest code retrieval? A Voyage
key upgrades the embedding model — oce setup --embeddings voyage — and the
index rebuilds with it. Local does the job fine if you'd rather not.
3. Open Trace
Both index the current directory on start and keep one conversation going — see Trace below for what makes it different.
4. Or search from the command line
🔭 Trace
Trace is the agent workspace. Every coding agent shows you what it did; Trace also shows you what it knew — because OCE owns the retrieval, not just the chat loop.
- Evidence rail. What is in the model's context window right now: every retrieved chunk ranked by its fusion score, the graph edge that pulled it in ("called by search.ts"), and a budget meter split into retrieval / files / history / system. Pin a chunk and it survives compaction; evict one and it is genuinely removed from the next request.
- Retrieval readout instead of a spinner —
retrieved 5 · top 0.94 · graph +2 · 251ms. - The spine. A timeline of checkpoints, one per turn, on the same hash chain as the audit log. Click one to rewind: the conversation and the files the agent changed roll back — and a file you edited by hand since is left alone.
- Approvals with a blast radius. Every edit and shell command waits for
y/always /n, showing the diff, a risk score, and how many indexed callers the file has. - Sub-agents you can watch. Delegated research streams into its own collapsible block instead of going silent for minutes.
- Parallel sessions. In a git repository, each new session gets its own
worktree and branch, so agents never edit the same checkout. Review a
session's diff and land it (commit +
--no-ffmerge) when it's done — uncommitted work is never discarded when you close one. - The composer.
@pathpins a file into context (fuzzy-matched against the index),!commandruns a shell command through the same approval flow, and/commandfor everything else — the same in the browser and terminal.
oce trace binds to 127.0.0.1 only and mints a fresh access token each
launch. Useful flags: --port, --no-open, --headless (API only),
--no-parallel.
In the terminal
Bare oce opens the same workspace full-screen in your terminal: the same
evidence rail (from 100 columns wide, or Ctrl+R), the same
checkpoint gutter, the same approvals. Esc or Ctrl+C
interrupts a run; Ctrl+C twice or /exit quits. Pipes,
--print, and dumb terminals fall back to the classic line-by-line REPL, which
you can also ask for with oce --classic.
As a desktop app
desktop/ wraps Trace in an Electron shell that adds desktop notifications
(only when an approval is waiting, a turn finishes in the background, or
something fails), an application menu, and trace:// deep links. It is built
from a source checkout for now — see desktop/README.md.
The classic REPL
oce --classic streams styled output, shows each tool call with a live spinner and timing, and — before any file edit or shell command — prints a diff/command preview and asks for approval (y / always / n). Ctrl+C interrupts the current run without quitting the session.
Approval modes (as in the other leading coding CLIs):
- default (
suggest) — every edit and shell command asks first --auto-edit— file edits apply automatically; shell still asks--full-auto— nothing asks (for containers / CI)
Switch mid-session with /mode. Interactive sessions have the edit and shell tools available behind approvals; the non-interactive --print path keeps them opt-in via --allow-edits / --allow-shell.
Slash commands: /help /reset /compact /plan /diff /usage /tools /mode /sessions /resume /exit.
Sessions persist automatically to .open-context/sessions/. oce --continue resumes the last conversation in the workspace; oce --resume <id> restores a specific one (list them with /sessions).
Harness features:
- Plan tracking — the agent maintains a live step checklist for multi-step work, rendered as you watch.
- Sub-agent delegation — broad explorations run in a scoped read-only child agent, so their large intermediate output never floods the main context.
- Summarizing compaction — when history gets long, older turns are condensed into a context note by the model rather than dropped, so decisions and file paths survive; force it with
/compact. - Environment awareness — platform, git branch/status, date, and index stats are injected into the system prompt.
- Cost + parallelism — every turn ends with a stats line (steps, tool calls, token usage, wall time); read-only tool calls in a turn run in parallel, while any turn with an edit or shell call stays strictly ordered.
--routesends each query to a cost-appropriate model tier;--memoryremembers codebase insights across sessions;--auditlogs runs to the tamper-evident audit log.
Non-interactive use for scripts and CI:
The programmatic API mirrors all of this: defaultAgentTools({ context }) stays read-only unless you pass includeEdits/shell/plan/delegate, and ContextAgent accepts hooks (a PermissionManager composes in here), compaction, and environmentProvider.
5. Connect to Claude / Cursor via MCP
The MCP server indexes the workspace on startup and then watches for changes, so the index stays live without a manual re-index. Pass --no-watch to disable the watcher. (The MCP handshake is established before indexing begins, so the first index of a large repo won't block your client from connecting.)
In HTTP mode the server speaks MCP's Streamable HTTP transport, binds to loopback by default, answers GET /health, and — when --auth-token (or OCE_MCP_AUTH_TOKEN) is set — requires Authorization: Bearer <token> on every request.
Then add to your MCP config:
6. Or use the VS Code extension
The extension/ folder ships a full VS Code experience on top of the same
engine: a sidebar chat grounded in your index (streaming, markdown,
code-block copy/insert/apply), agent edits with per-file diff /
undo / redo and a per-turn "undo all", quick search
(Ctrl+Shift+K), auto-indexing on save, and an
index health panel for debugging retrieval. Each platform package carries
one Node-API SQLite binding, which runs on every VS Code from 1.103 and on
remote hosts (SSH, WSL, Codespaces) — see
extension/PUBLISHING.md for the support matrix,
or build your own VSIX:
📖 Usage Guide
CLI Reference
Programmatic API
MCP Server Integration
Exposed MCP tools:
codebase-retrieval— Natural language search over codelist-files— Browse indexed files with filtersread-file— Read file contents with optional line rangesfind-symbol-definition— Exact-name lookup of where a function/class/type is definedfind-symbol-references— Every indexed usage site of an identifierindex-status— Chunk count, file count, search mode, embedding model
🏗️ Architecture
⚙️ Configuration
Embedding Models
The local provider needs the optional @huggingface/transformers package; models download once into ~/.open-context/models (override with OCE_MODEL_DIR) and run offline afterwards.
Agent LLMs
openai, anthropic, google (Gemini, streaming + tools), ollama (fully local — oce -p ollama --llm-model qwen2.5-coder:7b needs no API key), and custom (any OpenAI-compatible endpoint via --llm-base-url). With -p ollama for the LLM, --embedding-provider local for embeddings, and reranker: { provider: "local" }, the entire stack runs offline — index, search, rerank, and agent.
Config file
Persistent settings live in ~/.open-context/config.json (user) and <workspace>/.open-context/config.json (project — commit it). Flags and env vars always win. API keys are deliberately rejected in config files; use env vars.
Search Configuration
Re-ranking
👥 Team Index Sync (Team)
Index once — in CI or on a lead's machine — and let the whole team pull the result instead of each paying to embed the same monorepo:
The artifact is the store itself (vectors + FTS + code graph + file hashes) gzipped, so reconciliation is a plain incremental index: only files whose hashes differ from the artifact re-embed. No OCE cloud service is involved — artifacts go to storage you control.
On top of that, a machine-wide embedding cache (~/.open-context/embed-cache.db, on by default in the CLI and extension) keys vectors by content hash: identical code never embeds twice, across repos, branches, and store rebuilds. Disable with --no-embed-cache or openContext.embedding.cache.enabled.
🛡️ Policy Controls
Commit a policy file and every OCE surface (CLI, extension, library) enforces it — a --allow-shell flag can't override it, and the merge is always most-restrictive-wins:
oce policy prints the effective merge and where each rule came from. Orgs on a Team+ plan can additionally ship an Ed25519-signed policy.lock (issued with scripts/license-tool.mjs sign-policy) that developers cannot loosen or delete their way out of.
🧾 Audit Log
oce agent --audit (or the openContext.agent.audit.enabled setting) appends every run, tool call, and MCP invocation to .open-context/audit/audit.jsonl. Each record is SHA-256 hash-chained to the previous one, so edits, deletions, and reordering are detectable:
Audit logging is an Enterprise feature; a workspace/org policy with "audit": { "required": true } also switches it on.
🛠️ Development
Project Structure
🧪 How Search Works
- Chunking: Your code is parsed by Tree-sitter into semantic units (functions, classes, methods). Unsupported files fall back to boundary-aware line chunking.
- Embedding: Each chunk is embedded using your chosen provider. Voyage Code-3 is optimized for code and gives the best retrieval quality.
- Indexing: Vectors go into
sqlite-vec, text into FTS5, metadata into SQLite tables. All local. - Query: Your natural language query is embedded and searched simultaneously via vector similarity and BM25.
- Fusion: Results are fused with Reciprocal Rank Fusion, then boosted by symbol-name matches, your editor context (active file, open tabs), and git recency.
- Re-ranking (optional): Top candidates are re-scored by a dedicated re-ranker for higher precision.
- Graph Expansion: Top results are expanded along the code graph — callers, callees, and referenced definitions ride along so the LLM sees the full picture.
If the sqlite-vec extension can't load on your platform, steps 2 and 4's vector half are skipped automatically and the engine runs keyword-only (BM25) — slower to find conceptual matches, but everything keeps working and getStatus() / the CLI / the extension all surface the mode.
📏 Measuring Retrieval Quality
oce eval scores the engine against a labeled query set — so ranking changes are measured, not guessed:
Reports recall@k, MRR, nDCG@k, hit-rate, and per-query latency, plus per-case deltas (improved / regressed) against a saved baseline. Metrics are file-granular: a case passes when the gold file ranks in the top-k unique files returned.
Current numbers, measured fresh on this repo's committed 44-case gold set (eval/oce.eval.json) and the external 27-case Flask set (eval/external/flask.eval.json) — baselines committed beside them:
Two honest readings, and both matter:
- Hybrid earns its keep where queries paraphrase intent — +6 points of recall on this repo's set, and it's the mode the agent actually runs in.
- Adaptive fusion closed the definition-query gap. Equal-weight RRF used to demote confident BM25 hits below vector-preferred docs/tests (MiniLM hybrid scored 0.852 on Flask, losing to keyword-only's 0.926). Queries are now classified by shape — identifier spellings, quoted code and file paths lean BM25; paraphrases lean semantic (
src/core/query-profile.ts) — and the local-MiniLM hybrid reaches parity with keyword-only (0.926) on the Flask set while keeping hybrid's edge on paraphrase queries. The voyage columns predate adaptive fusion (query-time change only; the committed baselines remain the equal-weight reference). Re-run any of it yourself:oce eval --no-adaptive-fusionA/Bs the old behavior.
The June baseline this section used to quote (hybrid 0.977) no longer reproduces on today's engine (0.943) — drift the harness now catches on every run instead of silently shipping.
Reports record which search mode produced them (hybrid vs keyword-only), and baseline comparisons warn loudly on a mode mismatch.
Cross-repo validation: the bundled set only proves retrieval on this repository. eval/external/ holds gold sets for codebases OCE has never seen — starting with Flask 3.1.2 (Python, 27 cases, recall@10 0.926 keyword-only) — with committed baselines and a workflow for adding more. A ranking change that wins on eval/oce.eval.json should be re-run there before it counts as progress.
A case file is a JSON array (or { cases: [...] }):
Keep your eval sets out of the index by listing their directory in .contextignore — a gold set maps queries to answers, so indexing it contaminates the rankings it measures.
📦 Requirements
- Node.js 22 or newer (22 and 24 LTS install without a compiler; Node 20 is end-of-life and the SQLite binding no longer ships prebuilt binaries for it)
- A chat model —
oce setuplists free options (Ollama locally, or a free-tier key from Google, Groq, Cerebras, or OpenRouter) - Embeddings are optional: without them, search runs keyword-only (BM25). For semantic ranking use Ollama (
nomic-embed-text, free and local), the optional@huggingface/transformerspackage (--provider local), or a Voyage / OpenAI key - Platforms without a sqlite-vec build (e.g. win32-arm64, Alpine) also run keyword-only
📄 License
MIT © Gain
Built for developers who want their AI to actually understand their code.
來源:README.md,提交 46b1241
工具
0版本歷史
1- v0.7.1最新Nov 8, 2026
評分
已滿足適用檢查項的 50%
該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。
- 近 30 天內可連通25 分
請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。
- 已宣告認證方式10 分
請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。
- 已列出工具15 分
請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。
- 描述必需15 分
- 圖示10 分
- 文件15 分
- 授權條款10 分