CodeGraph 0.7.0

dotnet tool install --global CodeGraph --version 0.7.0
                    
This package contains a .NET tool you can call from the shell/command line.
dotnet new tool-manifest
                    
if you are setting up this repo
dotnet tool install --local CodeGraph --version 0.7.0
                    
This package contains a .NET tool you can call from the shell/command line.
#tool dotnet:?package=CodeGraph&version=0.7.0
                    
nuke :add-package CodeGraph --version 0.7.0
                    

CodeGraph

Give your AI coding agents structural code understanding instead of grep.

CI NuGet License: MIT .NET 8+ | 10

CodeGraph is a Roslyn-powered CLI tool that builds a semantic graph of your C# codebase and writes it as JSON — queryable by LLM agents. Instead of dumping thousands of grep matches into a prompt, your AI assistant gets the actual dependency structure, call chains, and type hierarchy.


Why CodeGraph?

Before — your AI assistant runs grep "OrderService" and gets 200+ hits:

src/Orders/OrderService.cs:14:public class OrderService : IOrderService
src/Orders/OrderService.cs:28:    public async Task<Order> PlaceOrder(...)
src/Api/Startup.cs:42:services.AddScoped<IOrderService, OrderService>();
src/Api/Controllers/OrderController.cs:18:    private readonly IOrderService _orderService;
tests/Orders/OrderServiceTests.cs:12:public class OrderServiceTests
... 195 more results

Aftercodegraph query OrderService --depth 1 --format context returns the actual structure:

# Query: OrderService
Commit: abc1234 | Branch: main | 2026-01-15T10:30:00Z

## Target: MyApp.Services.OrderService (Type)
File: src/Orders/OrderService.cs [14–87]
Signature: public class OrderService : IOrderService
Accessibility: Public

### Outgoing Relationships
**Implements:**
  → IOrderService

**Calls:**
  → IOrderRepository.SaveAsync(Order)
  → IEventBus.PublishAsync(OrderPlacedEvent)

**DependsOn:**
  → Order
  → OrderRequest

### Incoming Relationships
**Calls:**
  ← OrderController.PlaceOrder(OrderRequest)

**ResolvesTo:**
  ← IOrderService (via DI)

**Covers:**
  ← OrderServiceTests.PlaceOrder_ShouldPublishEvent

Your AI assistant gets a focused, structured view — not a wall of text.


Quick Start

# Install as a global .NET tool
dotnet tool install -g CodeGraph

# In your repo — initialize config + MCP registration:
codegraph init
# → Creates codegraph.json, .vscode/mcp.json, .mcp.json, apm.yml

# Build the graph:
codegraph index --solution MyApp.sln

# Query the graph:
codegraph query PlaceOrder --depth 1
codegraph query IOrderRepository --kind resolves-to
codegraph query "Order*" --format json --depth 2

After codegraph init, AI agents that support MCP (VS Code Copilot, Claude Code, Cursor) will auto-discover codegraph_query as a tool — no configuration needed.

Output

The index command writes JSON files to .codegraph/:

  • One file per assembly/project — sized for LLM context windows
  • _external.json — SBOM-like graph of all external/NuGet dependencies
  • meta.json — git metadata, statistics, and index timestamp

The query command reads those files and returns a focused subgraph.


CLI Reference

codegraph init

Auto-detect your solution, create config + MCP server registration files, and scaffold agent skill files.

codegraph init [--agent <name>] [--solution <path.sln|path.slnx>] [--output <dir>] [--force]

Step 1 — Config + MCP files (always):

  • codegraph.json — index/query configuration
  • .vscode/mcp.json — MCP server for VS Code Copilot / Cursor
  • .mcp.json — MCP server for Claude Code
  • apm.yml — MCP server for APM (Agent Package Manager)

Step 2 — Agent skill files (auto-detected or explicit):

Auto-detects which AI agents are configured in the repo (looks for .claude/, CLAUDE.md, .github/copilot-instructions.md, AGENTS.md, .cursorrules, .cursor/rules/), then writes agent-specific skill files so each agent understands how to use CodeGraph:

