Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

Documentation

Task-oriented guides and references for every codeweb surface — CLI, graph model, HTTP API, and MCP tools.

The pages in this section cover one user task each. Start with Getting started, then pick the surface you need. Every factual claim is verified against the source code of the current release.

1 - Getting started

Build codeweb, analyze a real project, and trace your first call chain.

What codeweb does

codeweb parses a source tree and builds a directed semantic graph. The core chain connects four layers:

Java Method ──InvokesMapper──▶ MappedStatement ──CallsProcedure──▶ Procedure ──DirectCall──▶ Procedure
                                                                    │
                                                                    └──TableAccess──▶ Table
  • SQL layer: procedures, functions, packages, tables, views, triggers, and other DDL objects parsed from openGauss / GaussDB dialect SQL.
  • Mapper layer: MyBatis/iBatis <select> / <update> / <insert> / <delete> statements from XML mapper files.
  • Java layer: methods and classes parsed with tree-sitter, plus SQL embedded in annotations and JDBC calls.
  • JSP layer (default feature jsp): SQL embedded in scriptlets, declarations, and expressions.

The result is queryable in both directions: who calls a procedure, what does a Java method touch, and what breaks when a table changes.

Build from source

codeweb is a single Rust crate. Rust’s latest stable toolchain is required.

git clone https://github.com/c2j/codeweb.git
cd codeweb

# CLI + TUI + JSP + Java extraction (default features)
cargo build --release

# Add the HTTP server and browser UI
cargo build --release --features serve

# Add the MCP server for LLM clients
cargo build --release --features mcp

# Everything at once
cargo build --release --features full

The binary lands in target/release/codeweb. Which subcommands exist depends on the feature set: serve needs the serve feature, mcp needs the mcp feature. See Architecture for the full feature matrix.

Create a project

codeweb init writes a codeweb.toml and a .codeweb/ state directory, registers the source directories to analyze, and immediately runs the first full analysis:

codeweb init my-project \
  -d ./src/main/java \
  -d ./src/main/resources/mapper \
  -d ./sql
  • Without --root, the project is created in the current directory and every -d path is registered for analysis. A -d that points outside the current directory does not move the project there.
  • --root <dir> creates the project in <dir> instead. A non-empty root without an existing codeweb.toml is refused unless you pass --force.

The generated codeweb.toml controls what is analyzed:

[project]
name = "my-project"

[analysis]
paths = ["./src/main/java", "./src/main/resources/mapper", "./sql"]
# exclude = ["**/test/**"]
# discriminator_columns = ["operation_no"]

[analysis.java]
# extra_sql_methods = ["doQuery"]
# extra_sql_var_patterns = ["QUERY"]

Analyze and inspect

Run from the same directory where you ran codeweb init — the project root holding codeweb.toml (or pass -p <dir> from anywhere):

codeweb analyze        # init already ran the first analysis; this refreshes incrementally
codeweb stats          # node/edge counts by type
codeweb files          # analyzed files with node counts
codeweb diff           # what changed since the last analysis

Subsequent codeweb analyze runs only re-parse files whose fingerprint (blake3 hash) changed, so iterations are fast. To force a full re-analysis, delete the .codeweb/fingerprints state.

Trace your first chain

With the repository’s demo sources, run inside the codeweb checkout:

codeweb init demo \
  -d lib/codeweb-complex-demo/sql \
  -d lib/codeweb-complex-demo/xml \
  -d lib/codeweb-complex-demo/java
codeweb analyze
codeweb trace "process_order"
codeweb trace-sql "UPDATE inventory"

trace prints the callers and callees of the matched node as a tree. trace-sql finds MappedStatement and JavaSql nodes by SQL fragment and walks back to the Java methods that reach them.

Pick an interface

SurfaceCommandFeatureWhat you get
CLIcodeweb <command>defaultAll analysis and export commands
TUIcodeweb tuidefaultTerminal explorer with search and node detail
Browser UIcodeweb serveserveCytoscape.js canvas plus a REST API
MCPcodeweb mcpmcp11 JSON-RPC tools for LLM clients

Next steps

2 - CLI reference

Every codeweb subcommand and flag, verified against the –help output of the current release.

Every project-scoped command accepts -p, --project <DIR> (default .), plus the global options below. This page documents codeweb v0.9.11 with all features enabled.

Global options

