diff --git a/.cursor/mcp.json b/.cursor/mcp.json new file mode 100644 index 0000000..f4d8b3f --- /dev/null +++ b/.cursor/mcp.json @@ -0,0 +1,9 @@ +{ + "mcpServers": { + "ai-code-graph": { + "type": "stdio", + "command": "ai-code-graph", + "args": ["mcp", "--db", "./ai-code-graph/graph.db"] + } + } +} diff --git a/.cursor/rules/ai-code-graph.mdc b/.cursor/rules/ai-code-graph.mdc new file mode 100644 index 0000000..357b51d --- /dev/null +++ b/.cursor/rules/ai-code-graph.mdc @@ -0,0 +1,25 @@ +--- +description: AI Code Graph MCP workflow for C# analysis and edits +alwaysApply: true +--- + +# AI Code Graph Integration + +If `cg_*` MCP tools are available, use them for code-understanding tasks. + +Before editing any method, call `cg_get_context` first (when graph data exists) to review complexity, callers, callees, duplicates, and cluster context. + +Primary tools: +- `cg_get_context` +- `cg_get_hotspots` +- `cg_get_callgraph` +- `cg_get_impact` +- `cg_query` +- `cg_dead_code` + +Secondary tools: +- `cg_token_search`, `cg_semantic_search`, `cg_get_similar` +- `cg_get_duplicates`, `cg_get_clusters`, `cg_export_graph` +- `cg_churn`, `cg_coupling`, `cg_diff`, `cg_get_drift`, `cg_get_tree`, `cg_analyze` + +If the database is missing, run `cg_analyze` first to build `./ai-code-graph/graph.db`. diff --git a/AiCodeGraph.Cli/Commands/CommandRegistry.cs b/AiCodeGraph.Cli/Commands/CommandRegistry.cs index 909f004..1496e4e 100644 --- a/AiCodeGraph.Cli/Commands/CommandRegistry.cs +++ b/AiCodeGraph.Cli/Commands/CommandRegistry.cs @@ -32,6 +32,7 @@ public static RootCommand Build() new DiffCommand(), new McpCommand(), new SetupClaudeCommand(), + new SetupCursorCommand(), new StatusCommand(), new LayersCommand(), new QueryCommand(), diff --git a/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs b/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs new file mode 100644 index 0000000..e41c47f --- /dev/null +++ b/AiCodeGraph.Cli/Commands/SetupCursorCommand.cs @@ -0,0 +1,232 @@ +using System.CommandLine; +using System.CommandLine.Parsing; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace AiCodeGraph.Cli.Commands; + +public class SetupCursorCommand : ICommandHandler +{ + public Command BuildCommand() + { + var dbOption = new Option("--db") + { + Description = "Path to graph.db used by Cursor MCP integration", + DefaultValueFactory = _ => "./ai-code-graph/graph.db" + }; + + var command = new Command("setup-cursor", "Scaffold Cursor MCP config, rules, and skill for AI Code Graph") + { + dbOption + }; + + command.SetAction((parseResult, _) => + { + var dbPath = parseResult.GetValue(dbOption) ?? "./ai-code-graph/graph.db"; + var created = new List(); + + var cursorDir = Path.Combine(Directory.GetCurrentDirectory(), ".cursor"); + var rulesDir = Path.Combine(cursorDir, "rules"); + var skillsDir = Path.Combine(cursorDir, "skills", "ai-code-graph"); + + Directory.CreateDirectory(cursorDir); + Directory.CreateDirectory(rulesDir); + Directory.CreateDirectory(skillsDir); + + EnsureCursorMcpConfig(cursorDir, dbPath, created); + CreateFileIfMissing(rulesDir, "ai-code-graph.mdc", GetRuleContent(), created); + CreateFileIfMissing(skillsDir, "SKILL.md", GetSkillContent(), created); + + if (created.Count > 0) + { + Console.WriteLine("Cursor integration set up:"); + foreach (var path in created) + { + Console.WriteLine($" + {Path.GetRelativePath(Directory.GetCurrentDirectory(), path)}"); + } + + Console.WriteLine(); + Console.WriteLine("Next steps:"); + Console.WriteLine(" 1. In Cursor, enable the ai-code-graph MCP server if prompted"); + Console.WriteLine(" 2. Run `ai-code-graph analyze YourSolution.sln` to build graph.db"); + Console.WriteLine(" 3. Ask the agent to use AI Code Graph context before edits"); + } + else + { + Console.WriteLine("All Cursor integration files already exist. Nothing to do."); + } + + return Task.CompletedTask; + }); + + return command; + } + + private static void EnsureCursorMcpConfig(string cursorDir, string dbPath, List created) + { + var mcpPath = Path.Combine(cursorDir, "mcp.json"); + var serverNode = new JsonObject + { + ["type"] = "stdio", + ["command"] = "ai-code-graph", + ["args"] = new JsonArray("mcp", "--db", dbPath) + }; + + if (!File.Exists(mcpPath)) + { + var root = new JsonObject + { + ["mcpServers"] = new JsonObject + { + ["ai-code-graph"] = serverNode + } + }; + + File.WriteAllText(mcpPath, root.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + created.Add(mcpPath); + return; + } + + try + { + var root = JsonNode.Parse(File.ReadAllText(mcpPath)) as JsonObject; + if (root == null) + { + Console.WriteLine("Warning: .cursor/mcp.json is not a JSON object. Skipping MCP update."); + return; + } + + var servers = root["mcpServers"] as JsonObject; + if (servers == null) + { + servers = new JsonObject(); + root["mcpServers"] = servers; + } + + var hasServer = servers.ContainsKey("ai-code-graph"); + var existingServer = hasServer ? servers["ai-code-graph"] : null; + var shouldWrite = false; + + if (!hasServer) + { + servers["ai-code-graph"] = serverNode; + shouldWrite = true; + } + else if (existingServer is not JsonObject existingServerObject) + { + servers["ai-code-graph"] = serverNode; + shouldWrite = true; + } + else if (!JsonNode.DeepEquals(existingServerObject, serverNode)) + { + servers["ai-code-graph"] = serverNode; + shouldWrite = true; + } + + if (shouldWrite) + { + File.WriteAllText(mcpPath, root.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + created.Add(mcpPath + " (updated)"); + } + } + catch (JsonException) + { + Console.WriteLine("Warning: failed to parse .cursor/mcp.json. Skipping MCP update."); + } + } + + private static void CreateFileIfMissing(string dir, string filename, string content, List created) + { + var path = Path.Combine(dir, filename); + if (!File.Exists(path)) + { + File.WriteAllText(path, content); + created.Add(path); + } + } + + private static string GetRuleContent() => @"--- +description: AI Code Graph MCP workflow for C# analysis and edits +alwaysApply: true +--- + +# AI Code Graph Integration + +If `cg_*` MCP tools are available, use them for code-understanding tasks. + +Before editing any method, call `cg_get_context` first (when graph data exists) to review complexity, callers, callees, duplicates, and cluster context. + +Primary tools: +- `cg_get_context` +- `cg_get_hotspots` +- `cg_get_callgraph` +- `cg_get_impact` +- `cg_query` +- `cg_dead_code` + +Secondary tools: +- `cg_token_search`, `cg_semantic_search`, `cg_get_similar` +- `cg_get_duplicates`, `cg_get_clusters`, `cg_export_graph` +- `cg_churn`, `cg_coupling`, `cg_diff`, `cg_get_drift`, `cg_get_tree`, `cg_analyze` + +If the database is missing, run `cg_analyze` first to build `./ai-code-graph/graph.db`. +"; + + private static string GetSkillContent() => @"--- +name: ai-code-graph +description: Guides AI Code Graph workflows for .NET analysis, refactoring, architecture checks, impact analysis, and duplicate detection. Use when users ask about complexity hotspots, blast radius, dead code, coupling, drift, or semantic code lookup. +--- + +# AI Code Graph Skill + +## Quick Start + +1. If graph data is missing, run `cg_analyze` on the solution. +2. Before editing a method, run `cg_get_context`. +3. Use method IDs from results for stable follow-up calls. + +## Before Editing a Method + +Use `cg_get_context` and interpret: +- **Complexity**: If CC > 10, avoid increasing branching/nesting. +- **Callers/Callees**: Estimate blast radius before signature or behavior changes. +- **Duplicates**: Apply the same fix to clone partners when appropriate. +- **Cluster**: Keep changes aligned with the method's intent group. + +Then run: +- `cg_get_impact` for transitive caller impact +- `cg_get_callgraph` for direct relationships + +## Refactoring Workflows + +- **Complexity hotspot review**: `cg_get_hotspots` and prioritize highest CC methods. +- **Dead code cleanup**: `cg_dead_code`, remove or deprecate unreachable methods. +- **Coupling risk scan**: `cg_coupling`, focus on high-instability namespaces/types. +- **Churn risk scan**: `cg_churn`, prioritize high change-frequency x complexity areas. + +## Search Workflows + +- Use `cg_query` first for deterministic graph-based retrieval. +- Use `cg_token_search` for identifier/token overlap lookups. +- Use `cg_semantic_search` as fallback for natural-language intent matching. +- Use `cg_get_similar` to find candidates for consolidation. + +## Architecture Review + +- Use `cg_get_drift` to compare against baseline and detect regressions. +- Use `cg_get_clusters` and `cg_get_duplicates` to inspect intent fragmentation. +- Use `cg_export_graph` for structured downstream analysis. +- For layer and dependency policy checks, run CLI commands: + - `ai-code-graph layers --db ./ai-code-graph/graph.db` + - `ai-code-graph check-deps --db ./ai-code-graph/graph.db` + +## Task-to-Tool Decision Guide + +- **""I need context before changing code""** -> `cg_get_context` +- **""What breaks if I change this?""** -> `cg_get_impact` then `cg_get_callgraph` +- **""Where are risky areas?""** -> `cg_get_hotspots`, `cg_churn`, `cg_coupling` +- **""Can we delete this?""** -> `cg_dead_code` and caller checks +- **""Find code related to this idea""** -> `cg_query`, then `cg_token_search`/`cg_semantic_search` +- **""Are we drifting architecturally?""** -> `cg_get_drift`, `cg_get_clusters`, duplicates review +"; +} diff --git a/AiCodeGraph.Tests/CliCommandTests.cs b/AiCodeGraph.Tests/CliCommandTests.cs index 16c6372..1651a4b 100644 --- a/AiCodeGraph.Tests/CliCommandTests.cs +++ b/AiCodeGraph.Tests/CliCommandTests.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Text.Json.Nodes; using AiCodeGraph.Core.Storage; using Microsoft.Data.Sqlite; @@ -17,7 +18,7 @@ public class CliCommandTests : TempDirectoryFixture public CliCommandTests() : base("cli-test") { } - private async Task<(int ExitCode, string Output, string Error)> RunCliAsync(string args, int timeoutMs = 10000) + private async Task<(int ExitCode, string Output, string Error)> RunCliAsync(string args, int timeoutMs = 10000, string? workingDirectory = null) { var psi = new ProcessStartInfo { @@ -26,7 +27,8 @@ public CliCommandTests() : base("cli-test") { } RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, - CreateNoWindow = true + CreateNoWindow = true, + WorkingDirectory = workingDirectory ?? Directory.GetCurrentDirectory() }; using var process = Process.Start(psi)!; @@ -239,4 +241,121 @@ public async Task Command_UnrecognizedOption_ReturnsNonZero() Assert.NotEqual(0, exitCode); Assert.Contains("Unrecognized", error); } + + [Fact] + public async Task SetupCursorCommand_WithExistingServer_UpdatesDbPath() + { + var workspace = Path.Combine(TempDir, "workspace-update"); + Directory.CreateDirectory(workspace); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor")); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor", "rules")); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor", "skills", "ai-code-graph")); + + var mcpPath = Path.Combine(workspace, ".cursor", "mcp.json"); + await File.WriteAllTextAsync( + mcpPath, + """ + { + "mcpServers": { + "ai-code-graph": { + "type": "stdio", + "command": "ai-code-graph", + "args": ["mcp", "--db", "./old/graph.db"] + } + } + } + """); + + await File.WriteAllTextAsync(Path.Combine(workspace, ".cursor", "rules", "ai-code-graph.mdc"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, ".cursor", "skills", "ai-code-graph", "SKILL.md"), "existing"); + + var (exitCode, output, error) = await RunCliAsync("setup-cursor --db ./new/graph.db", workingDirectory: workspace); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains($"{Path.Combine(".cursor", "mcp.json")} (updated)", output); + + var root = JsonNode.Parse(await File.ReadAllTextAsync(mcpPath))!.AsObject(); + var args = root["mcpServers"]!["ai-code-graph"]!["args"]!.AsArray(); + Assert.Equal("mcp", args[0]!.GetValue()); + Assert.Equal("--db", args[1]!.GetValue()); + Assert.Equal("./new/graph.db", args[2]!.GetValue()); + } + + [Fact] + public async Task SetupCursorCommand_WithMatchingServer_NoChanges() + { + var workspace = Path.Combine(TempDir, "workspace-noop"); + Directory.CreateDirectory(workspace); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor")); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor", "rules")); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor", "skills", "ai-code-graph")); + + var mcpPath = Path.Combine(workspace, ".cursor", "mcp.json"); + await File.WriteAllTextAsync( + mcpPath, + """ + { + "mcpServers": { + "ai-code-graph": { + "type": "stdio", + "command": "ai-code-graph", + "args": ["mcp", "--db", "./same/graph.db"] + } + } + } + """); + + await File.WriteAllTextAsync(Path.Combine(workspace, ".cursor", "rules", "ai-code-graph.mdc"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, ".cursor", "skills", "ai-code-graph", "SKILL.md"), "existing"); + + var before = await File.ReadAllTextAsync(mcpPath); + var (exitCode, output, error) = await RunCliAsync("setup-cursor --db ./same/graph.db", workingDirectory: workspace); + var after = await File.ReadAllTextAsync(mcpPath); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains("Nothing to do.", output); + Assert.Equal(before, after); + } + + [Fact] + public async Task SetupCursorCommand_WithMissingServer_AddsServerEntry() + { + var workspace = Path.Combine(TempDir, "workspace-insert"); + Directory.CreateDirectory(workspace); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor")); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor", "rules")); + Directory.CreateDirectory(Path.Combine(workspace, ".cursor", "skills", "ai-code-graph")); + + var mcpPath = Path.Combine(workspace, ".cursor", "mcp.json"); + await File.WriteAllTextAsync( + mcpPath, + """ + { + "mcpServers": { + "other-server": { + "type": "stdio", + "command": "other-tool", + "args": ["run"] + } + } + } + """); + + await File.WriteAllTextAsync(Path.Combine(workspace, ".cursor", "rules", "ai-code-graph.mdc"), "existing"); + await File.WriteAllTextAsync(Path.Combine(workspace, ".cursor", "skills", "ai-code-graph", "SKILL.md"), "existing"); + + var (exitCode, output, error) = await RunCliAsync("setup-cursor --db ./inserted/graph.db", workingDirectory: workspace); + + Assert.Equal(0, exitCode); + Assert.True(string.IsNullOrWhiteSpace(error)); + Assert.Contains($"{Path.Combine(".cursor", "mcp.json")} (updated)", output); + + var root = JsonNode.Parse(await File.ReadAllTextAsync(mcpPath))!.AsObject(); + var servers = root["mcpServers"]!.AsObject(); + Assert.NotNull(servers["other-server"]); + Assert.NotNull(servers["ai-code-graph"]); + Assert.Equal("./inserted/graph.db", servers["ai-code-graph"]!["args"]!.AsArray()[2]!.GetValue()); + } } diff --git a/CLAUDE.md b/CLAUDE.md index f01e625..c6ee717 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,6 +13,13 @@ dotnet test --filter "ClassName" # Run specific test class dotnet pack AiCodeGraph.Cli # Package as global tool ``` +## AI Setup Helpers + +```bash +ai-code-graph setup-claude # Scaffold Claude slash commands + MCP config +ai-code-graph setup-cursor # Scaffold Cursor MCP config + rule + project skill +``` + ## Project Structure - `AiCodeGraph.Cli/` - CLI entry point using System.CommandLine 2.0.2. All commands defined in `Program.cs`. diff --git a/README.md b/README.md index 18ce644..28672a6 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,15 @@ ai-code-graph setup-claude Creates slash commands (`/cg:context`, `/cg:hotspots`, etc.) and MCP server config. +### Cursor + +```bash +# One-command setup +ai-code-graph setup-cursor +``` + +Creates `.cursor/mcp.json`, `.cursor/rules/ai-code-graph.mdc`, and `.cursor/skills/ai-code-graph/SKILL.md`. + ### MCP Server ```bash