MCP server Code2Database
Commit 22 de out. de 2026Converte bases de código em um grafo de conhecimento consultável para permitir que agentes de LLM realizem análises estruturais profundas, detecção de concorrência e análise de impacto.
Também conhecido como ssxdes/Code2Database
- Stars
- 1
- Ferramentas
- —
- Downloads, 30 dias
- —
- Versão mais recente
- —
- Último commit
- 22 de out. de 2026
- Licença
- MIT
O que é o MCP Code2Database?
Code2Database é um MCP server. Converte bases de código em um grafo de conhecimento consultável para permitir que agentes de LLM realizem análises estruturais profundas, detecção de concorrência e análise de impacto.
Resumo gerado a partir do README do projeto
Sobre o MCP server de Code2Database
Desenvolvedores podem transformar toda a sua base de código em um grafo de conhecimento persistente e consultável para realizar análises estruturais profundas sem a necessidade de buscas manuais em arquivos. Em vez de depender de grep ou ler arquivos um por um, esta ferramenta permite que agentes de IA executem consultas precisas para entender relacionamentos entre funções, fluxo de dados e lógica de compilação condicional. É projetado para engenheiros que trabalham com sistemas complexos em linguagens como C, C++, Go, Python, Java, Rust e Assembly.
O sistema opera escaneando o código-fonte para produzir fatos de AST imutáveis, que são então construídos em um grafo de invocação. Os usuários podem integrá-lo com clientes como Claude Code, Codex CLI, Cursor e Gemini CLI via MCP stdio. O servidor suporta uma abordagem de contexto em camadas, fornecendo pacotes de contexto micro, lite, standard ou full para manter o uso de tokens no mínimo. Para análises avançadas, ele pode utilizar libclang para dispatch de vtable tipado e o solver Z3 para verificações de viabilidade de caminho.
O que você pode fazer com ele
- 1Realizar análise de impactoDetermine quais partes de um sistema serão afetadas se uma função específica for modificada.
- 2Detectar riscos de concorrênciaIdentifique potenciais data races e deadlocks em bases de código multithread.
- 3Depurar crashes de sistemaRastreie todos os caminhos de execução possíveis desde os pontos de entrada até um ponto de crash específico.
- 4Rastrear acesso a dados em nível de campoConsulte exatamente quais funções estão lendo ou escrevendo em um campo de struct ou variável global específica.
Escrito a partir do README do projeto. Cada caso de uso é verificado com uma citação dele.
Configuração
C2D_LANGUAGES
| Nome | Descrição | Tipo |
|---|---|---|
| C2D_LANGUAGES | — |
Verificações automatizadas
Executado em 15 de nov. de 2026Relatório completo →Ainda não verificado. Um servidor precisa de uma pontuação de 80, nenhum problema grave e dados suficientes para verificarmos. Como as verificações funcionam · O que corrigir para ganhar mais pontos
- Repositório de origem vinculado e acessívelssxdes/code2database is public and reachablegithub.com/ssxdes/code2database ↗Passou
- O pacote indica este repositório como sua origemNão verificado
- Proveniência da build (atestação Sigstore)Não verificado
- Licença de código aberto (OSI)MITspdx.org/licenses/MIT.html ↗Passou
- Commit ou release no último anoLast commit or release 2026-10-22github.com/ssxdes/code2database ↗Passou
- OpenSSF ScorecardNão verificado
- Nome do pacote não é próximo a um pacote popularNão verificado
- Nenhum aviso crítico no pacote ou em suas dependênciasNão verificado
- Sem instruções ocultas para o modelo0 tool descriptions and the README read; no override phrases, credential paths or hidden charactersPassou
- Ferramentas destrutivas estão rotuladasNão verificado
- O endpoint remoto responde ao handshake do MCPNão verificado
README
Ver no GitHubCode2Database
Turn your codebase into a queryable code database — not just readable text
One scan. Persistent graph. Surgical queries. Fewer tool calls. Faster answers.
中文文档 · English Docs · Skill Guide
The shift: from reading code to querying code
AI agents today understand a codebase the slow way — grep, glob, Read, one file at a time, rebuilding invocation paths and dependencies by hand. That's a pile of tool calls and round-trips before the real work even starts. Every question re-discovers the same structure.
Code2Database turns that into a one-shot query. Scan once, and your codebase becomes a persistent knowledge graph: every function, every call edge, every condition, every concurrency hazard, every field access — indexable, queryable, and LLM-ready. The next question isn't "let me grep for it" — it's one tool call that returns the exact nodes, the invocation path between them, the conditional branches that gate them, and the blast radius if you change them.
Surgical context, not a file-by-file search. Fewer tool calls. Faster answers. And a graph that compounds in value as your team keeps querying it.
| Read-only code text | → | Queryable code database |
|---|---|---|
grep / glob / Read |
→ | explore-flow → nodes + paths |
| one file at a time | → | trace forward → A → B with conditions |
| re-discover on every question | → | concurrency detect-races → cross-thread hazards |
| manual call-path tracing | → | param-flow → data flow across funcs |
| no concurrency visibility | → | field-access → who reads/writes X |
no #ifdef awareness |
→ | trace reverse → all paths to crash point |
When to use it
- Understand how a codebase is structured and how functions call each other
- Trace execution paths from API entry points to internal implementations
- Impact analysis — what breaks if I change this function?
- Concurrency risks — detect data races and deadlocks in multi-threaded code
- Debug crashes by reverse-tracing from a crash point back to all entry points
- Understand how
#ifdefconditional compilation affects invocation paths - Query which functions access specific struct fields or global variables
- Build an always-up-to-date code graph that updates incrementally
- Give an LLM agent a compact project map it can drill into on demand
Quick Start
# 1. Install
bash install.sh --lang en --target all
# 2. Generate a project profile (project-specific conventions: callbacks, vtables, lock APIs)
# Auto-detects project type and writes .code2database_profile.json next to the source.
# Built-in profiles exist for common projects (linux_kernel, dpdk, spdk, etc.) —
# you can skip this step and pass --profile config/profiles/<type>.json to scan instead.
python3 scripts/code2database_scanner.py auto-profile \
--source /path/to/code \
--outdir /path/to/code
# 3. Scan source code → extraction.json (immutable AST facts)
python3 scripts/code2database_scanner.py scan \
--source /path/to/code \
--profile /path/to/code/.code2database_profile.json \
--output code2db-out/.code2database_extraction.json
# 4. Build invocation graph → queryable database
python3 scripts/code2database_builder.py build \
--extraction code2db-out/.code2database_extraction.json \
--outdir code2db-out/ --build-config auto
# 5. Query the graph
python3 scripts/code2database_builder.py explore-flow \
--graph code2db-out/ --query "initialization" --max-tokens 2000
# 6. (Optional) Start background daemon for real-time auto-sync
python3 scripts/code2database_builder.py daemon start \
--graph code2db-out/ --source /path/to/code
After building, start with code2db-out/.code2database_context_pack_micro.md (~200 tokens) for a project overview, step up to lite for more detail, then use the query commands to drill down. This micro → lite → local pattern keeps token cost minimal — the agent only loads what the question actually needs.
Installation
One-Click Install (Recommended)
# Interactive: choose language and install path
bash install.sh
# Non-interactive:
bash install.sh --lang en --dir ~/.claude/skills/Code2Database --target claudecode
bash install.sh --lang zh --dir ~/.local/share/Code2Database --target codex
bash install.sh --target all # Install for all supported tools
The installer installs 4 sub-skills under ~/.claude/skills/:
Code2Database(core — always loaded, ownsscripts/)Code2Database-analysis(deep analysis — on-demand)Code2Database-ops(graph editing + ops — on-demand)Code2Database-kb(standalone knowledge/memory base — on-demand)
The three on-demand sub-skills symlink to the core's scripts/ directory — single CLI, no duplication.
Supported targets:
- claudecode — Claude Code (installs skill to
~/.claude/skills/, configures MCP server) - codex — Codex CLI (adds instructions to
~/.codex/instructions.md) - cursor — Cursor (creates rule file + MCP config)
- opencode — OpenCode (creates config with MCP server)
- gemini — Gemini CLI (creates instructions file)
Partial Language Install (lean install for single-language engineers)
If you only work with one or two languages, you can skip the tree-sitter grammars you don't need:
# Install only C and Go grammars (skip C++, Python, Java, Rust)
C2D_LANGUAGES=c,go bash install.sh --lang en --target claudecode
# Or run setup.sh directly with a language filter
bash scripts/setup.sh --languages c,go
bash scripts/setup.sh --languages c,cpp,rust --with-optional # also installs libclang + z3
Valid values: c, cpp, go, python, java, rust, all (default). ASM uses regex — no tree-sitter grammar needed.
Manual Install
# All languages (default)
pip install -r scripts/requirements.txt
# Or pick specific languages via setup.sh
bash scripts/setup.sh --languages c,go
Required: networkx, tree-sitter + language bindings (per-language — see Partial Language Install above)
Optional (recommended, NOT required):
libclang>=17.0— enables cgdb clang backend (typed vtable dispatch, CFG, data flow, sync primitives, config predicates). Tree-sitter-only mode is fully functional without it.z3-solver>=4.12— sound path feasibility (heuristic fallback without it)python-igraph>=0.11+leidenalg>=0.10— cross-domain Leiden community detection (domain fallback without them)
Language Support
Every language below gets full structural extraction and cross-file resolution into one graph — no per-language setup:
| Language | Extensions | What gets extracted |
|---|---|---|
| C / C++ | .c .cc .cpp .h .hpp .cxx |
Functions, calls, #ifdef branches, struct field access, macros, callbacks |
| Go | .go |
Functions, methods, interfaces/structs (method sets, embedding), imports, goroutine spawns, interface dynamic dispatch (INFERRED edges from statically-typed receivers) |
| Python | .py |
Functions, classes, decorators, async calls |
| Java | .java |
Classes, methods, annotations (Spring routes → API entries, framework callbacks), extends/implements, JVM main detection |
| Rust | .rs |
Functions, traits, impls, macro_rules! definitions + invocations + calls inside macro arguments, attributes (#[derive] ...) |
| Assembly | .S .s .asm |
Function labels, call instructions, register usage (regex-based) |
Plus profile-driven detection for frameworks, build systems, and project conventions — swap one Profile JSON to retarget the tool to a new project type.
Why Code2Database? — what's different
Most code-graph tools stop at "function calls function." Code2Database goes deeper: it tracks the conditions that gate each call, the concurrency context in which it runs, the fields and globals it touches, and the conditional compilation that decides whether it's compiled at all. That's the gap between an invocation graph and a code database you can ask real engineering questions of.
| Capability | What it gives you |
|---|---|
| Condition-aware chains | if/switch/#ifdef branches with empty-node aggregation. You see not just "A calls B" but "A calls B when CONFIG_X is defined and flag == 1." |
| Concurrency modeling | Thread spawn, goroutine, callback detection. Cross-thread data race detection. Concurrency safety analysis: can these two chains actually run in parallel? |
| Field-level access tracking | Query "which functions read/write task_struct->pid?" — across the whole graph, not by grepping. |
| Crash reverse-trace | Given a crash point, trace all paths from entry points that reach it. Built for post-mortem debugging. |
Conditional compilation (#ifdef) |
The graph knows which calls exist only under which CONFIG_* flags. Critical for kernel / embedded / cross-platform C. |
| 4-tier LLM context packs | micro (~200 tokens) → lite → std → full. The agent starts with the smallest map and only loads detail where the question demands. |
| Edge confidence | Every edge tagged EXTRACTED (1.0) / INFERRED (0.7–0.95) / AMBIGUOUS (0.1–0.3) — you always know what was found vs. guessed. |
| Profile → Scan → Build separation | Scan stage produces immutable AST facts; Build stage does inference. Extraction bug? Verify scan independently. Improve inference? Re-run Build in seconds, no re-scan. |
| Bilingual docs (EN/中文) | Skill instructions, references, and usage guides in both English and Chinese. |
| Commit-based provenance | Every node/edge carries commit_meta.source_commit (git/svn hash). Engineers verify with git show <hash>, not timestamps. See describe-commit, node-history, graph provenance, blame-node, find-commits. |
| Cypher-subset queries | Declarative graph queries with MATCH/WHERE/RETURN — query "MATCH (n)-[r:INVOKES]->(m) WHERE n.name =~ 'foo.*' RETURN n,m". |
| Value flow & DATA_FLOW edges | Trace parameter→return-value propagation across functions. Solves "where does this NULL come from?" — value-flow, param-flow. |
| Lock-held region analysis | Precise lock-held ranges with event-stream + char positions, not just "lock exists" — lock-coverage. Reduces false positives in race detection. |
| Z3 path feasibility | Auto-solve path feasibility with Z3 SMT solver; heuristic fallback when unavailable — path-feasible. Optional z3-solver dep. |
| Cross-function data dependencies | DATA_DEP edges scan ALL nodes for readers/writers, not just call-reachable successors — data-dep. |
| Invariant extraction | Preconditions, postconditions, loop_invariants, state_machine per function — invariants extract, invariants find, invariants apply. |
| LLM auto-semantic enhancement | Confidence-threshold auto-write (EXTRACTED+evidence auto-applies; INFERRED requires confirm; AMBIGUOUS rejected) with batch-confirm and rollback — auto-enhance, batch-confirm, rollback, fill-request. |
| Transactional updates | Snapshots + fcntl file locks for atomic multi-step updates — tx begin/commit/rollback/status/snapshot/restore/list-snapshots/replay-wal. |
| Cross-language FFI | Python ctypes / Go cgo / Rust extern "C" boundary tracing with type marshalling — ffi detect, ffi list, ffi trace, ffi types. |
| BUG benchmark | GraphInvestigator vs GrepInvestigator — measures recall, precision, tool calls, tokens, time — bug-benchmark. |
| Profile health & auto-evolution | 0-100 score across 7 categories; auto-detects new callback patterns; binds to git/svn HEAD — profile health, profile evolve, profile bind-version. |
| Doc-code alignment | Detects return-value / param / signature / stale-doc mismatches between docs and code — doc code-check, doc mark-stale, doc alignment-report, doc signature-diff. describe-node surfaces doc_code_mismatches. |
| Background daemon | Long-running process monitors source files (inotify/polling) and auto-updates graph in transactions — daemon start/stop/status/force-refresh/pause/resume/wait-sync/logs/reload/list-projects. Unix socket API at /tmp/code2database-daemon-<project>.sock. |
Key Features
| Feature | Description |
|---|---|
| Multi-language AST scanning | C/C++, Go, Python, Java, Rust, ASM via tree-sitter / regex |
| Condition-aware chains | if/switch/#ifdef branches with empty node aggregation and conditional compilation annotation |
| Concurrency modeling | Thread spawn, goroutine, callback detection; data race detection; concurrency safety analysis |
| Edge confidence | EXTRACTED (1.0) / INFERRED (0.7-0.95) / AMBIGUOUS (0.1-0.3) with the source evidence trail |
| One-shot exploration | explore-flow — single query to get relevant nodes, paths, and conditions |
| Incremental syncs | quick-update — patch graph without LLM; light-scan / patch-from-git for zero-token syncs |
| MCP server mode | serve — expose 83 MCP tools (55 base + 28 design-report) (36 code2database_* + 19 cgdb_*) for LLM agents (stdio transport) |
| Memory system | memory save / memory search / memory manage — persistent Q&A memory with decay |
| Blast radius analysis | blast-radius — what functions, APIs, and tests are affected by a change |
| Data race detection | concurrency detect-races / concurrency analyze — cross-thread data race and deadlock detection |
| Crash reverse-trace | trace reverse — trace all paths reaching a crash point from entry points |
| Field-level access | field-access — query which functions read/write specific struct fields or globals |
| Parameter flow | param-flow — track how a value flows across function boundaries |
| External code separation | Automatic detection of third-party / vendored code — keeps the graph about your code |
| Bilingual docs | English (docs/en/) and Chinese (docs/zh/) skill instructions and references |
| Commit provenance | commit_meta.source_commit on every node/edge; verify with git show <hash> |
| Cypher-subset queries | query — MATCH/WHERE/RETURN declarative graph queries |
| Value flow + DATA_FLOW | value-flow — parameter→return-value propagation across functions |
| Lock coverage | lock-coverage — precise lock-held ranges with event-stream + char positions |
| Path feasibility | path-feasible — Z3 SMT solver for sound path feasibility |
| Data dependencies | data-dep — cross-function DATA_DEP edges; scans ALL nodes for readers/writers |
| Invariants | invariants extract / invariants find / invariants apply — preconditions/postconditions/loop_invariants/state_machine |
| Auto-enhancement | auto-enhance / batch-confirm / rollback — confidence-threshold auto-write |
| Transactions | tx begin/commit/rollback — snapshots + fcntl locks |
| FFI tracing | ffi detect/list/trace/types — Python ctypes / Go cgo / Rust extern "C" |
| BUG benchmark | bug-benchmark — GraphInvestigator vs GrepInvestigator recall/precision |
| Profile health | profile health/evolve/bind-version — 0-100 score + auto-evolution |
| Doc-code alignment | doc code-check/mark-stale/alignment-report/signature-diff — detect doc-code mismatches |
| Background daemon | daemon start/stop/status/... — inotify + Unix socket + transactional sync |
How It Works
┌──────────────────────────────────────────────────────────────────────────┐
│ Source files (C/C++/Go/Python/Java/Rust/ASM) │
└────────────────────────────────────┬─────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────┐
│ [Profile] project-specific config: skip names, callbacks, vtables, │
│ domain rules, lock patterns, framework conventions │
└────────────────────────────────────┬─────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────┐
│ [Scan] tree-sitter AST extraction → extraction.json │
│ Produces immutable facts: functions, params, body_text, │
│ invoked, conditions, #ifdef, field reads/writes │
└────────────────────────────────────┬─────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────┐
│ [Build] Inference + graph construction │
│ vtable dispatch · callback bridging · domain classification │
│ community detection · race detection · edge confidence │
│ invariants · FFI detection · doc-code alignment │
└────────────────────────────────────┬─────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────┐
│ [Daemon] (optional) inotify/polling → debounce → batch │
│ → transactional sync → output file rebuild │
│ Circuit breaker: >1000 events/min → bulk rebuild │
└────────────────────────────────────┬─────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────┐
│ [Query] micro → lite → local · 83 MCP tools (55 base + 28 design-report) · 123 visible CLI cmds │
│ explore-flow · trace-chain · detect-races · param-flow │
│ value-flow · lock-coverage · path-feasible · data-dep │
│ extract-invariants · ffi-trace · doc-code-check · query │
│ field-access · reverse-trace · blast-radius · daemon-* │
└──────────────────────────────────────────────────────────────────────────┘
Why three stages?
| Problem | Monolithic approach | Three-stage approach |
|---|---|---|
| Switch projects | Change hardcoded rules | Only swap Profile JSON |
| Extraction bug | Can't tell if scan or build is wrong | Scan stage can be independently verified |
| Improve inference | Must re-scan everything | Only re-run Build (seconds, not minutes) |
| New language support | Rewrite everything | Write new Scanner only |
Capability Matrix
| Capability | What it gives you |
|---|---|
| Languages | 6 + ASM — C/C++ (shared scanner), Go, Python, Java, Rust, ASM (regex — no tree-sitter grammar) (Python + tree-sitter + ASM regex) |
| Storage | JSON output + optional SQLite backend for large graphs |
| MCP server | stdio transport, 83 query tools (36 code2database_* + 19 cgdb_* + 28 design-report) for LLM agents |
| CLI commands | 123 visible builder commands (278 spellings incl. hidden legacy) + 8 scanner subcommands, organized into 4 sub-skills (/Code2Database core, /Code2Database-analysis, /Code2Database-ops, /Code2Database-kb) — Build, Query, Trace, Concurrency, Knowledge, Memory, Provenance, Cypher, Data Flow, Lock Analysis, Path Feasibility, Invariants, Auto-Enhance, Transactions, FFI, Benchmark, Profile Health, Doc-Code, Daemon, cgdb (clang backend) |
| Call condition parsing | if/switch/#ifdef branches + empty-node aggregation |
Conditional compilation (#ifdef) |
Graph knows which calls exist only under which CONFIG_* flags |
| Data race detection | Cross-thread hazard detection — concurrency detect-races |
| Concurrency safety analysis | Can these two chains actually run in parallel? — concurrency analyze |
| Field-level access tracking | "Who reads/writes task_struct->pid" across the whole graph — field-access |
| Crash reverse-trace | All paths from entry points to a crash point — trace reverse |
| Execution scenarios | End-to-end execution flow tracking from API entry to leaves |
| Build-system macro resolution | compile_commands.json + #ifdef macro expansion |
| LLM context packs | 4 tiers — micro (~200 tokens) → lite → std → full |
| Blast radius analysis | What breaks if I change this function? — blast-radius |
| External code separation | Auto-detect vendor/third-party code — graph is about your code |
| Parameter flow tracking | How a value flows across function boundaries — param-flow |
| Commit provenance | Every node/edge has source_commit (git/svn hash) — describe-commit, node-history, graph provenance, blame-node, find-commits |
| Cypher-subset queries | Declarative graph queries — query "MATCH ... WHERE ... RETURN ..." |
| Value flow | Parameter→return-value propagation, DATA_FLOW edges — value-flow |
| Lock coverage | Precise lock-held ranges with event-stream + char positions — lock-coverage |
| Path feasibility | Z3 SMT solver for sound feasibility — path-feasible |
| Data dependencies | Cross-function DATA_DEP edges — data-dep |
| Invariant extraction | Preconditions/postconditions/loop_invariants/state_machine — invariants extract |
| LLM auto-enhancement | Confidence-threshold auto-write + batch-confirm + rollback — auto-enhance |
| Transactional updates | Snapshots + fcntl locks for atomic writes — tx begin/commit/rollback |
| FFI tracing | Python ctypes / Go cgo / Rust extern "C" — ffi detect/list/trace/types |
| BUG benchmark | GraphInvestigator vs GrepInvestigator recall/precision — bug-benchmark |
| Profile health | 0-100 score + auto-evolution + git/svn HEAD binding — profile health/evolve/bind-version |
| Doc-code alignment | Detect doc-code mismatches; surface in describe-node — doc code-check |
| Background daemon | Real-time file monitoring + transactional auto-sync — daemon start |
The design intent: Code2Database isn't "more languages" or "more tools" — it's deeper program semantics. Conditions, concurrency, field access,
#ifdef, crash tracing. The graph captures what an engineer actually needs to reason about, not just what's easy to extract.
Command Reference
Perguntas sobre o MCP Code2Database
Ele consegue detectar problemas de concorrência?
Sim, ele pode detectar data races, deadlocks e riscos entre threads em código multithread.
Ele lida com compilação condicional como #ifdef?
Sim, o grafo inclui a percepção de caminhos de compilação condicional e quais chamadas existem sob flags específicas.