A Model Context Protocol (MCP) server providing 58 AI-optimized tools for .NET/C semantic code analysis, navigation, refactoring, and code generation using Microsoft Roslyn. Built for AI coding agents - provides compiler-accurate code understanding that AI cannot infer from reading source files alone. Then run with: 1. Install the tool globally: 2. Create .mcp.json in your project root: 3. Restart
Add this skill
npx mdskills install pzalutski-pixel/sharplens-mcpProfessional MCP server delivering 58 Roslyn-powered C# analysis tools with excellent documentation
1# SharpLensMcp23[](https://www.nuget.org/packages/SharpLensMcp)4[](LICENSE)56A Model Context Protocol (MCP) server providing **58 AI-optimized tools** for .NET/C# semantic code analysis, navigation, refactoring, and code generation using Microsoft Roslyn.78Built for AI coding agents - provides compiler-accurate code understanding that AI cannot infer from reading source files alone.910## Installation1112### Via NuGet (Recommended)13```bash14dotnet tool install -g SharpLensMcp15```1617Then run with:18```bash19sharplens20```2122### Build from Source23```bash24dotnet build -c Release25dotnet publish -c Release -o ./publish26```2728## Claude Code Setup29301. **Install the tool globally**:31```bash32dotnet tool install -g SharpLensMcp33```34352. **Create `.mcp.json` in your project root**:36```json37{38 "mcpServers": {39 "sharplens": {40 "type": "stdio",41 "command": "sharplens",42 "args": [],43 "env": {44 "DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"45 }46 }47 }48}49```50513. **Restart Claude Code** to load the MCP server52534. **Verify** by asking Claude to run a health check on the Roslyn server5455### Why Use This with Claude Code?5657Claude Code has native LSP support for basic navigation (go-to-definition, find references). SharpLensMcp adds **deep semantic analysis**:5859| Capability | Native LSP | SharpLensMcp |60|------------|------------|--------------|61| Go to definition | ✅ | ✅ |62| Find references | ✅ | ✅ |63| Find async methods missing CancellationToken | ❌ | ✅ |64| Impact analysis (what breaks?) | ❌ | ✅ |65| Dead code detection | ❌ | ✅ |66| Complexity metrics | ❌ | ✅ |67| Safe refactoring with preview | ❌ | ✅ |68| Batch operations | ❌ | ✅ |6970## Configuration7172| Environment Variable | Description | Default |73|---------------------|-------------|---------|74| `DOTNET_SOLUTION_PATH` | Path to `.sln` or `.slnx` file to auto-load on startup | None (must call `load_solution`) |75| `SHARPLENS_ABSOLUTE_PATHS` | Use absolute paths instead of relative | `false` (relative paths save tokens) |76| `ROSLYN_LOG_LEVEL` | Logging verbosity: `Trace`, `Debug`, `Information`, `Warning`, `Error` | `Information` |77| `ROSLYN_TIMEOUT_SECONDS` | Timeout for long-running operations | `30` |78| `ROSLYN_MAX_DIAGNOSTICS` | Maximum diagnostics to return | `100` |79| `ROSLYN_ENABLE_SEMANTIC_CACHE` | Enable semantic model caching | `true` (set to `false` to disable) |8081If `DOTNET_SOLUTION_PATH` is not set, you must call the `load_solution` tool before using other tools.8283## AI Agent Configuration Tips8485AI models may have trained bias toward using their native tools (Grep, Read, LSP) instead of MCP server tools, even when SharpLensMcp provides better capabilities.8687**To ensure optimal tool usage:**88891. **Claude Code**: Add to your project's `CLAUDE.md`:90 ```91 For C# code analysis, prefer SharpLensMcp tools over native tools:92 - Use `roslyn:search_symbols` instead of Grep for finding symbols93 - Use `roslyn:get_method_source` instead of Read for viewing methods94 - Use `roslyn:find_references` for semantic (not text) references95 ```96972. **Other MCP clients**: Configure tool priority in your agent's system prompt9899The semantic analysis from Roslyn is more accurate than text-based search, especially for overloaded methods, partial classes, and inheritance hierarchies.100101## Agent Responsibility: Document Synchronization102103**Important:** SharpLensMcp maintains an in-memory representation of your solution for fast queries. When files are modified externally (via Edit/Write tools), the agent is responsible for synchronizing changes.104105### When to call `sync_documents`:106107| Action | Call sync_documents? |108|--------|---------------------|109| Used Edit tool to modify .cs files | ✅ **Yes** |110| Used Write tool to create new .cs files | ✅ **Yes** |111| Deleted .cs files | ✅ **Yes** |112| Used SharpLensMcp refactoring tools (rename, extract, etc.) | ❌ No (auto-updated) |113| Modified .csproj files | ❌ No (use `load_solution` instead) |114115### Usage:116117```118# After editing specific files119sync_documents(filePaths: ["src/MyClass.cs", "src/MyService.cs"])120121# After bulk changes - sync all documents122sync_documents()123```124125### Why this design?126127This mirrors how LSP (Language Server Protocol) works - the client (editor) notifies the server of changes. This approach:128- Eliminates race conditions (agent controls timing)129- Avoids file watcher complexity and platform quirks130- Is faster than full solution reload131- Gives agents explicit control over workspace state132133**If you don't sync:** Queries may return stale data (old method signatures, missing new files, etc.)134135## Features136137- **58 Semantic Analysis Tools** - Navigation, refactoring, code generation, diagnostics138- **AI-Optimized Descriptions** - Clear USAGE/OUTPUT/WORKFLOW patterns139- **Structured Responses** - Consistent `success/error/data` format with `suggestedNextTools`140- **Zero-Based Coordinates** - Clear warnings to prevent off-by-one errors141- **Preview Mode** - Safe refactoring with preview before apply142- **Batch Operations** - Multiple lookups in one call to reduce context usage143144## Tool Categories145146### Navigation & Discovery (13 tools)147| Tool | Description |148|------|-------------|149| `get_symbol_info` | Semantic info at position |150| `go_to_definition` | Jump to symbol definition |151| `find_references` | All references across solution |152| `find_implementations` | Interface/abstract implementations |153| `find_callers` | Impact analysis - who calls this? |154| `get_type_hierarchy` | Inheritance chain |155| `search_symbols` | Glob pattern search (`*Handler`, `Get*`) |156| `semantic_query` | Multi-filter search (async, public, etc.) |157| `get_type_members` | All members by type name |158| `get_type_members_batch` | Multiple types in one call |159| `get_method_signature` | Detailed signature by name |160| `get_derived_types` | Find all subclasses |161| `get_base_types` | Full inheritance chain |162163### Analysis (9 tools)164| Tool | Description |165|------|-------------|166| `get_diagnostics` | Compiler errors/warnings |167| `analyze_data_flow` | Variable assignments and usage |168| `analyze_control_flow` | Branching/reachability |169| `analyze_change_impact` | What breaks if changed? |170| `check_type_compatibility` | Can A assign to B? |171| `get_outgoing_calls` | What does this method call? |172| `find_unused_code` | Dead code detection |173| `validate_code` | Compile check without writing |174| `get_complexity_metrics` | Cyclomatic, nesting, LOC, cognitive |175176### Refactoring (13 tools)177| Tool | Description |178|------|-------------|179| `rename_symbol` | Safe rename across solution |180| `change_signature` | Add/remove/reorder parameters |181| `extract_method` | Extract with data flow analysis |182| `extract_interface` | Generate interface from class |183| `generate_constructor` | From fields/properties |184| `organize_usings` | Sort and remove unused |185| `organize_usings_batch` | Batch organize multiple files |186| `get_code_actions_at_position` | All Roslyn refactorings at position |187| `apply_code_action_by_title` | Apply any refactoring by title |188| `implement_missing_members` | Generate interface stubs |189| `encapsulate_field` | Field to property |190| `inline_variable` | Inline temp variable |191| `extract_variable` | Extract expression to variable |192193### Code Generation (2 tools)194| Tool | Description |195|------|-------------|196| `add_null_checks` | Generate ArgumentNullException guards |197| `generate_equality_members` | Equals/GetHashCode/operators |198199### Compound Tools (6 tools)200| Tool | Description |201|------|-------------|202| `get_type_overview` | Full type info in one call |203| `analyze_method` | Signature + callers + outgoing calls + location |204| `get_file_overview` | File summary with diagnostics |205| `get_method_source` | Source code by name |206| `get_method_source_batch` | Multiple method sources in one call |207| `get_instantiation_options` | How to create a type |208209### Infrastructure (5 tools)210| Tool | Description |211|------|-------------|212| `health_check` | Server status |213| `load_solution` | Load .sln/.slnx for analysis |214| `get_project_structure` | Solution structure |215| `dependency_graph` | Project dependencies |216| `get_code_fixes` / `apply_code_fix` | Automated fixes |217218## Other MCP Clients219220For MCP clients other than Claude Code, add to your configuration:221222```json223{224 "mcpServers": {225 "sharplens": {226 "command": "sharplens",227 "args": [],228 "env": {229 "DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"230 }231 }232 }233}234```235236## Usage2372381. **Load a solution**: Call `roslyn:load_solution` with path to `.sln` or `.slnx` file (or set `DOTNET_SOLUTION_PATH`)2392. **Analyze code**: Use any of the 57 tools for navigation, analysis, refactoring2403. **Refactor safely**: Preview changes before applying with `preview: true`241242## Architecture243244```245MCP Client (AI Agent)246 | stdin/stdout (JSON-RPC 2.0)247 v248 SharpLensMcp249 - Protocol handling250 - 57 AI-optimized tools251 |252 v253Microsoft.CodeAnalysis (Roslyn)254 - MSBuildWorkspace255 - SemanticModel256 - SymbolFinder257```258259## Requirements260261- .NET 8.0 SDK/Runtime262- MCP-compatible AI agent263264## Development265266### Adding New Tools2672681. **Add method to `src/RoslynService.cs`**:269```csharp270public async Task<object> YourToolAsync(string param1, int? param2 = null)271{272 EnsureSolutionLoaded();273 // Your logic...274 return CreateSuccessResponse(275 data: new { /* results */ },276 suggestedNextTools: new[] { "next_tool_hint" }277 );278}279```2802812. **Add tool definition to `src/McpServer.cs`** in `HandleListToolsAsync`2822833. **Add routing to `src/McpServer.cs`** in `HandleToolCallAsync` switch2842854. **Build and publish**:286```bash287dotnet build -c Release288dotnet publish -c Release -o ./publish289```290291### Key Files292293| File | Purpose |294|------|---------|295| `src/RoslynService.cs` | Tool implementations (57 methods) |296| `src/McpServer.cs` | MCP protocol, tool definitions, routing |297298## License299300MIT - See [LICENSE](LICENSE) for details.301
Full transparency — inspect the skill content before installing.