OptionValuesMeaning
--langzh-CN, en (default zh-CN)Output language
--threadsintegerWorker threads for parallel parsing. Default: max(4, logical_cpus - 2). Also honors RAYON_NUM_THREADS; the flag wins
-V, --version—Print version (currently 0.9.11)

Without a subcommand, codeweb runs in legacy mode: codeweb [INPUT] --format <dot&#124;json&#124;mermaid&#124;ndjson> --output <FILE> [--include-unresolved] [--sql-only] parses a file or directory directly and prints an export.

Project lifecycle

CommandKey optionsPurpose
codeweb init <NAME>-d, --dir <DIR> (repeatable), --root <DIR>, --forceCreate codeweb.toml + .codeweb/, register analysis paths, and immediately run the first analysis (the MCP codeweb_init tool, in contrast, inits without analyzing). A non-empty --root without codeweb.toml needs --force
codeweb analyze-p, --projectFull or incremental analysis (fingerprint-based)
codeweb diff-p, --projectFiles changed since the last analysis
codeweb stats-p, --projectNode/edge counts by type
codeweb files-p, --projectAnalyzed files with node counts

Tracing and inspection

CommandKey optionsPurpose
codeweb trace <FROM>-s, --style tree&#124;path, --exact, --regex, --all-matches, --fail-on-multiple, --builtfuncCallers and callees of a node
codeweb detail [NAMES]...-s, --style tree&#124;path, -d, --depth 1&#124;0&#124;-1, -f, --files, --related-ddl, -v, --verbose, --summarize-tables, --exact, --regex, --all-matches, --fail-on-multiple, --builtfuncPer-node callers/callees with optional source context
codeweb inspect [NODES]...-m, --max-depth (default 15), --max-paths (default 10), -s, --style summary&#124;paths&#124;both&#124;tree, --unreachable, --exact, --regex, --all-matches, --fail-on-multipleDirected paths connecting two or more nodes
codeweb impact--file <FILE> (repeatable) or --node <NODE> (mutually exclusive), -f, --format json&#124;text (default json), -d, --depth (default 1), -e, --edge-types (default all), --exact, --regexUpstream/downstream impact for a file’s nodes or one symbol
codeweb trace-sql [SQL]-f, --file <FILE> or positional SQL / - for stdinSearch mapper/sql nodes by SQL fragment, trace back to Java methods

Analysis

CommandKey optionsPurpose
codeweb lineage <TARGET>--direction upstream&#124;downstream&#124;both (default both), --depth (default 5), --format tree&#124;json&#124;dot&#124;mermaid, --view tree&#124;entity&#124;relation&#124;grouped, --flow-onlyTable/column lineage. See Lineage
codeweb columns--procedure <NAME> or --package <NAME> (required, one only), --table <NAME>, --format json&#124;seed-hints (default json), --discriminator <COL> (repeatable)Aggregated column analysis. See Column analysis
codeweb predicates--procedure <NAME> (required), --format jsonPL IF/CASE predicates resolved to columns
codeweb conflicts--severity high&#124;medium (default high), -f, --format json&#124;text (default json), --table <NAME>Cross-procedure table-lock conflicts (static analysis)
codeweb partition-k, --k <K>, --auto, --gamma <GAMMA>, --max-iterations <N>, --min-delta-q <Q>, --min-component-size <N> (default 1), --table-projection [<tau:lambda:k>], -o, --output <FILE>Cluster nodes for system decomposition; exports DOT with cluster_* blocks
codeweb mark-n, --node <NODE> (repeatable), -c, --csv <CSV> (required), -o, --output <FILE>Mark WDR SQL detail CSV rows by relation to graph nodes

Query and export

CommandKey optionsPurpose
codeweb query-f, --file <FILE> (- for stdin) or -s, --spec <JSON>Execute a declarative QuerySpec
codeweb export-f, --format dot&#124;json&#124;mermaid&#124;ndjson (default dot), -o, --output <FILE> (stdout if omitted), --filter <SUBSTR>Export the graph or the subgraph around matching seeds
codeweb dedup-o, --output <FILE> (default in-place), --dry-runMerge duplicate nodes and edges
codeweb import-f, --file <FILE>, -o, --output <FILE>, -p, --prefix <PREFIX>, -n, --name <NAME>, --forceImport a CGEF JSON file. See CGEF
codeweb merge-o, --output <FILE> (required), --name <NAME> (default merged), [STORES]...Merge multiple stores with dedup