Agent Detection File(s) written
Claude Code .claude/ dir or CLAUDE.md .claude/skills/codegraph/SKILL.md, .claude/skills/codegraph/scripts/query-wrapper.sh
GitHub Copilot .github/copilot-instructions.md Appends CodeGraph section to .github/copilot-instructions.md
OpenCode / Codex AGENTS.md Appends CodeGraph section to AGENTS.md
Cursor .cursorrules or .cursor/rules/ .cursor/rules/codegraph.md
(all agents) .codegraph/INSTRUCTIONS.md (generic instructions, always written)
Flag Description
--agent <name> Skip auto-detection and install for a specific agent: claude, copilot, opencode, cursor, all
--solution <path> Combine init + index in one step
--output <dir> Output directory for graph data (default: .codegraph)
--force Overwrite existing skill files

codegraph index

Build the semantic graph from your C# solution.

codegraph index --solution <path.sln|path.slnx> [options]
Flag Description Default
--solution <path> Path to .sln or .slnx file From codegraph.json
--output <dir> Output directory for graph files .codegraph
--projects <filter> Wildcard filter for project names All projects
--config <path> Path to codegraph.json config Auto-detected
--configuration <name> Build configuration Debug
--skip-restore Skip dotnet restore step false
--skip-build Hidden alias for --skip-restore false
--changed-only Incremental re-index; only re-index projects with changes since last indexed commit false
--sequential Disable parallel multi-solution indexing (recommended on machines with < 16 GB RAM) false
--verbose Enable verbose output false

codegraph query

Query the graph for symbols, relationships, and dependencies.

codegraph query <symbol-pattern> [options]

Symbol patterns support wildcards (Order*, *Service), exact match (OrderService), and kind prefix (type:OrderService, method:PlaceOrder).

Flag Description Default
--depth <n> BFS traversal depth 1
--kind <type> Edge filter (see table below) All kinds
--mode <mode> Traversal mode: focused (high-signal edges only), structural (includes containment), all all
--namespace <pattern> Namespace filter (supports wildcards) All namespaces
--project <name> Project filter All projects
--format <fmt> Output format: json, text, context, compact context
--max-nodes <n> Maximum nodes in result 50
--include-external Include external assembly dependencies false
--no-rank Disable relevance ranking (ranking enabled by default)
--budget <tokens> Maximum token budget; output is truncated with a hint when exceeded (none)
--no-metrics Suppress the compression metrics footer false
--graph-dir <dir> Graph directory .codegraph
--from <solution> Scope query to a specific solution sub-graph (multi-solution only) All solutions

Output formats:

Format Description
context Markdown-like, optimized for LLM prompts (default)
compact Compressed prefix-stripped format, 3–5× smaller than context
text Human-readable tabular summary
json Machine-readable full QueryResult

Edge kind aliases:

Alias EdgeType
calls, calls-to, calls-from Calls
inherits Inherits
implements Implements
depends-on DependsOn
resolves-to ResolvesTo
covers Covers
covered-by CoveredBy
references References
overrides Overrides
contains Contains
all No filter

codegraph diff

Compare two graph snapshots and report structural changes.

codegraph diff [options]
Flag Description Default
--base <dir> Base graph snapshot directory .codegraph-prev
--head <dir> Head graph snapshot directory .codegraph
--ref <git-ref> Use .codegraph-<ref> as base snapshot (none)
--only <types> Comma-separated: added, removed, signature-changed, added-nodes, removed-nodes, added-edges, removed-edges All change types
--format <fmt> Output format: json, text, context context

See docs/diff.md for the full how-to guide.

codegraph list

Browse the code graph hierarchy — enumerate assemblies, types, interfaces, or namespaces without writing a query.

