Code2Database MCP server
2026년 10월 22일 커밋코드베이스를 쿼리 가능한 지식 그래프로 변환하여 LLM 에이전트가 심층적인 구조 분석, 동시성 탐지 및 영향 분석을 수행할 수 있도록 합니다.
다른 이름 ssxdes/Code2Database
- 스타
- 1
- Tools
- —
- 다운로드, 30일
- —
- 최신 버전
- —
- 마지막 커밋
- 2026년 10월 22일
- 라이선스
- MIT
Code2Database MCP란?
Code2Database은(는) MCP server입니다. 코드베이스를 쿼리 가능한 지식 그래프로 변환하여 LLM 에이전트가 심층적인 구조 분석, 동시성 탐지 및 영향 분석을 수행할 수 있도록 합니다.
프로젝트 README에서 생성된 요약
Code2Database MCP server 정보
개발자는 전체 코드베이스를 영구적이고 쿼리 가능한 지식 그래프로 변환하여, 수동으로 파일을 검색하는 번거로움 없이 심층적인 구조 분석을 수행할 수 있습니다. grep에 의존하거나 파일을 하나씩 읽는 대신, 이 도구를 사용하면 AI 에이전트가 정밀한 쿼리를 실행하여 함수 관계, 데이터 흐름 및 조건부 컴파일 로직을 이해할 수 있습니다. C, C++, Go, Python, Java, Rust, Assembly와 같은 언어로 복잡한 시스템을 다루는 엔지니어를 위해 설계되었습니다.
이 시스템은 소스 코드를 스캔하여 불변의 AST 팩트를 생성하고, 이를 호출 그래프로 구축하는 방식으로 작동합니다. 사용자는 MCP stdio를 통해 Claude Code, Codex CLI, Cursor, Gemini CLI와 같은 클라이언트에 이를 통합할 수 있습니다. 서버는 계층형 컨텍스트 방식을 지원하여 토큰 사용량을 최소화할 수 있도록 micro, lite, standard 또는 full 컨텍스트 팩을 제공합니다. 고급 분석을 위해 libclang을 사용한 타입화된 vtable 디스패치와 경로 타당성 검사를 위한 Z3 solver를 활용할 수 있습니다.
활용 사례
- 1영향 분석 수행특정 함수를 수정할 경우 시스템의 어느 부분이 영향을 받는지 확인합니다.
- 2동시성 위험 탐지멀티스레드 코드베이스 내의 잠재적인 데이터 레이스 및 데드락을 식별합니다.
- 3시스템 크래시 디버깅진입점부터 특정 크래시 지점까지 가능한 모든 실행 경로를 추적합니다.
- 4필드 수준 데이터 액세스 추적특정 struct 필드나 전역 변수를 읽거나 쓰는 함수가 정확히 무엇인지 쿼리합니다.
프로젝트의 README를 바탕으로 작성되었습니다. 모든 활용 사례는 해당 내용의 인용문과 대조하여 확인합니다.
구성
C2D_LANGUAGES
| 이름 | 설명 | 유형 |
|---|---|---|
| C2D_LANGUAGES | — |
자동 검사
2026년 11월 15일에 실행됨전체 보고서 →아직 인증되지 않았습니다. 서버는 80점 이상의 점수, 심각한 결함 없음, 그리고 검사에 충분한 데이터를 갖추어야 합니다. 검사 방식 · 점수를 높이기 위해 수정할 항목
- 소스 저장소 연결 및 접근 가능ssxdes/code2database is public and reachablegithub.com/ssxdes/code2database ↗통과
- 패키지가 이 저장소를 소스로 명시검사되지 않음
- 빌드 출처(Sigstore 증명)검사되지 않음
- 오픈 소스 라이선스 (OSI)MITspdx.org/licenses/MIT.html ↗통과
- 최근 1년 내 커밋 또는 릴리스Last commit or release 2026-10-22github.com/ssxdes/code2database ↗통과
- OpenSSF Scorecard검사되지 않음
- 패키지 이름이 인기 패키지와 유사하지 않음검사되지 않음
- 패키지 및 해당 종속성에 중요한 보안 권고 없음검사되지 않음
- 모델에 대한 숨겨진 지침 없음0 tool descriptions and the README read; no override phrases, credential paths or hidden characters통과
- 파괴적인 도구에 라벨 표시됨검사되지 않음
- 원격 엔드포인트가 MCP 핸드셰이크에 응답검사되지 않음
README
GitHub에서 보기Code2Database
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
Code2Database MCP 질문
동시성 문제를 탐지할 수 있나요?
네, 멀티스레드 코드에서 데이터 레이스, 데드락 및 스레드 간 위험 요소를 탐지할 수 있습니다.
#ifdef와 같은 조건부 컴파일을 처리할 수 있나요?
네, 그래프에 조건부 컴파일 경로와 특정 플래그 아래에서 존재하는 호출 정보가 포함됩니다.