CodeGraph 0.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet tool install --global CodeGraph --version 0.2.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.2.0
                    
This package contains a .NET tool you can call from the shell/command line.
#tool dotnet:?package=CodeGraph&version=0.2.0
                    
nuke :add-package CodeGraph --version 0.2.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
--namespace <pattern> Namespace filter (supports wildcards) All namespaces
--project <name> Project filter All projects
--format <fmt> Output format: json, text, context 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)
--graph-dir <dir> Graph directory .codegraph
--from <solution> Scope query to a specific solution sub-graph (multi-solution only) All solutions

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

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 one tool — codegraph_query — with a typed JSON schema. Agents call it like any other tool (no shell commands, no prompt engineering). The server starts on demand via stdio and exits when the agent disconnects.

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).