codegraph list [scope] [options]
Scope Description
assemblies All assemblies with type/method counts (default)
types Types ranked by connectivity (in + out degree)
interfaces Interfaces with implementation counts
namespaces Namespaces with type and method counts
Flag Description Default
--assembly <name> Filter by assembly name (applies to types, interfaces, namespaces) All
--top <n> Maximum items to return (applies to types only) 20
--graph-dir <path> Graph directory .codegraph
codegraph list                              # List all assemblies
codegraph list types                        # Most-connected types across all assemblies
codegraph list types --assembly MyApp.Core  # Types in a specific assembly
codegraph list interfaces --top 10          # Top 10 most-implemented interfaces
codegraph list namespaces                   # All namespaces

See docs/list.md for the full guide, including output format details and orientation workflows.

codegraph stats

Print a quick overview of the graph: total node and edge counts, broken down by kind and type.

codegraph stats [options]
Flag Description Default
--graph-dir <dir> Graph directory .codegraph
codegraph stats                          # Stats for .codegraph/
codegraph stats --graph-dir .codegraph-prev  # Stats for an older snapshot

Example output:

CodeGraph Statistics
  Total nodes: 1 842
  Total edges: 5 219

Nodes by kind:
  Method: 982
  Type: 421
  Property: 287
  ...

Edges by type:
  Calls: 2 104
  Contains: 1 388
  References: 901
  ...

See docs/stats.md for common workflows including CI monitoring and snapshot comparison.

codegraph report

Generate a Markdown report that summarises the graph: hub types (highest connectivity), assembly boundaries, test coverage by assembly, and suggested starter queries.

codegraph report [options]
Flag Description Default
--graph-dir <dir> Directory containing graph.db .codegraph
--output, -o <path> Output file path .codegraph/REPORT.md
codegraph report                         # Write .codegraph/REPORT.md
codegraph report -o docs/report.md       # Write to a custom path
codegraph report --graph-dir .codegraph-prev  # Report on an older snapshot

Tip: codegraph index automatically generates REPORT.md after every successful index run, so agents always have a fresh overview on first use.

See docs/report.md for the full guide, including report sections, CI usage, and sharing with GitHub Wiki.

codegraph wiki

Generate a navigable Markdown wiki from the graph. Useful for publishing auto-generated architecture documentation to GitHub Wiki or any docs site.

codegraph wiki [options]
Flag Description Default
--graph-dir <dir> Graph directory .codegraph
--output, -o <dir> Output directory .codegraph/wiki

The generator creates:

File Content
INDEX.md Graph summary, assembly list, top hub types
assemblies/<name>.md Per-assembly: types, methods, DI registrations, test coverage
INTERFACES.md All interfaces with their implementations
DI-WIRING.md Dependency-injection registrations and resolved types
codegraph wiki                           # Generate .codegraph/wiki/
codegraph wiki -o docs/wiki              # Publish to a docs directory
codegraph wiki --graph-dir .codegraph-prev  # Wiki from an older snapshot

See docs/wiki.md for the full guide, including generated file structure, GitHub Wiki publishing, and CI integration.

codegraph export

Export the graph from its SQLite database (graph.db) back to JSON files. Useful for tooling that consumes the JSON format or for archiving a snapshot.

codegraph export [options]
Flag Description Default
--graph-dir <dir> Directory containing graph.db .codegraph
--output <dir> Output directory for JSON files export
codegraph export                         # Export .codegraph/graph.db → export/
codegraph export --output my-snapshot    # Export to a named directory

See docs/export.md for the full guide, including archiving, CI artifact publishing, and jq examples.

codegraph mcp

Start an MCP (Model Context Protocol) stdio server. This is how AI agents discover and use CodeGraph as a native tool.

codegraph mcp [--graph-dir <dir>]
Flag Description Default
--graph-dir <dir> Graph directory .codegraph

The server exposes six tools. Agents call them like any other tool (no shell commands, no prompt engineering). The server starts on demand via stdio and exits when the agent disconnects.