Interactive and server

CommandFeatureKey optionsPurpose
codeweb tuitui-p, --projectTerminal explorer with search and node detail
codeweb serveserve-a, --addr (default 127.0.0.1:3000), --open, --log-level info&#124;debugHTTP server with browser UI. See HTTP API
codeweb mcpmcp-p, --projectMCP server over stdio. See MCP tools

Subcommands that need a feature flag are absent from binaries built without it; codeweb serve on a default build exits with an unrecognized-command error.

3 - Graph model

Node types, edge kinds, node keys, and the inferred/system markers used across CLI output and exports.

Node types

Every node carries a type tag in CLI output and all export formats. A * suffix is a qualifier whose meaning depends on the type: for table* / view* / seq* it means inferred (referenced by DML, no DDL definition found); for proc* / func* it means the procedure/function body could not be fully parsed.

TagMeaningNotes
proc / proc*Stored procedure* = incomplete body parse
func / func*Function* = incomplete body parse
table / table*Table* = referenced in DML, no DDL
view / view*View* = referenced in DML, no DDL
seq / seq*Sequence* = referenced, no DDL
pkgPackage
triggerTrigger
typeCustom type
indexIndex
mviewMaterialized view
synonymSynonym
eventEvent
builtinBuilt-in SQL functionSubtypes in JSON: builtin:func, builtin:op, builtin:hint, builtin:special
unresUnresolved referenceDynamic or unmatched call target
mapperMyBatis/iBatis mapped statement
methodJava method
classJava class
sqlSQL embedded in JavaFrom annotations or JDBC calls
jspJSP pageRequires the jsp feature
jspsqlSQL embedded in JSPRequires the jsp feature
customImported custom nodeCreated via CGEF import

Tables and views that live in known system schemas (pg_catalog, sys, dbe_*, …) or are well-known system names (dual, sys_dummy) are flagged system: true in JSON output; codeweb nodes --system filters for them.

Node keys

Nodes are identified by a NodeKey string that combines name, type, and location of origin:

  • SQL objects: type:schema.name (for example table:public.orders); routines include the package when defined in one.
  • Java methods: the fully qualified name including the class (com.example.OrderService.createOrder).
  • Mappers: namespace.id (com.example.OrderMapper.insertOrder).

Substring search in trace, detail, inspect, and impact matches against these keys. Use --exact for a case-insensitive exact match, --regex for regular expressions, and --fail-on-multiple to refuse ambiguous matches.

Edge kinds

EdgeConnectsMeaning
DirectCallprocedure → procedureStatic CALL / PERFORM
DynamicCallprocedure → unresolvedEXECUTE IMMEDIATE with a non-literal target
CallsProceduremapper / Java / JSP SQL → procedureSQL body calls a stored procedure
InvokesMapperJava method → mapped statementMapper id call or interface binding
CallsJavaSQL / procedure → Java methodOutbound call into Java
UsesBuiltinFunctionroutine → built-inCOUNT, SUBSTR, operators, hints
ContainsMethodclass → methodJava class structure
ContainsSqlJava method → JavaSqlMethod owns embedded SQL
Extends / Implementsclass → classJava inheritance
TableAccessroutine / statement → tableRead/write with access modes and write kinds
DependsOnnode → nodeStructural dependency (views, synonyms)
ContainsRoutinepackage → routinePackage body membership
TriggersRoutinetrigger → routineTrigger fires routine
ReferencesType / UsesSequence / IndexesTable / AliasesObjectroutine → objectDDL references
AnchorsOnroutine → table/column%TYPE / %ROWTYPE schema anchor; excluded from lineage, conflicts, and --summarize-tables
CustomEdgeany → anyImported via CGEF with a custom type name

For traversal, edges fold into five categories: call, composition, dataflow, reference, inheritance. These are the values accepted by codeweb impact --edge-types and by the edge_categories field of the query engine.

4 - Trace and query

Trace call chains, inspect reachability, compute impact, search by SQL fragment, and run declarative JSON queries.

Trace

codeweb trace <FROM> walks the full call chain around a node, printing callers and callees. Matching is substring-based on node keys by default.

