Integration of CodeGraph CPG analysis into the OpenCode AI coding assistant via MCP tools, the opencode-codegraph plugin, scenario commands, a custom agent, and the LSP server.
Table of Contents¶
- Overview
- Installation
- Unified Launch Script
- Repository Walkthrough
- Features
- Plugin
- Custom Commands
- Custom Agent
- LSP Server
- Configuration
- Architecture
- Troubleshooting
Overview¶
CodeGraph integrates with OpenCode through five layers that can be used independently or together. The primary interactive path is the OpenCode plugin plus the LSP server, with MCP tools remaining available for direct inspection and scripted workflows.
| Layer | What it does | How it works |
|---|---|---|
| MCP Tools (149) | Direct CPG, context, and workflow queries | codegraph_query, codegraph_explain, codegraph_context_fetch, etc. via stdio |
Plugin (opencode-codegraph) |
Scenario-aware context layer + agent-native tools | CPG/OpenViking context injection, explicit session tools, review/explain helpers, workflow follow-up, and governed multi-user session visibility |
| Custom Commands (8) | Reusable analysis prompts | /review, /audit, /explain, /onboard, /update, /status, /next, /continue |
| Custom Agent | CPG-focused AI agent | @codegraph — always checks call graph before changes |
| LSP Server | Real-time diagnostics | Security findings, dead code, complexity in editor via GoCPG gRPC |
Automatic vs manual mechanisms¶
| Mechanism | Trigger type | What happens |
|---|---|---|
Plugin chat.message + experimental.chat.system.transform |
Automatic | CPG context is injected when chat starts or file paths are mentioned |
Plugin tool.execute.after on git commit |
Automatic | Best-effort plugin-driven freshness/update flow runs after local commits |
LSP diagnostics (opencode + codegraph_lsp) |
Automatic | Editor diagnostics are recomputed through GoCPG read-only gRPC queries |
MCP codegraph_watch check/update |
Manual | Explicit freshness check/update with structured status fields |
OpenCode /update command |
Manual | Convenience wrapper around codegraph_watch freshness workflow |
OpenCode /status command |
Manual | Unified status for freshness, current HEAD, and latest review trace |
OpenCode /next command |
Manual | One-command workflow guidance from the current dogfooding state |
OpenCode /continue command |
Manual | Safe execution of the next refresh/review-oriented workflow step without exposing manual DB maintenance controls |
Direct gocpg update |
Manual | Forced incremental parse outside OpenCode UI flows |
Automatic plugin hooks are best-effort and non-blocking. For deterministic CI/headless freshness guarantees, run codegraph_watch update (or /update) explicitly.
Installation¶
Minimal setup (MCP only)¶
Create opencode.json in the project root:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"codegraph": {
"type": "local",
"command": ["python", "-m", "src.mcp", "--transport", "stdio", "--db", "data/projects/codegraph.duckdb"],
"environment": {
"CODEGRAPH_PROJECT": ""
}
}
},
"plugin": ["opencode-codegraph"],
"instructions": [".codegraph/AGENTS.md", ".codegraph/SCENARIO_PLAYBOOK.md"]
}
Note: The
opencode-codegraphplugin (npm) is the primary OpenCode integration layer. It provides auto-enrichment, explicit CodeGraph/OpenViking session tools, scenario-aware command support, review/explain helpers, and visibility into shared or handed-off explicit sessions. It requires the CodeGraph API running (uvicorn src.api.main:app --port 8000). If the API is not available, the plugin degrades gracefully and MCP tools still work via stdio.
Full setup (MCP + LSP)¶
Add LSP server for real-time editor diagnostics:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"codegraph": {
"type": "local",
"command": ["python", "-m", "src.mcp", "--transport", "stdio", "--db", "data/projects/codegraph.duckdb"],
"environment": {
"CODEGRAPH_PROJECT": ""
}
}
},
"lsp": {
"codegraph": {
"command": ["python", "-m", "codegraph_lsp", "--db", "data/projects/codegraph.duckdb"],
"extensions": [".py", ".go", ".js", ".ts", ".java", ".c", ".cpp", ".cs", ".kt", ".php", ".rb"]
}
},
"plugin": ["opencode-codegraph"],
"instructions": [".codegraph/AGENTS.md", ".codegraph/SCENARIO_PLAYBOOK.md"]
}
Note:
--dbis required. It identifies the target CPG managed by GoCPG. In this repository we usedata/projects/codegraph.duckdb.
Prerequisites¶
- CodeGraph installed (
pip install -e .in the codegraph repo) - CPG database built (
gocpg parse --input=. --output=project.duckdb) - GoCPG gRPC server running and able to access the target CPG database
- OpenCode 1.2.0+ installed (
npm install -g opencode-ai)
Unified Launch Script¶
Recommended startup command (MCP + plugin + LSP + scenario routing context):
python scripts/run_opencode_codegraph.py --model openai/gpt-5.3-codex
What the launcher guarantees before OpenCode starts:
opencode.jsoncontainsmcp.codegraph,lsp.codegraph, pluginopencode-codegraph, and instructions.- Plugin dependencies in
.opencode/are installed (runsnpm installonly when needed). - CodeGraph API is auto-started if unavailable (required by plugin tools and scenario flows).
- OpenCode starts with
--agent codegraphby default. - When
CODEGRAPH_OPENCODE_PLUGIN_SOURCE=local, the launcher also syncs the workspaceopencode-codegraphinto OpenCode runtime cache directories under%USERPROFILE%\\.cache\\opencode\\..., so headlessopencode runuses the current local plugin code.
Headless example:
python scripts/run_opencode_codegraph.py --run "Use codegraph_project_context and summarize top risks"
Pass extra OpenCode flags after --:
python scripts/run_opencode_codegraph.py --model openai/gpt-5.3-codex -- --print-logs
Verify setup¶
opencode mcp list # Should show: ✓ codegraph connected
opencode debug config # Check resolved configuration
opencode agent list # Should show: codegraph agent
python -m src.mcp --help # MCP entrypoint is importable
python -m codegraph_lsp --help # LSP entrypoint is importable
Repository Walkthrough¶
The exact setup applied in this repository:
- Updated
opencode.jsonto include bothmcp.codegraphandlsp.codegraph. - Set LSP DB path to
data/projects/codegraph.duckdbas the GoCPG-managed target database. - Kept LSP in stdio mode (default) for OpenCode-managed lifecycle.
- Added
plugin: ["opencode-codegraph"]and instructions: -.codegraph/AGENTS.md(MCP tools + CPG reference) -.codegraph/SCENARIO_PLAYBOOK.md(21-scenario routing guidance) - Validated config and runtime availability:
python -m json.tool opencode.json # JSON is valid
opencode mcp list # codegraph server connected
opencode debug config # shows resolved mcp/lsp/plugin/instructions
python -m src.mcp --help # MCP server available
python -m codegraph_lsp --help # LSP server available
gocpg stats --db data/projects/codegraph.duckdb
Stdio vs TCP¶
- Recommended for OpenCode: stdio (do not run a long-lived background LSP process manually).
- Use TCP only for debugging:
python -m codegraph_lsp --db data/projects/codegraph.duckdb --transport tcp --host 127.0.0.1 --port 2087
Ownership model¶
- GoCPG is the only runtime process that opens and mutates the CPG DuckDB file.
- OpenCode MCP, plugin, and LSP integrations are read-only clients over GoCPG APIs.
--dbin OpenCode and LSP config is a target database identifier, not permission for those clients to open DuckDB directly.
Features¶
1. MCP Tools (149 tools)¶
All 149 CodeGraph MCP tools are available in OpenCode chat. Key tool groups:
| Group | Tools | Use case |
|---|---|---|
| Context | codegraph_project_context, codegraph_file_context, codegraph_diff_context |
Understand project/file/diff before changes |
| Navigation | codegraph_find_callers, codegraph_find_callees, codegraph_explain, codegraph_search |
Navigate the call graph |
| Analysis | codegraph_hotspots, codegraph_taint_analysis, codegraph_pattern_search, codegraph_hypothesis |
Find security issues and hotspots |
| Operations | codegraph_compose, codegraph_autofix, codegraph_diagram |
Run composite analysis, auto-fix, diagrams |
| Project | codegraph_project_list, codegraph_project_switch |
Multi-project management |
Full tool reference is in .codegraph/AGENTS.md (auto-loaded via instructions).
2. Instructions Files¶
Two instruction files are loaded into every conversation via instructions:
.codegraph/AGENTS.mdprovides:- Complete list of available MCP tools with descriptions
- CPG table reference (
nodes_method,edges_call, etc.) - Usage recommendations (when to use which tool)
.codegraph/SCENARIO_PLAYBOOK.mdprovides:- Routing guidance for all 21 CodeGraph scenarios
- Intent-to-scenario mapping (when to use S02 vs S09 vs S18, etc.)
- Clarification that structural pattern search is a tool/CLI feature, not a numbered scenario
3. Freshness and Incremental Updates¶
The supported freshness path for OpenCode users is now plugin- and command-driven:
- the plugin can run a best-effort post-commit refresh after local
git commit; /updateruns an explicit freshness check and incremental update throughcodegraph_watch;/statusand/nextsurface the current workflow state and the recommended follow-up action;- LSP diagnostics reflect the refreshed CPG state in the editor.
In headless OpenCode, /update is the recommended control point because it returns structured freshness diagnostics (cpg_commit, head_commit, commits_behind, commits_behind_strict, is_fresh, is_fresh_strict, has_relevant_changes_since_cpg, freshness_reason, needs_update) and update diagnostics (failure_kind, auto_unlock_attempted, auto_unlock_killed_pids, auto_unlock_errors, next_step, next_command).
Plugin¶
The opencode-codegraph npm plugin (v0.1.37) is the main OpenCode integration surface. It adds auto-enrichment, explicit agent-native context operations, scenario-aware command support, workflow continuity, and lifecycle-aware OpenViking guidance on top of MCP tools. Source code: opencode-codegraph/ directory.
Plugin Features¶
| Hook | What it does |
|---|---|
experimental.chat.system.transform |
Injects CPG project summary (files, methods, hotspots, security findings) into system prompt |
chat.message |
Auto-enriches chat with CPG context when files are mentioned (methods, metrics, security findings) |
chat.message with edit intent |
Adds pre-edit warnings when the message looks like a modification request (refactor, fix, update, etc.) |
experimental.session.compacting |
Preserves workflow and explicit context-session continuity across long sessions |
command.execute.before |
Adds scenario-aware readiness, skill hints, resume guidance, session follow-up, and shared-session wording for /onboard, /review, /continue, /next, /explain, /status, and /update |
tool.execute.after |
Detects git commit, runs the best-effort post-commit CodeGraph refresh flow, and appends either a ready review summary or a pending summary with the next follow-up action. When the refresh finishes, OpenCode also receives a short notification title so the user sees the result immediately. |
permission.ask |
Auto-allows all codegraph_* MCP tools (no confirmation prompts) |
The plugin automation is best-effort and conversational. The supported developer workflow is centered on the OpenCode plugin, scenario commands, and the LSP server.
Current plugin-facing OpenViking session model:
- explicit session open or reconnect is the default path for scenario commands
/continue,/status, and/reviewpreserve the same evidence chain when a reusable session existsread_onlyshared sessions are visible and reopenable for review or testing, but not writable- ownership transfer is authoritative in CodeGraph; the plugin surfaces the resulting access mode and follow-up wording
- default skill guidance is lifecycle-aware:
currentonly by default,needs_reviewonly by explicit opt-in,deprecatedexcluded
Plugin Tools¶
The plugin adds explicit CodeGraph/OpenViking tools implemented in TypeScript on top of MCP:
| Tool | Parameters | Description |
|---|---|---|
codegraph_context_open_session |
session_id (optional) |
Open or reconnect an explicit CodeGraph/OpenViking context session |
codegraph_context_fetch |
query, target_uri (optional), limit (optional), session_id (optional), include_needs_review (optional) |
Fetch semantic context candidates for the active OpenCode session |
codegraph_context_read |
uri, level (optional), session_id (optional) |
Read a specific OpenViking viking:// resource |
codegraph_context_browse |
uri, level_limit (optional), node_limit (optional), session_id (optional) |
Browse an OpenViking resource tree |
codegraph_context_record_used_context |
items_json, session_id (optional) |
Persist used-context trace before background commit |
codegraph_context_commit |
session_id (optional) |
Trigger background commit for an explicit context session |
codegraph_context_status |
session_id (optional) |
Check background commit status |
codegraph_context_sync_status |
none | Read project-level context readiness and sync status |
codegraph_fused_search |
query, target_uri (optional), limit (optional), include_graph (optional), session_id (optional), include_needs_review (optional) |
Return one fused payload of OpenViking context hits and graph evidence |
codegraph_skill_list |
category (optional), include_needs_review (optional) |
List curated agent-visible CodeGraph skills |
codegraph_review |
base_ref (optional, default HEAD~1) |
Security + impact analysis on current diff |
codegraph_explain_function |
name (required) |
Deep function analysis with call graph, metrics, taint paths |
codegraph_review first tries the standard review workflow; if it returns empty output, the API now falls back to deterministic CPG-based analysis (changed files from diff, impacted methods/callers, and per-file security pattern findings).
Requirements¶
The plugin requires CodeGraph REST API running (uvicorn src.api.main:app --port 8000). If the API is not available, the plugin degrades gracefully — plugin-side automation skips cleanly and MCP tools continue working via stdio.
opencode-codegraph is built against @opencode-ai/plugin >=1.2.0.
Custom Commands¶
Eight commands are available via /command in OpenCode TUI:
For headless CLI runs, use opencode run --command <name> [args...] (not a literal /name message).
| Command | Description | Usage |
|---|---|---|
/review |
CPG-powered code review (diff analysis, taint, impact) | TUI: /review · Headless: opencode run --command review |
/audit |
Full codebase audit (uses compose, falls back to quick audit on timeout) | TUI: /audit · Headless: opencode run --command audit |
/explain |
Function analysis with focused call graph and metrics | TUI: /explain process_data · Headless: opencode run --command explain process_data |
/onboard |
Focused codebase onboarding for a question/topic | TUI: /onboard how does auth work? · Headless: opencode run --command onboard "how does auth work?" |
/update |
CPG freshness check + incremental update for active project | TUI: /update · Headless: opencode run --command update |
/status |
Unified development status across freshness and review trace | TUI: /status · Headless: opencode run --command status |
/next |
Single best next command from the current workflow state | TUI: /next · Headless: opencode run --command next |
/continue |
Safely execute the next refresh/review workflow step | TUI: /continue · Headless: opencode run --command continue |
Commands are defined in .opencode/commands/ as markdown files with YAML frontmatter.
Custom Agent¶
Switch to the CodeGraph agent for CPG-focused analysis:
@codegraph
The codegraph agent (uses your default model):
- Always checks CPG before modifying code
- Verifies callers before refactoring (codegraph_find_callers)
- Runs taint analysis before security reviews (codegraph_taint_analysis)
- Prioritizes by complexity and impact metrics (codegraph_hotspots)
Defined in .opencode/agents/codegraph.md.
LSP Server¶
The CodeGraph LSP server provides real-time CPG-powered diagnostics:
- Diagnostics: Security findings, dead code, complexity warnings
- Hover: Method metrics (complexity, fan_in, fan_out)
- CodeLens: Callers/callees count, taint paths
- Code Actions: Auto-fix for pattern findings
The dead-code diagnostics pipeline is filtered to reduce false positives from synthetic names (for example <module> and metaclass adapter artifacts) and deduplicated by method identity, so headless diagnostics are usable for iterative review.
Headless plan/act/review loop (validated)¶
# Plan: inspect current status, then refresh if needed
opencode run --command status
opencode run --command update
opencode debug lsp diagnostics src/dogfooding/cpg_freshness.py
# Act: edit code and run focused tests
pytest tests/unit/dogfooding/test_cpg_freshness.py tests/mcp/test_ci_ops.py -v
# Review: verify diagnostics + freshness status again
opencode debug lsp diagnostics src/mcp/tools/ci_ops.py
opencode run --command update
Use this loop when proving that CodeGraph data stays actionable across iterations: fix code, re-check diagnostics, and re-check CPG freshness in the same session.
Parameters¶
python -m codegraph_lsp --db project.duckdb [--complexity-threshold 10] [--transport stdio] [--log-level info]
| Parameter | Default | Description |
|---|---|---|
--db |
(required) | Path to DuckDB CPG database |
--complexity-threshold |
10 |
Cyclomatic complexity warning threshold |
--transport |
stdio |
Transport protocol: stdio or tcp |
--host |
127.0.0.1 |
TCP host (only for --transport tcp) |
--port |
2087 |
TCP port (only for --transport tcp) |
--log-level |
info |
Log level: debug, info, warning, error |
Configuration¶
Environment Variables¶
| Variable | Default | Description |
|---|---|---|
CODEGRAPH_API_URL |
http://localhost:8000 |
CodeGraph API base URL |
CODEGRAPH_PROJECT |
(empty) | Default project ID |
File Structure¶
.opencode/
commands/
review.md # /review command
audit.md # /audit command
explain.md # /explain command
onboard.md # /onboard command
update.md # /update command
status.md # /status command
agents/
codegraph.md # codegraph agent
.codegraph/
AGENTS.md # MCP tool reference (loaded via opencode.json instructions)
SCENARIO_PLAYBOOK.md # Scenario routing hints for model context
opencode.json # MCP + plugin + instructions config
opencode-codegraph/ # Plugin source (npm: opencode-codegraph@0.1.37)
Architecture¶
OpenCode
|
+-- Plugin (opencode-codegraph, npm)
| |-- chat.message hook --> CodeGraph REST API --> CPG context
| |-- experimental.chat.system.transform hook --> CodeGraph REST API --> project summary
| |-- tool.execute.after hook --> CodeGraph REST API --> incremental update
| |-- permission.ask hook --> auto-allow codegraph_*
| +-- custom tools --> CodeGraph REST API --> review/explain
|
+-- MCP Server (src.mcp, stdio)
| +-- 149 tools --> CPG, context, taint, patterns, compose
|
+-- Custom Commands (.opencode/commands/)
| +-- /review, /audit --> Prompt templates using MCP tools
| +-- /explain, /onboard --> Prompt templates using MCP tools
| +-- /update --> Freshness check + incremental CPG update
| +-- /status --> Unified freshness + review-trace status
|
+-- Custom Agent (.opencode/agents/codegraph.md)
| +-- CPG-first workflow --> Always check callers before refactoring
|
+-- Instructions (.codegraph/AGENTS.md)
| +-- Tool reference --> Auto-loaded into every conversation
|
+-- LSP Server (codegraph_lsp, optional)
+-- diagnostics --> security, dead code, complexity
+-- hover --> method metrics
+-- codelens --> callers/callees/taint
+-- codeaction --> autofix
Troubleshooting¶
MCP Server Not Connecting¶
opencode mcp list # Check connection status
opencode debug config # Verify MCP config is resolved
python -m src.mcp --transport stdio # Test MCP server directly
- Ensure
pythonis in PATH and the codegraph virtualenv is active - Check that CPG database exists (
data/projects/*.duckdb)
Commands Not Available¶
- Verify
.opencode/commands/directory exists in project root - Check files have valid YAML frontmatter (starts with
---) - Restart OpenCode after adding new commands
- Test:
opencode debug skillshould list the commands
Headless Command Usage¶
- In TUI use
/review,/audit, etc. - In headless mode use
opencode run --command review(oraudit,explain,onboard,update) - Do not send
/reviewas a plain message toopencode run; it is treated as normal text
Agent Not Showing¶
- Verify
.opencode/agents/codegraph.mdexists - Check frontmatter has
descriptionfield - Test:
opencode agent listshould showcodegraph - Test:
opencode debug agent codegraphfor full details
LSP Not Working¶
- Verify
--dbpoints to an existing DuckDB file - Check that
codegraph_lspmodule is importable:python -m codegraph_lsp --help - Confirm
opencode debug configincludeslsp.codegraph.commandwith the expected DB path - For stdio mode, no standalone TCP listener is expected
- Test:
opencode debug lsp diagnostics src/api/main.py
No CPG Data in Tool Results¶
- Verify CPG database is built:
python -m src.cli query "SELECT count(*) FROM nodes_method" - Check active project:
opencode run "Use codegraph_project_context" - Set project:
CODEGRAPH_PROJECT=myprojectinopencode.jsonenvironment