MCP Tool Description
codegraph_query Query the graph by symbol pattern with depth, edge-type, and format options
codegraph_list Browse the graph hierarchy (assemblies, types, interfaces, namespaces)
codegraph_summary Generate an overview report: hub types, assembly boundaries, test coverage
codegraph_path Find the shortest dependency path between two symbols
codegraph_impact Reverse-dependency analysis — assess the blast radius of a change
codegraph_explain Full symbol deep-dive: signature, members, all edges, test coverage

See docs/mcp.md for the full guide, including per-agent configuration and troubleshooting.

codegraph view

Generate an interactive 3D graph visualization as a self-contained HTML file and open it in the default browser.

codegraph view [options]
Flag Description Default
--graph-dir <path> Graph directory .codegraph
--output <path> Write HTML to a specific file instead of a temp file (temp file)
--max-nodes <n> Maximum nodes to render (smart-sampled when exceeded) 5000
--no-open Generate HTML but do not open in browser false
codegraph view                              # Open graph in browser
codegraph view --output graph.html          # Save to file
codegraph view --max-nodes 2000             # Limit for performance
codegraph view --graph-dir .codegraph/Api   # View specific sub-graph

See docs/view.md for the full how-to guide, including sidebar controls, node sampling, and CI usage.

Configuration is automaticcodegraph init generates the MCP config files. To add manually:

// .vscode/mcp.json (VS Code Copilot, Cursor)
{
  "servers": {
    "codegraph": {
      "type": "stdio",
      "command": "dotnet",
      "args": ["codegraph", "mcp"],
      "cwd": "${workspaceFolder}"
    }
  }
}
// .mcp.json (Claude Code)
{
  "mcpServers": {
    "codegraph": {
      "command": "dotnet",
      "args": ["codegraph", "mcp"]
    }
  }
}

Agent Integration

codegraph init generates the MCP config files automatically. The agent sees codegraph_query as a native tool.

Agent Config File Auto-generated
VS Code Copilot .vscode/mcp.json ✅ by codegraph init
Cursor .vscode/mcp.json ✅ by codegraph init
Claude Code .mcp.json ✅ by codegraph init
APM apm.yml ✅ by codegraph init

Agent Skills (skills.sh)

CodeGraph provides packaged agent skills compatible with the skills.sh ecosystem. Install all skills with:

npx skills add droosma/vibe-codeGraph

Or install individual skills:

Skill Purpose Install
codegraph-query Query the semantic graph for structural relationships npx skills add droosma/vibe-codeGraph@codegraph-query
codegraph-index Index or re-index a C# codebase npx skills add droosma/vibe-codeGraph@codegraph-index
codegraph-review Impact analysis for code review npx skills add droosma/vibe-codeGraph@codegraph-review

Each skill includes a standalone SKILL.md with trigger phrases, CLI reference, examples, and best practices. See the skills/ directory for details.

APM (Agent Package Manager) Support

CodeGraph supports Microsoft APM for managing agent configuration. If you use APM, run:

apm install --mcp codegraph -- dotnet codegraph mcp

Or use the apm.yml generated by codegraph init and run apm install to wire CodeGraph into all detected agent clients.

See docs/agent-setup.md for detailed per-agent instructions.


Configuration

CodeGraph is configured via a codegraph.json file in your repo root. Run codegraph init to generate one, or see the full reference at docs/configuration.md.

Section Controls
solution Path to a single .sln or .slnx file
solutions Array of solution entries for multi-solution mono-repos
output Graph output directory (default: .codegraph)
splitBy File split strategy: project (default) or assembly (both are assembly-based), or namespace
index Project filtering, build configuration, external packages
ioc IoC/DI container resolution settings
tests Test discovery patterns
docs Documentation extraction
query Default query parameters

See codegraph.json.example for a single-solution example, or codegraph.multi-solution.json.example for a multi-solution example.


How It Works