codeweb trace "process_order"
codeweb trace "process_order" --style path     # flat path list instead of a tree
codeweb trace "t_order" --exact                # case-insensitive exact key match
codeweb trace "order.*insert" --regex          # regex over node keys
codeweb trace "calc" --all-matches             # every matching node
codeweb trace "calc" --fail-on-multiple        # refuse ambiguous matches
codeweb trace "trim" --builtfunc               # include built-in function calls (hidden by default)

Detail

codeweb detail <NAMES>... shows direct callers and callees per node, optionally with source context:

codeweb detail "calculate_total"
codeweb detail "calculate_total" --files          # list source files in the chain
codeweb detail "pkg_order" --summarize-tables     # aggregate R/W table access of a package
codeweb detail "v_order" --related-ddl            # include indexes, synonyms, triggers
codeweb detail "v_order" --verbose                # include DDL source text
codeweb detail "calculate_total" --depth -1       # unlimited traversal (default 1)

--depth accepts 1 (direct), 0 (target only), or -1 (unlimited).

Inspect

codeweb inspect finds directed paths that connect two or more nodes across all edge types:

codeweb inspect "createOrder" "pkg_payment"
codeweb inspect "createOrder" "pkg_payment" --max-depth 15 --max-paths 10
codeweb inspect "createOrder" "pkg_payment" --style tree
codeweb inspect "createOrder" "pgl_unused" --unreachable   # also show pairs with 0 paths

Impact

codeweb impact answers “what is affected by this change” — per file or per node. The two target flags are mutually exclusive:

# Everything upstream and downstream of a file's nodes (JSON, integrates with git diff hooks)
codeweb impact --file src/main/java/com/example/OrderMapper.java --format json

# A single symbol
codeweb impact --node "proc_create_order" --format text

# Widen traversal and restrict edge categories
codeweb impact --node "orders" --depth 2 --edge-types call,dataflow

--edge-types accepts all (default), call, dataflow, reference, composition, inheritance.

Search by SQL fragment

codeweb trace-sql searches mapper and sql nodes by SQL text (case-insensitive substring) and traces back to the invoking Java methods:

codeweb trace-sql "UPDATE inventory SET"
codeweb trace-sql --file fragment.sql     # read the fragment from a file (avoids shell quoting)
codeweb trace-sql - <<'EOF'
SELECT * FROM orders WHERE status = 'PENDING'
EOF

Deduplicate

codeweb dedup merges duplicate nodes and edges (for example a table seen both with and without DDL across phases):

codeweb dedup --dry-run          # preview only
codeweb dedup                    # in-place
codeweb dedup -o cleaned.bincode # write to a new store

Declarative queries

codeweb query runs a JSON QuerySpec against the graph. A spec has three parts: start (which nodes), steps (traversal), and collect (result shape).

codeweb query --spec '{"start":{"type":"proc","name":"order"},"collect":"nodes"}'
codeweb query --file spec.json
FieldValuesMeaning
starttype, name, schemaStarting node(s); all fields optional
steps[]{"action":"outgoing","edge_categories":[...],"max_depth":N}Follow outgoing edges
{"action":"incoming", ...}Follow incoming edges
{"action":"filter","type_tag":"table","schema":"public"}Keep matching nodes
{"action":"until","type_tag":"table"}Stop traversal at a node type
collectnodes (default), paths, subgraphResult shape

edge_categories accepts call, composition, dataflow, reference, inheritance — see Edge kinds. The same spec format works over HTTP (POST /api/v1/query) and MCP (codeweb_query), so one spec serves CLI, scripts, and LLM clients.

5 - Lineage

Table-level and column-level lineage with upstream, downstream, and bidirectional modes, plus export to tree, JSON, DOT, and Mermaid.

Run lineage

codeweb lineage <TARGET> computes how data reaches — and leaves — a table or column:

codeweb lineage "orders"                                   # table-level
codeweb lineage "orders.status"                            # column-level
codeweb lineage "public.orders.status"                     # schema-qualified column
codeweb lineage "table:public.orders"                      # node-key grammar, same as trace/detail

Options:

codeweb lineage "orders" --direction upstream    # who writes/defines it
codeweb lineage "orders" --direction downstream  # who consumes it
codeweb lineage "orders" --depth 5               # recursion depth (default 5)
codeweb lineage "orders" --flow-only             # hide reference-only sources

--direction accepts upstream, downstream, or both (default).

Output formats

codeweb lineage "orders" --format json      # machine-readable
codeweb lineage "orders" --format dot > lineage.dot
codeweb lineage "orders" --format mermaid   # markdown-embeddable

