OpenGrok MCP Server
Enables retrieval of commit history and Git blame annotations for source files indexed within OpenGrok.
Allows users to perform full-text searches, find symbol definitions, and browse file contents from OpenGrok directly within the GitHub Copilot Chat environment.
OpenGrok MCP Server
Code intelligence for any OpenGrok-indexed codebase — search, read, blame, symbol navigation, diffs, commit history, call graphs, dependency maps, and guided investigation. Optimized for token efficiency through Code Mode and AST-aware code reads.
Quick Start
Option 1 — VS Code Extension
Install OpenGrok MCP from the VS Code Marketplace, or search "OpenGrok" in the Extensions panel. The configuration panel opens on first launch — enter your OpenGrok endpoint, username, and password, then click Save Settings and reload when prompted.
The extension provides a visual configuration UI and manages the MCP server process automatically. No Python, external Node.js install, or manual environment setup required.
Option 2 — npm / npx CLI
npm install -g opengrok-mcp-server
opengrok-mcp setup # interactive wizard: URL, credentials, MCP client registrationOr run without installing:
npx opengrok-mcp-server setupOther CLI commands:
opengrok-mcp status # health check: validates connectivity and detects installed MCP clients
opengrok-mcp setup --test # test the stored connection without the wizard
opengrok-mcp setup --set contextBudget=generous # update one stored setting non-interactively
opengrok-mcp export-audit --format json --output audit.jsonl # export the audit log
opengrok-mcp version # print version and exit
opengrok-mcp help # show all commandsWorks with any MCP-compatible client (CLI or IDE). See MCP_CLIENTS.md for config format and troubleshooting.
Credentials are stored in the OS keychain (macOS Keychain, Windows Credential Manager, Linux libsecret) with an AES-256-GCM encrypted file fallback for headless environments.
Automatic Updates — The extension checks GitHub for new releases once per 24 hours and notifies you when one is available. Use OpenGrok: Check for Updates to check on demand.
Related MCP server: code-index-mcp
The Problem
Engineers working in large codebases face a specific gap when using AI coding assistants. The model's context window contains the file currently open, the conversation, and whatever has been manually shared — but a production codebase has structure, history, and cross-module relationships that exist entirely outside that window.
A symbol defined in one module and called from seventy others. A function whose behavior only becomes clear from the three commits that shaped it. An include chain stretching across a dozen directories. A call graph showing which components depend on a service before it gets refactored.
Without access to the code index, the model fills these gaps by guessing: it fabricates file paths, invents function signatures, misattributes changes to authors. The model is not wrong because it is unintelligent — it is wrong because it is isolated.
OpenGrok already solves this for human engineers. It indexes source in dozens of programming languages, maintains a full-text index across committed history, and exposes definition lookups, reference graphs, blame, directory traversal, and file history through a REST API. The problem was that AI tools had no way to reach it.
How It Works
┌──────────────────────────────────────────────────────┐
│ AI Client (Claude, Copilot, Cursor, Codex …) │
└─────────────────────┬────────────────────────────────┘
│ MCP (stdio or HTTP)
┌─────────────────────▼────────────────────────────────┐
│ OpenGrok MCP Server (Node.js) │
│ opengrok_api ──── full API spec, once per session │
│ opengrok_execute ─ run JavaScript in sandbox │
│ │
│ OpenGrok client ── search · symbols · blame · diffs │
└─────────────────────┬────────────────────────────────┘
│ HTTP (REST + web fallback)
┌─────────────────────▼────────────────────────────────┐
│ OpenGrok │
│ search · symbols · call graphs · index health │
└──────────────────────────────────────────────────────┘The server exposes two primary tools. opengrok_api delivers the full API specification at session start. Every subsequent operation goes through opengrok_execute: the AI writes a JavaScript program using the env.opengrok.* object — search, getFileContent, getFileAnnotate, getFileHistory, browseDir, getFileSymbols — and submits it as a single execution.
Intermediate results stay inside the sandbox; only the final return value crosses back to the context window. A complete investigation — find the symbol, read the definition, check who changed it, trace the callers — is one script, not a sequence of round-trips with results flowing through the context between each. Token savings of 80–95% are typical for complex investigations.
All env.opengrok.* calls appear synchronous inside sandbox code — the QuickJS WASM VM bridges async HTTP calls transparently over a SharedArrayBuffer + Atomics channel (8 MB data region, 62 s per-call timeout, 62 s hard execution cap), while keeping the Node.js event loop free.
Memory bank — two files persist across turns and session restarts: active-task.md (4 KB) for current investigation state and investigation-log.md (32 KB) for append-only findings. Inside the sandbox: env.opengrok.readMemory() / env.opengrok.writeMemory(). See the Memory Bank reference below.
Reference
31 tools total: 2–5 in Code Mode (opengrok_api + opengrok_execute, plus 3 memory tools when OPENGROK_ENABLE_MEMORY_TOOLS=true) and 26 in standard mode (OPENGROK_CODE_MODE=false).
Primary Tools
Tool | Purpose |
| Full-text, definition, reference, path, and history search. Supports |
| Locate files by name or directory pattern. Supports |
| Read source code. Use |
| Commit history for a file. Supports |
| View folder structure and contained files. Supports |
| List all indexed repositories. |
| Line-by-line blame annotation. Supports |
| Extract classes, functions, macros, and structs from a file. Supports |
| Query autocomplete recommendations. Supports |
Compound Tools
These merge multiple API calls into a single operation.
Tool | What it replaces | Savings |
| Search definition + read source + fetch headers + get references | ~92% fewer tokens |
| Search + read surrounding context (cap: | ~92% fewer tokens |
| 2–5 parallel searches, deduplicated results | ~73% fewer tokens |
| Latency, connectivity, staleness score | Diagnostic |
Investigation Tools
Tool | Purpose |
| Recent line changes grouped by commit — author, date, SHA, changed lines with context |
| BFS traversal of |
| Regex code search; returns |
| Blame with line range ( |
| Call chain tracing via OpenGrok API v2 (requires |
| Unified diff between two revisions with context lines |
| C/C++ compiler flags and include paths from local |
| All matching lines in a file when search shows truncated hits |
| Commit history with co-changed file lists via RSS feed |
| Direct download URL for a file (no HTTP call) |
| Project groups (empty when admin auth required) |
| Popular suggestions for a project field (empty when admin auth required) |
| Repositories for a project (empty when admin auth required) |
(Note: search tools support language filtering. Pass file_type using the canonical analyzer name — cxx for C++, golang for Go, sh for shell, javascript for JS. Aliases accepted: cpp/c++→cxx, go→golang, bash/shell→sh, js→javascript, ts→typescript, cs→csharp, py→python, rb→ruby, rs→rust.)
defs/refs/symbol fallback notes — defs, refs, and symbol searches require a project scope (pass projects or set OPENGROK_DEFAULT_PROJECT); without one they may return too many cross-project hits. On instances where the REST endpoint returns an error or empty results for these types, the client automatically falls back to web-UI parsing so the LLM still gets answers. opengrok_call_graph needs API v2 and degrades to a refs-based view on v1.
Set OPENGROK_CODE_MODE=true (the default). Call opengrok_api once at session start to receive the full API spec. All subsequent operations go through opengrok_execute.
All sandbox API calls are synchronous — flat globals (search(...)), no await. The env.opengrok.* object form (env.opengrok.search(...)) is equivalent.
Search & Discovery
Method | Returns |
| Full text, defs, refs, symbol, path, hist. Opts: |
| One result-set per query (max 10), run in parallel on the host. Per-query |
|
|
|
|
| All matching lines in a file when search results show truncated hits. Also used automatically when |
search() uses canonical file type names only (e.g. cxx, golang, sh) — see the alias list above. Pass expandFunction: true to expand matching results to their enclosing function body (adds host-side reads, up to 3 files per call).
Cursor pagination — Methods that return a cursor field (search, findFile, browseDir, getFileSymbols, getFileHistory, getFileDiff) support pagination. Pass the cursor back as opts.cursor on the next call to fetch the next page. If a cursor has expired (session restarted or too much time elapsed), the response contains { _cursorExpired: true } — restart pagination from the beginning.
Read & Navigate
Method | Returns |
|
|
|
|
|
|
|
|
History & Blame
Method | Returns |
|
|
|
|
| Commit history with co-changed file lists via RSS feed ( |
|
|
|
|
Code Intelligence
Method | Returns |
| Call chain tracing. |
| Definition + refs + headers combined. Definition expands to the full function body via tree-sitter |
| Dependency graph: |
| C/C++ compiler flags and include paths, or |
traceCallChain callers come from refs search; callees come from tree-sitter AST analysis for supported languages (C/C++, Java, Go, Python, JS/TS, Rust, and more). Both long-running methods fan out over a background client — a rate-limit-free sibling connection with a short per-operation budget — so deep traversals don't consume the foreground rate-limit quota.
System
Method | Returns |
|
|
|
|
| Read |
|
|
| Ask the user to choose (requires |
| Request AI text from the client's LLM (requires |
Example
// Example opengrok_execute code
const refs = env.opengrok.search("handleCrash", { searchType: "refs", maxResults: 5 });
const first = refs.results[0];
const content = env.opengrok.getFileContent(first.project, first.path, {
startLine: first.matches[0].lineNumber - 5,
endLine: first.matches[0].lineNumber + 10,
});
return { callerFile: first.path, code: content.content };When search() returns zero results and sampling is enabled, _suggestions: string[] is automatically injected into the result — check it before calling sample() explicitly.
Tree-sitter intelligence — range reads and expandFunction expand matches to enclosing function bodies using tree-sitter AST analysis (WASM grammars, no host toolchain needed). Per-tier line budgets apply: minimal 200 lines, standard 400 lines, generous 600 lines. Override the grammar directory with OPENGROK_GRAMMAR_DIR; contribute new grammars via npm run copy-grammars (see CONTRIBUTING.md).
fitToBuffer truncation — sandbox results that exceed the 8 MB bridge buffer are trimmed by fitToBuffer(), which keeps complete result elements rather than truncating mid-JSON. Trimmed results carry _truncated: true — narrow the query or page with cursor when you see it.
Elicitation (OPENGROK_ENABLE_ELICITATION=false to disable, default: true)
When enabled, opengrok_api prompts the user to select a working project at session start if no OPENGROK_DEFAULT_PROJECT is configured and more than one project exists. Sandbox code can also call env.opengrok.elicit() to ask the user to choose between multiple matches during execution. Requires a client that supports MCP Elicitation — Claude Code v2.1.76+ supports this. Degrades gracefully to { action: "cancel" } on other clients.
Sampling (OPENGROK_ENABLE_SAMPLING=true, default: false)
Delegates LLM calls back to the client via MCP Sampling, using the client's model subscription without separate API keys. Triggers automatically in three places: sandbox error explanation, large dependency graph summarization (>10 nodes), and zero-result query reformulation (_suggestions injection). VS Code Copilot supports sampling; other clients vary. The server degrades gracefully when sampling is unavailable.
Sampling triggers are automatic — not on-demand. A single investigation session can generate many sampling calls across sandbox errors, zero-result searches, and large dependency graphs. Some clients consume premium requests per call after the first confirmation prompt. Enable with this in mind.
Code Mode includes 2 tools by default (api + execute; 5 with OPENGROK_ENABLE_MEMORY_TOOLS=true). Two files persist across turns and session restarts:
Tool | Purpose |
| Status, size, and 3-line preview of both memory files |
| Read |
| Write or append; auto-timestamps |
File | Size Limit | Purpose |
| ≤ 4 KB | Current task state: |
| ≤ 32 KB | Append-only log of findings, grouped by |
Delta encoding returns [unchanged] on repeated reads of unmodified content. Richness-scored trimming keeps the highest-value log entries when space is tight.
Core
Variable | Default | Description |
| (blank) | OpenGrok server base URL (required). Supplied by the setup wizard or VS Code settings. |
| (blank) | Authentication username. Leave unset for anonymous access. |
| (blank) | Authentication password. Prefer OS keychain via |
| (blank) | Path to a file containing the OpenGrok password (file-mounted secret for CI/containers). Alternative to |
|
| Set |
|
| HTTP request timeout in seconds. |
Code Mode & Performance
Variable | Default | Description |
|
| Code Mode (2–5 tools: |
|
| Response size tier: |
| — | Override the per-response byte cap (takes precedence over |
| — | Override the |
| — | Force a format globally: |
| — | Default project name to scope all searches. |
|
| Default search result limit. |
| — | Comma-separated paths to |
| auto-detected | Override path to tree-sitter grammar WASM files. Default: walk up from the bundle directory to find |
Memory Bank
Variable | Default | Description |
|
| Register the 3 Code Mode memory tools (memory status, read, update). Off = api + execute only. |
| server default | Override directory for |
|
| Prepend compact history summaries to |
|
| Number of recent |
Rate Limiting
Variable | Default | Description |
|
| Enable token-bucket rate limiting. |
|
| Global requests-per-minute limit. |
| — | Per-tool RPM overrides: |
Response Cache
Variable | Default | Description |
|
| Enable TTL response cache. |
|
| Max cache entries. |
|
| Max total cache size in bytes (50 MB). |
|
| Search result cache TTL in seconds. |
|
| File content cache TTL in seconds. |
|
| File history cache TTL in seconds. |
|
| Project list cache TTL in seconds. |
MCP Protocol
Variable | Default | Description |
|
| Project picker at |
|
| MCP Sampling for error explanation, graph summarization, and zero-result recovery. |
|
| FileReferenceCache for |
| — | Model preference for sampling calls. |
|
| Token budget for sampling responses (max: 4096). |
OpenGrok API
Variable | Default | Description |
|
| REST API version. Use |
Security & Audit
Variable | Default | Description |
| — | File path for structured audit log (CSV or JSON). |
|
| Reject base URLs and redirects resolving to private/loopback IP ranges (default: warn-only). |
Logging
Variable | Default | Description |
|
| Set |
Proxy
Variable | Default | Description |
| — | HTTP proxy for outbound requests. |
| — | HTTPS proxy for outbound requests. |
VS Code users can set opengrok-mcp.baseUrl, opengrok-mcp.codeMode, opengrok-mcp.contextBudget, opengrok-mcp.memoryBankDir, opengrok-mcp.defaultProject, opengrok-mcp.responseFormatOverride, opengrok-mcp.compileDbPaths, opengrok-mcp.enableObservationMasker, and opengrok-mcp.observationMaskerTurns in VS Code settings instead. Secret values such as the password are never written to VS Code settings.
MCP SDK Note: This version uses
@modelcontextprotocol/sdkv1.30.0 (v1 line).
By default the server communicates over stdio. For shared team deployments, the HTTP transport layer is available as a library API (startHttpTransport() in src/server/transport/http-transport.ts) but is not yet wired into the CLI entry point — OPENGROK_HTTP_PORT is documented below but main.ts does not yet read it to start the HTTP server automatically. Use startHttpTransport() directly in custom deployments.
Session Management
Each HTTP client receives an isolated
McpServerinstance (per-session factory pattern)Sessions expire after 30 minutes of inactivity;
OPENGROK_HTTP_MAX_SESSIONScaps concurrent sessions (default: 100)GET /mcp/sessionsreturns JSON with active session count and oldest session age
Authentication
Method | Configuration |
Static Bearer token |
|
OAuth 2.1 resource server |
|
RBAC with named roles |
|
In resource server mode, this server validates JWTs issued by your own IdP — there is no built-in /token endpoint. When OPENGROK_JWT_ISSUER is set, tokens from other issuers are rejected. RFC 9728 protected resource metadata is served at /.well-known/oauth-protected-resource.
RBAC Roles
Role | Permissions |
| Full access to all tools and configuration |
| All search, read, memory, and code tools |
| Search and read tools only — no memory writes, no code execution |
Unknown or missing tokens are rejected with 403 Forbidden. When no authentication is configured, unauthenticated requests are granted admin (local dev mode).
CORS
Browser-based clients are gated by an origin allowlist (OPENGROK_ALLOWED_ORIGINS, comma-separated). Without auth configured, loopback origins (localhost, 127.0.0.1, [::1]) are allowed for local development; once auth is configured (OPENGROK_HTTP_AUTH_TOKEN or RBAC tokens), loopback is no longer implicit — list every allowed origin explicitly, including local ones.
Area | Protection |
SSRF | DNS rebinding detection + IPv6-mapped address blocking in |
Path traversal | NFC normalization + bidirectional Unicode character blocking in |
HTML injection | Entity decoding on all parser text nodes before display |
Prompt injection | Markdown-field escaping in all formatters |
Token comparison |
|
CORS | Allowlist via |
Security headers |
|
Credential encryption | AES-256-GCM with auto-upgrade from older encrypted files |
Rate limiting | Integer-based token bucket (eliminates float drift); per-tool defaults ( |
Sandbox isolation | QuickJS WASM VM — no filesystem, no network, method allowlist only; 62 s timeout, 8 MB buffer |
Audit logs | Injection-escaped structured audit entries |
For the full security architecture (threat model, defense layers, hardening guide), see SECURITY.md.
Sandbox trust recommendation: When configuring OpenGrok MCP in VS Code's MCP settings, you may set sandboxEnabled: true which auto-approves tool calls without confirmation prompts. This is safe because all tool execution occurs inside the QuickJS WASM sandbox with no host access — the LLM cannot execute arbitrary system commands through this server.
VS Code Integration
Command | Action |
| Interactive settings GUI |
| Validate API access and token validity |
| Expose background process stdout/stderr |
| Quick-access status menu from the status bar |
| Manually trigger an update check |
VS Code manages tool authorizations per workspace. If you open a different repository, re-check the OpenGrok box in the Copilot tools panel.
The configuration panel and VS Code Settings UI cover the same settings: use the panel for guided setup, secrets, testing, and reload prompts. Use opengrok-mcp.* settings in settings.json for workspace overrides, Settings Sync, and scripted defaults. Code Mode is recommended; disabling it uses legacy standard tools and excludes new Code Mode-only capabilities.
Troubleshooting
Runopengrok-mcp status to check connectivity and confirm which MCP clients are configured.
After reloading VS Code or updating the extension, tools may temporarily disappear from the Copilot tools list. Click the tools icon, select "Update Tools", then runDeveloper: Reload Window to restore them.
Connection failed — Verify OPENGROK_BASE_URL. Check that your VPN or proxy is not blocking the endpoint.
401 Unauthorized — Run OpenGrok: Open Configuration to re-enter credentials.
Self-signed SSL certificate errors — Set opengrok-mcp.verifySsl to false in VS Code settings, or OPENGROK_VERIFY_SSL=false in your MCP client config.
Slow queries or timeouts — Narrow the scope with file_type filtering or target a specific project. Check indexing status with opengrok_index_health.
Verbose logging — Set OPENGROK_LOG_LEVEL=debug.
OpenGrok Compatibility
Engine version | Status | Notes |
v1.13.x and above | Supported | Full REST API |
v1.7.0 — v1.12.x | Legacy mode | HTML scraping for symbols and blame |
Below v1.7.0 | Unsupported | Unpredictable behaviour |
Going Further
Client Setup · Architecture · Security · Contributing · Changelog
License Information
This system is distributed under the PolyForm Noncommercial License 1.0.0.
✅ Permitted: Personal use, hobby projects, academic research, education
❌ Prohibited: Any commercial, business, enterprise, or paid utilization
Commercial Licensing: To use this extension in an enterprise context (internal tooling, CI pipelines, business infrastructure), a commercial license is strictly required. Reach out to rudroy09@gmail.com for enterprise tier pricing.
Read LICENSE-COMMERCIAL.md for full terms.
This server cannot be deployed
Maintenance
Related MCP Connectors
The OpenRouter MCP server plugs OpenRouter into the AI tools you already use. Once connected, your assistant can pull live OpenRouter data (models, prices, your credits, rankings, and docs) and send quick test messages, all without leaving your editor.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
The Cortex MCP server provides read-only access to real-time engineering context from the Cortex developer portal, allowing AI coding assistants to answer natural language questions about your organization's catalog (microservices, libraries, domains, teams, infrastructure), scorecards (engineering standards and best practices), initiatives (goals and deadlines), and Engineering Intelligence metrics. It includes tools for querying documentation, tracking personal entities, and accessing AI-assisted insights across the entire Cortex ecosystem.
Search your AI chat history (ChatGPT, Claude, Codex) from any MCP client. Remote, private, read-only
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceA VS Code extension provides a MCP server that exposes Roslyn language features. It enables tools like find usages, go to definition, quick info, etc.4 npm223AGPL 3.0
- AlicenseAqualityAmaintenanceA Model Context Protocol (MCP) server that helps large language models index, search, and analyze code repositories with minimal setup14783 PyPI1,001MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI clients to perform local code search, indexing, and analysis across Java, JavaScript/TypeScript, .NET/C#, and Python projects through the MCP protocol.1Apache 2.0
- AlicenseNot gradedqualityDmaintenanceA production-ready Model Context Protocol (MCP) server that extends GitHub Copilot with GitHub repository management capabilities. Enables AI-driven issue tracking, repository information retrieval, and seamless GitHub integration.1MIT