┌─────────────┐     ┌──────────────┐     ┌──────────────┐     ┌───────────┐
│ dotnet       │────▸│ Syntax Pass  │────▸│ Semantic Pass │────▸│ JSON Graph│
│ restore +    │     │ (structure)  │     │ (relations)  │     │ (per-asm) │
│ Hybrid       │     └──────────────┘     └──────────────┘     └───────────┘
└─────────────┘           │                     │                    │
                          │              ┌──────────────┐            ▼
                          │              │   DI Pass    │     ┌─────────────┐
                          │              │ (ResolvesTo) │     │ _external   │
                          │              └──────────────┘     │   (SBOM)    │
                          │              ┌──────────────┐     └─────────────┘
                          │              │ Test Pass    │            │
                          │              │  (Covers)    │            ▼
                          │              └──────────────┘     ┌─────────────┐
                          └──────────────────────────────────▸│ Query Engine│
                                                              │ (BFS + rank)│
                                                              └─────────────┘
  1. Hybrid Workspace Loader — Runs dotnet restore, then parses .sln / .slnx / .csproj / project.assets.json to assemble Roslyn CSharpCompilation objects directly (no MSBuildWorkspace). If the restore fails, a warning is emitted to stderr and indexing continues with best-effort compilation.
  2. Syntax Pass — Walks syntax trees to extract namespaces, types, methods, properties, fields, constructors, and events. Creates structural Contains edges. Enriches nodes with metadata (isAbstract, isStatic, isAsync, returnType, etc.).
  3. Semantic Pass — Uses the Roslyn semantic model to resolve calls, inheritance, interface implementations, type dependencies, references, and overrides. Creates external nodes for cross-assembly references.
  4. DI Pass — Detects AddScoped/AddTransient/AddSingleton patterns to emit ResolvesTo edges with lifetime metadata.
  5. Test Coverage Pass — Detects test methods (xUnit, NUnit, MSTest) and emits Covers/CoveredBy edges linking tests to production code.
  6. Graph Writer — Outputs JSON files split by assembly (one per project), external nodes to _external.json (SBOM), plus meta.json with git metadata and statistics.
  7. Query Engine — Pattern-matches symbols, performs BFS traversal, filters by edge type/namespace/project, ranks by relevance, and formats output.

For a deep dive, see docs/architecture.md.


CI/CD Integration

Keep your graph fresh in CI

- name: Update CodeGraph
  run: |
    dotnet tool install -g CodeGraph
    codegraph index --solution MyApp.sln --changed-only

Publishing a new release

Push a version tag to trigger the NuGet publish workflow:

git tag v0.1.0
git push origin v0.1.0

This runs .github/workflows/publish.yml which builds, tests, packs, and pushes to NuGet.org. You'll need to add a NUGET_API_KEY secret to your GitHub repository.


Contributing

We welcome contributions! See CONTRIBUTING.md for development setup, code style, and PR guidelines.

Running Tests

# Unit tests
dotnet test

# Mutation testing (requires dotnet-stryker tool)
dotnet tool restore
cd tests/CodeGraph.Core.Tests && dotnet stryker
cd tests/CodeGraph.Indexer.Tests && dotnet stryker
cd tests/CodeGraph.Query.Tests && dotnet stryker

Stryker generates HTML reports in StrykerOutput/ with mutation scores per project. The CI pipeline runs mutation testing automatically on PRs that touch src/ or tests/.


Documentation


License

MIT © 2026 CodeGraph Contributors

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

Version Downloads Last Updated
0.7.0 104 5/11/2026
0.6.0 93 5/11/2026
0.5.0 101 5/8/2026
0.4.0 97 5/8/2026
0.3.0 110 5/8/2026
0.2.2 86 5/7/2026
0.2.1 78 5/7/2026
0.2.0 83 5/7/2026
0.1.4 102 4/24/2026
0.1.3 100 4/22/2026
0.1.2 112 4/16/2026
0.1.1 100 4/16/2026
0.1.0 103 4/16/2026

Initial release: Roslyn indexer, query engine, MCP stdio server with auto-detect framing (VS Code + Claude Code).