--format dot and --format mermaid export the entity subgraph. The default --format tree supports four renderings via --view:

ViewRendering
tree (default)Indented lineage tree
entityEntities only, no processes
relationExplicit source──process──▶target lines
groupedBranches grouped by connecting process

Tune flow detection

With --flow-only, codeweb hides sources that only reference a table without moving data. The thresholds live in codeweb.toml:

[lineage]
# minimum column overlap and ratio for a flow edge to count

The [lineage] section exposes flow thresholds (flow_min_overlap, flow_min_ratio defaults apply unless overridden).

Column-level analysis

Lineage answers “where does this column come from”. For the inverse question — “which filters, joins, and mappings does a procedure apply to its tables” — use the column analysis commands codeweb columns and codeweb predicates. The HTTP equivalent is GET /api/v1/lineage; the MCP equivalent is codeweb_lineage.

6 - Column analysis

Aggregate filters, joins, SELECT INTO mappings, and predicates per procedure or package — the machine-readable entry point for test-data and mock generation.

Aggregate per procedure

codeweb columns exports, per procedure or package: hard filters, join conditions, SELECT INTO mappings, and enum/column mappings. Exactly one of --procedure or --package is required:

codeweb columns --procedure "proc_create_order" --format json
codeweb columns --package "pkg_order" --format json
codeweb columns --package "pkg_order" --table "orders" --format json   # narrow to one table

Output is JSON (schema from issue #165). --procedure and --package use the same substring matching as trace; matching more than one node fails the command.

Seed hints

--format seed-hints (issue #181) renders a table-requirements inventory for generating test data: involved tables with per-table operations, the routine signature, hard filters, cross-table equalities, and discriminator values. Each entry carries provenance and confidence.

codeweb columns --procedure "proc_create_order" --format seed-hints
codeweb columns --procedure "proc_create_order" --format seed-hints \
  --discriminator "operation_no"
  • --discriminator names a column whose literal values are enumerated as discriminator_values. The flag is repeatable and overrides the discriminator_columns list from codeweb.toml:
[analysis]
discriminator_columns = ["operation_no"]

By default the list is empty: codeweb has no built-in domain knowledge, so a project opts in explicitly.

Predicates

codeweb predicates --procedure <NAME> resolves PL IF/CASE conditions to table columns and outputs JSON:

codeweb predicates --procedure "proc_create_order" --format json

--format json is the only supported value today.

Mark WDR report rows

codeweb mark annotates rows of a WDR SQL detail CSV with their relation to a target graph node — useful for tying slow-SQL reports back to procedures and mappers:

codeweb mark --csv wdr_sql_detail.csv --node "proc_create_order" -o marked.csv
codeweb mark --csv wdr_sql_detail.csv --node "orders" --node "pkg_order"   # multiple targets, stdout

Interfaces

The aggregated column analysis is exposed on every surface:

  • CLI: codeweb columns, codeweb predicates
  • HTTP: GET /api/v1/columns?procedure=...|package=...[&table=...]
  • MCP: codeweb_column_analysis (same JSON schema as the CLI)

7 - CGEF import and merge

Import external graph data in the Codeweb Graph Exchange Format and merge it with locally analyzed stores.

Why CGEF

CGEF (Codeweb Graph Exchange Format) is the JSON format for graph data produced outside of codeweb — for example, call relationships of a private ERP system whose source cannot be scanned. Import it as a standalone store, merge it with local analysis, and trace chains across the boundary.

Document structure

A CGEF document is a JSON file with these top-level fields:

{
  "format_version": 1,
  "metadata": {
    "source": "erp-system",
    "generated_at": "2026-04-28T10:00:00Z"
  },
  "node_schemas": {},
  "edge_schemas": {},
  "nodes": [],
  "edges": []
}
FieldRequiredMeaning
format_versionyesFormat version; currently 1
metadatayessource identifier and ISO 8601 generated_at
node_schemasnoDeclarations for custom node types
edge_schemasnoDeclarations for custom edge types
nodesyesNode array (may be empty)
edgesyesEdge array (may be empty)

Standard node types cover all built-in codeweb objects (procedure, function, table, view, mapped_statement, java_method, java_class, java_sql, package, trigger, type, sequence, index, materialized_view, …). The full per-type key fields are specified in the CGEF user guide and the JSON Schema.

Custom types

Node or edge types that have no built-in equivalent are declared in node_schemas / edge_schemas (display name, key fields, property definitions). Their edges import as CustomEdge and their nodes with tag custom, so they behave like first-class nodes in trace, impact, and export.

Import

codeweb import --file enterprise-graph.json --output erp-store.bincode
codeweb import --file enterprise-graph.json --output erp.json --prefix "/opt/erp/src" --name "erp"
codeweb import --file broken.json --output erp.bincode --force
FlagMeaning
--fileCGEF JSON input
--outputOutput store: .bincode or .json
--prefixPath prefix prepended to all relative file paths
--nameProject name for the imported store
--forceImport even when validation or parse errors are found

Merge

codeweb merge -o full-graph.bincode my-project.bincode erp-store.bincode
codeweb merge -o full-graph.bincode --name "combined" my-project.bincode erp-store.bincode

Merging deduplicates nodes and edges across stores, so the same table analyzed locally and imported via CGEF collapses into one node. The merged store behaves like any local store for trace, serve, and export.

View the full guide

The Chinese guide docs/cgef-user-guide.md walks through a complete worked example, including the OP Excel lineage converter (lib/op-lineage.py).

8 - HTTP API

The serve feature — browser UI, REST endpoints under /api/v1, CORS, and access logging.

Start the server

Built with the serve feature, codeweb serve loads the project store and starts an HTTP server with an embedded browser UI:

cargo build --release --features serve
codeweb serve --addr 127.0.0.1:3000 --open
FlagDefaultMeaning
-p, --project.Project directory
-a, --addr127.0.0.1:3000Bind address (host:port)
--openoffOpen the browser after startup
--log-levelinfoAccess log level: info or debug

The UI offers a node list with search, a Cytoscape.js graph canvas with dagre layout, and a detail panel with callers/callees. Requests are CORS-permissive and logged to .codeweb/ in the project directory.

REST endpoints

All endpoints live under /api/v1 and return JSON unless noted.

MethodPathParametersDescription
GET/api/v1/stats—Node counts by type, edge count, project name
GET/api/v1/files—Analyzed files with node counts
GET/api/v1/nodessearch, node_type, orphan, low_degree, limit (default 100), offset (default 0)Filter and paginate node summaries; search sorts by match rank
GET/api/v1/nodes/:id—Node properties, direct callers, callees
GET/api/v1/nodes/:id/callerslimit, offset, depthUpstream neighbors
GET/api/v1/nodes/:id/calleeslimit, offset, depthDownstream neighbors
GET/api/v1/nodes/search-sqlq (required)Search mapper/sql nodes by SQL content, scored
GET/api/v1/tracefrom (required), depth (default 2, capped at 10), max_nodes (default 500)Bidirectional call chain trees; response reports truncated
GET/api/v1/columnsexactly one of procedure, package; optional tableAggregated column analysis (issue #165 JSON)
GET/api/v1/lineagetarget (required), direction (upstream/downstream/both), depth (default 5)Table/column lineage
POST/api/v1/querybody: QuerySpec JSONDeclarative traversal
GET/api/v1/exportformat: dot, json, ndjson, mermaidDownload the graph
GET/api/v1/graph—Full graph payload used by the browser UI canvas

Status codes follow the convention: 404 when a name matches nothing, 400 for ambiguous names or invalid parameters (for example passing both procedure and package to /api/v1/columns).

Examples

codeweb serve -p my-project --addr 127.0.0.1:3000 &

curl -s http://127.0.0.1:3000/api/v1/stats
curl -s "http://127.0.0.1:3000/api/v1/nodes?search=order&node_type=proc&limit=10"
curl -s "http://127.0.0.1:3000/api/v1/trace?from=process_order&depth=3"
curl -s "http://127.0.0.1:3000/api/v1/lineage?target=orders&direction=upstream"
curl -s "http://127.0.0.1:3000/api/v1/nodes/search-sql?q=UPDATE%20inventory"
curl -s -X POST http://127.0.0.1:3000/api/v1/query \
  -H 'Content-Type: application/json' \
  -d '{"start":{"type":"proc","name":"order"},"collect":"paths"}'
curl -s "http://127.0.0.1:3000/api/v1/export?format=ndjson" -o graph.ndjson

Security boundaries

The server reads the project store and binds the address you give it. It does not authenticate requests, and CORS is fully permissive, so treat it as a local development tool: do not expose it to untrusted networks. Read paths may point anywhere under analysis.paths; the serve mode has no write endpoints.

9 - MCP tools

Run codeweb as a Model Context Protocol server and query the graph from Claude Desktop, Cursor, or any MCP client.

Start the MCP server

Built with the mcp feature, codeweb mcp speaks JSON-RPC over stdio:

cargo build --release --features mcp
codeweb mcp --project /path/to/your/project

Register it in an MCP client, for example Claude Desktop’s claude_desktop_config.json:

{
  "mcpServers": {
    "codeweb": {
      "command": "/path/to/codeweb",
      "args": ["mcp", "--project", "/path/to/your/project"]
    }
  }
}

Lifecycle

The server starts even when the directory has no codeweb.toml yet: queries then return status: "uninitialized" instead of the process exiting.

  1. codeweb_init writes codeweb.toml and .codeweb/ under the served directory. It never analyzes on its own.
  2. codeweb_analyze builds or incrementally refreshes the graph and hot-swaps it into the running server, so later queries see the new graph without a restart.
  3. codeweb_diff lists files added, modified, or deleted since the last analysis.

Tools

ToolParametersDescription
codeweb_initname (optional, defaults to directory name), paths (optional, defaults to ["."])Initialize the project; no analysis
codeweb_analyze—Build/refresh the graph and hot-swap it in
codeweb_diff—Changes since the last analysis
codeweb_stats—Node counts by type, edge count, status; call this first
codeweb_nodessearch, node_type, limit, offsetList nodes with filtering and pagination
codeweb_node_detailids (list), depth (1 direct, 0 unlimited, N hops)Properties, callers, callees
codeweb_tracefrom, depth, max_nodesBidirectional call chain as nested trees
codeweb_search_sqlsqlSearch mapper/sql nodes by SQL text with relevance scoring
codeweb_queryspecExecute a QuerySpec
codeweb_column_analysisprocedure or package (exactly one), table (optional)Same JSON schema as codeweb columns --format json
codeweb_lineagetarget, direction, depthSame functions and JSON shape as codeweb lineage --format json

Security boundaries

Reads may point at any directory listed in analysis.paths, but every write is confined to the served directory: a tampered store.path that escapes it is rejected. The server exposes no shell execution and no file-write tools beyond the lifecycle above.

10 - Architecture

How codeweb is built — parsing pipeline, graph store, feature flags, module map, and extension points.

Pipeline

scan (globset) → load (encoding detection) → parse (rayon, parallel)
      │                │                          │
      │           SQL: ogsql-parser          relationships
      │           XML: iBatis loader         as (caller, callee, Edge)
      │           Java: tree-sitter-java           │
      │           JSP: preprocess to Java          ▼
      ▼                                    GraphBuilder
  fingerprints (blake3)                            │
 (incremental re-parse)                            ▼
                                         GraphStore (petgraph)
                                                │        │
                                     bincode on disk    in-memory index
                                                     │         │          │
                                                 CLI/TUI   serve (axum)  mcp (rmcp)
                                                              │
                                                   export: dot / json / mermaid / ndjson
  1. Scan — parser/scanner.rs discovers files through the configured include paths and excludes.
  2. Parse — parser/extractor.rs fans out over a rayon thread pool. SQL goes through ogsql-parser (openGauss/GaussDB dialect), mapper XML through its iBatis loader, Java through tree-sitter-java, and JSP through a preprocessor that synthesizes Java and reuses the Java SQL extraction.
  3. Build — graph/builder.rs turns relationships into nodes and edges, resolving names to schema/package-qualified keys and marking unreferenced DML targets as inferred (*) nodes.
  4. Store — graph/store.rs keeps the graph in a petgraph graph with query indexes, serializes to bincode under .codeweb/, merges and dedups stores, and supports incremental re-parse via blake3 fingerprints.
  5. Serve — the same store backs the CLI/TUI, the axum HTTP server, and the rmcp MCP server.

Feature flags

FeatureEnablesDefault
cliclap-based command lineyes
tuiratatui + crossterm terminal UIyes
javatree-sitter-java extraction plus ogsql-parser’s Java SQL extractionyes
jspJSP scriptlet/declaration/expression SQL extraction (implies java and the ogsql-parser ibatis feature)yes
serveaxum HTTP server, browser UI (rust-embed), access logno
mcprmcp MCP server with schemars-generated tool schemasno
analyzeLibrary-only build shape (no CLI/TUI/serve/MCP) used to embed analysis into other Rust applicationsno
search-sql-v2Activates the search-sql-v2 test suite for enhanced token-normalized SQL matching; today it changes tests, while runtime search is identical in every buildno
fullEverything aboveno

Feature composition matters at runtime: binaries built without serve or mcp lack those subcommands entirely. The default build already extracts SQL from Java and JSP; only the server surfaces are opt-in.

Module map

ModuleResponsibility
src/main.rsclap entry point and command dispatch
src/parser/File scanning, loading, and relationship extraction (extractor.rs, ibatis_loader.rs, java_loader.rs, java_method.rs, jsp_loader.rs, jsp_preprocessor.rs, fingerprint.rs)
src/graph/Graph model: store.rs (GraphStore, indexes, dedup, merge), builder.rs, traverse.rs, lineage.rs, cluster.rs, columns.rs, conflict.rs, key.rs; query/ (QuerySpec engine), search/ (fuzzy + SQL search)
src/export/dot.rs, json.rs, mermaid.rs, ndjson.rs
src/import/CGEF document model, parser, validator, custom schema registry, path prefix mapper
src/server/axum router, handlers, state, embedded UI assets, access log (serve)
src/mcp/MCP server entry and tool definitions (mcp)
src/tui/Terminal UI app, theme (tui)
src/project/codeweb.toml loading and project lifecycle
locales/rust-i18n catalogs at the repository root (en, zh-CN)

Extension points

  • New source language: add a loader under src/parser/ that emits relationships as (caller, callee, Edge) triples, then feed them to the graph builder — the JSP loader is the worked example (it preprocesses to synthetic Java and reuses the Java extraction).
  • External graphs: produce CGEF JSON from any tool and codeweb import it; custom node and edge types become first-class custom nodes and CustomEdge edges.
  • Automation: drive the same store from scripts via the REST API, the MCP tools, or codeweb query with JSON specs.

Known limitations

  • Dynamic SQL (EXECUTE IMMEDIATE with a non-literal string) becomes a DynamicCall edge to an unres node; codeweb resolves what is statically visible and marks the rest as unresolved rather than guessing.
  • JSP extraction reuses the Java SQL keyword gate, so JDBC escape calls such as {call pkg.x(...)} in scriptlets are filtered out today; direct stored-procedure calls from JSP need a follow-up post-processor.
  • The openGauss/GaussDB parser accepts the target dialect; other vendor dialects may parse partially or fail.
  • codeweb analyzes static source only: runtime configuration, reflection-based dispatch, and dynamically assembled SQL appear only to the extent they are literal in the code.

11 - Contributing

Development workflow, test discipline, and the pre-commit gates for codeweb.

Repository layout

codeweb is a single Rust crate with feature-gated surfaces (cli, tui, serve, mcp, jsp, java, analyze, search-sql-v2; full combines them). There is no workspace: check which module and feature your change touches first. SQL parsing lives in the separate ogsql-parser crate.

Test discipline

The repository follows test-driven development, one behavior per loop:

  1. Red — write a failing behavior test first. A compile error from a not-yet-existing API counts as red.
  2. Green — write the minimal implementation that passes; do not widen assertions to get there.
  3. Refactor — only with the tests green, scoped to the change path.

Rules that reviewers enforce:

  • Never delete, skip, or weaken existing tests to make changes pass.
  • Test names describe behavior (should_reject_negative_amount).
  • Characterization tests lock current behavior of legacy paths before changing them.
  • Fix the implementation when your change breaks an existing test, unless the human who wrote it says otherwise.

Pre-commit gates

Match CI exactly:

cargo fmt --all -- --check
cargo clippy --features full -- -D warnings
cargo test --features full -- --skip test_path_mapping_applied --skip test_serve_
  • cargo build --features full must compile whenever a change can affect feature-gated code (new enum variants matched in other features, for example).
  • The skipped tests are environment-dependent in CI by design; a bare cargo test --features full failing on test_serve_* locally is a known limitation, so confirm your change did not make it worse.

Submitting changes

  1. Create a feature branch from main.
  2. Commit with the gates green.
  3. Push and open a pull request.
  4. A maintainer reviews and merges; contributors do not merge their own pull requests.