sharplens-mcp
SharpLensMcp is a Model Context Protocol (MCP) server providing 67 AI-optimized, compiler-accurate tools for deep semantic analysis, navigation, refactoring, and code generation in .NET/C# projects using Microsoft Roslyn.
Navigation & Discovery
Go to definitions, find all references (classified as read/write/invocation/cast), find implementations of interfaces/abstract members
Search symbols with glob patterns (e.g.,
*Handler,Get*) or complex semantic filters (async status, accessibility, attributes)Get type hierarchies, base/derived types, callers, call graphs, method overloads, and attribute usages
Inspect external NuGet/BCL assembly types with XML docs
Semantic Analysis
Get compiler errors, warnings, and analyzer diagnostics (StyleCop, Roslynator, etc.)
Analyze data flow (variable assignments/reads/writes) and control flow (branching, reachability)
Detect unused/dead code, measure complexity metrics (cyclomatic, nesting, LOC, cognitive), find circular dependencies
Check type compatibility, analyze change impact (what breaks if you rename/modify a symbol), validate code snippets without writing to disk
Refactoring
Safely rename symbols across the entire solution, change method signatures (add/remove/reorder parameters)
Extract methods, extract variables, inline variables, extract interfaces, encapsulate fields into properties
Organize/remove unused
usingdirectives and format documents (single or batch)Access and apply 100+ built-in Roslyn code actions and fixes at any position
Code Generation
Generate constructors,
Equals/GetHashCode/==/!=operators, andArgumentNullExceptionnull-check guardsGenerate stub implementations for missing interface/abstract members
Project & Solution Insights
Load
.sln/.slnxsolutions, sync file changes, view project structure and dependency graphs (JSON or Mermaid)List NuGet dependencies, scan DI registrations (
AddScoped/AddTransient/AddSingleton), detect reflection/dynamic usageList active source generators and view their generated output
Get composite project health dashboards (diagnostics + unused code + coupling), detect god objects, find untested public surface
Compound & Infrastructure Tools
Single-call type overviews, method analyses, and file summaries
Batch operations for method sources, members, and usings to reduce round trips
Health check server status
Enables comprehensive .NET/C# code analysis through Microsoft Roslyn, providing semantic understanding of C# codebases including navigation, refactoring, diagnostics, and code generation capabilities.
Provides tools to analyze NuGet package dependencies across .NET projects, listing packages per project and detecting dependency relationships within the solution.
SharpLensMcp
A Model Context Protocol (MCP) server providing 91 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.
Installation
Via NuGet (Recommended)
dotnet tool install -g SharpLensMcpThen run with:
sharplensVia npm
npx -y sharplens-mcpBuild from Source
dotnet build -c Release
dotnet publish -c Release -o ./publishRelated MCP server: roslyn-codelens-mcp
Claude Code Setup
Install the tool (pick one):
dotnet tool install -g SharpLensMcp
# or
npx -y sharplens-mcpCreate
.mcp.jsonin your project root:
{
"mcpServers": {
"sharplens": {
"type": "stdio",
"command": "npx",
"args": ["-y", "sharplens-mcp"],
"env": {
"DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"
}
}
}
}Restart Claude Code to load the MCP server
Verify by asking Claude to run a health check on the Roslyn server
Why Use This with Claude Code?
Claude Code has native LSP support for basic navigation (go-to-definition, find references). SharpLensMcp adds deep semantic analysis:
Capability | Native LSP | SharpLensMcp |
Go to definition | ✅ | ✅ |
Find references | ✅ | ✅ |
Find async methods missing CancellationToken | ❌ | ✅ |
Impact analysis (what breaks?) | ❌ | ✅ |
Dead code detection | ❌ | ✅ |
Complexity metrics | ❌ | ✅ |
Safe refactoring with preview | ❌ | ✅ |
Batch operations | ❌ | ✅ |
Configuration
Environment Variable | Description | Default |
| Path to | None (must call |
| Use absolute paths instead of relative |
|
| Logging verbosity: |
|
| Timeout for long-running operations |
|
| Maximum diagnostics to return |
|
| Enable semantic model caching |
|
The pre-1.6.0 ROSLYN_* spellings of the last four variables are still read as a fallback for one release; the SHARPLENS_* spelling wins when both are set.
If DOTNET_SOLUTION_PATH is not set, you must call the load_solution tool before using other tools.
Migrating from 1.5.x tool names
Tool names no longer carry the roslyn: prefix — the colon violates the MCP tool-name pattern (^[a-zA-Z0-9_-]{1,64}$), which some clients enforce. Every tool keeps its name minus the prefix:
1.5.x name | 1.6.0 name |
|
|
|
|
|
|
...same rule for all 91 tools... | drop the |
tools/list publishes only the new names. Calls using the old prefixed names are still accepted as aliases for one release and will be removed in the following one.
AI Agent Configuration Tips
AI models may have trained bias toward using their native tools (Grep, Read, LSP) instead of MCP server tools, even when SharpLensMcp provides better capabilities.
To ensure optimal tool usage:
Claude Code: Add to your project's
CLAUDE.md:For C# code analysis, prefer SharpLensMcp tools over native tools: - Use `search_symbols` instead of Grep for finding symbols - Use `get_method_source` instead of Read for viewing methods - Use `find_references` for semantic (not text) referencesOther MCP clients: Configure tool priority in your agent's system prompt
The semantic analysis from Roslyn is more accurate than text-based search, especially for overloaded methods, partial classes, and inheritance hierarchies.
Agent Responsibility: Document Synchronization
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.
When to call sync_documents:
Action | Call sync_documents? |
Used Edit tool to modify .cs files | ✅ Yes |
Used Write tool to create new .cs files | ✅ Yes |
Deleted .cs files | ✅ Yes |
Used SharpLensMcp refactoring tools (rename, extract, etc.) | ❌ No (auto-updated) |
Modified .csproj files | ❌ No (use |
Usage:
# After editing specific files
sync_documents(filePaths: ["src/MyClass.cs", "src/MyService.cs"])
# After bulk changes - sync all documents
sync_documents()Why this design?
This mirrors how LSP (Language Server Protocol) works - the client (editor) notifies the server of changes. This approach:
Eliminates race conditions (agent controls timing)
Avoids file watcher complexity and platform quirks
Is faster than full solution reload
Gives agents explicit control over workspace state
If you don't sync: Queries may return stale data (old method signatures, missing new files, etc.)
Features
91 Semantic Analysis Tools - Navigation, refactoring, code generation, diagnostics, discovery, audit/quality
AI-Optimized Descriptions - Clear USAGE/OUTPUT/WORKFLOW patterns
Structured Responses - Consistent
success/error/dataformat withsuggestedNextToolsZero-Based Coordinates - Clear warnings to prevent off-by-one errors
Preview Mode - Safe refactoring with preview before apply
Batch Operations - Multiple lookups in one call to reduce context usage
Tool Categories
Navigation & Discovery (23 tools)
Tool | Description |
| Semantic info at position |
| Jump to symbol definition |
| All references; each classified read/write/invocation/cast/typeof/nameof/attribute; optional |
| Interface/abstract implementations |
| Impact analysis - who calls this? |
| Multi-hop callers/callees graph with depth bound + cycle detection |
| Inheritance chain |
| Glob pattern search ( |
| Multi-filter search (async, public, etc.) |
| All members by type name |
| Multiple types in one call |
| Detailed signature by name |
| Find all subclasses |
| Full inheritance chain |
| List attributes on a symbol |
| Enclosing symbol at position |
| All overloads of a method |
| Find types/members by attribute |
| Inspect NuGet/BCL/external assembly types — members + XML docs |
| Map a pasted stack trace to file/line/symbol, mangling undone |
| Extensions applying to a type — classic and C# 14 blocks |
| Full XML docs for a symbol with |
| Navigate to the base member / interface members a member implements |
Analysis (17 tools)
Tool | Description |
| Compiler errors/warnings + configured analyzer findings (StyleCop, Roslynator, NetAnalyzers); matches CI |
| Public-API breaking-change report vs a git ref |
| Which exceptions can escape a method, and where they're caught |
| Structural similarity search (token-shingle fingerprints) |
| Compute dead-code removals + newly unused usings (generation-only) |
| Unreachable basic blocks per method (real CFG, not heuristics) |
| Compute the usings that fix CS0246/CS0103 (generation-only) |
| Variable assignments and usage |
| Branching/reachability |
| What breaks if changed? |
| Can A assign to B? |
| What does this method call? |
| Dead code detection |
| Compile check without writing |
| Cyclomatic, nesting, LOC, cognitive |
| Project and namespace cycle detection |
| Unimplemented interface/abstract members |
Refactoring (16 tools)
Tool | Description |
| Safe rename across solution |
| Add/remove/reorder parameters |
| Extract with data flow analysis |
| Generate interface from class |
| From fields/properties |
| Compute the contents to move a type into its own file (generation-only) |
| Compute a partial-class split for selected members (generation-only) |
| Sort and remove unused |
| Batch organize multiple files |
| Batch format files in project |
| All Roslyn refactorings at position |
| Apply any refactoring by title |
| Generate interface stubs |
| Field to property |
| Inline temp variable |
| Extract expression to variable |
Code Generation (3 tools)
Tool | Description |
| Generate ArgumentNullException guards |
| Equals/GetHashCode/operators |
| Compilable test skeleton for a method (framework auto-detected) |
Compound Tools (7 tools)
Tool | Description |
| Full type info in one call |
| Signature + callers + outgoing calls + location |
| File summary with diagnostics |
| Source code by name |
| Multiple method sources in one call |
| How to create a type |
| Composite audit dashboard: diagnostics + unused + coupling + coverage per project |
Audit & Quality (10 tools)
Tool | Description |
| Detect over-coupled types via efferent + afferent coupling + member-count thresholds |
| Find public surface not reached by any [Fact]/[Theory]/[Test]/[TestMethod] |
| Which tests cover a symbol — the inverse of find_untested_code |
| Where a type is constructed ( |
| Where a type appears in is/as/pattern matches |
| Where an exception type is thrown (optionally derived) |
| Where an exception type is caught (optionally via a base clause) |
| async void / blocking-on-async / unforwarded CancellationToken |
| Enforce namespace/project dependency rules over the type graph |
| Naming audit honoring .editorconfig rules, with conventional defaults |
Discovery (3 tools)
Tool | Description |
| Scan DI service registrations |
| Detect reflection/dynamic usage |
| Surface [InterceptsLocation] call rerouting, generated code included |
Infrastructure (12 tools)
Tool | Description |
| Server status |
| PackageReferences/ProjectReferences the compiler never needs |
| Compute the fix for every instance of a diagnostic id (generation-only) |
| Load .sln/.slnx for analysis |
| Sync file changes into loaded solution |
| Solution structure |
| Project dependencies |
| Available fixes for a diagnostic |
| Apply a specific code fix |
| NuGet package listing per project |
| List active source generators |
| View generated source code |
Other MCP Clients
For MCP clients other than Claude Code, add to your configuration:
{
"mcpServers": {
"sharplens": {
"command": "sharplens",
"args": [],
"env": {
"DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"
}
}
}
}Usage
Load a solution: Call
load_solutionwith path to.slnor.slnxfile (or setDOTNET_SOLUTION_PATH)Analyze code: Use any of the 91 tools for navigation, analysis, refactoring, audit
Refactor safely: Preview changes before applying with
preview: true
Architecture
MCP Client (AI Agent)
| stdin/stdout (JSON-RPC 2.0)
v
SharpLensMcp
- Protocol handling
- 91 AI-optimized tools
|
v
Microsoft.CodeAnalysis (Roslyn)
- MSBuildWorkspace
- SemanticModel
- SymbolFinderRequirements
.NET 8.0 SDK or later — works with .NET 8, 9, 10, and future versions. Analyzes any .NET 8+ project/solution.
MCP-compatible AI agent
FAQ
Why does the tool target net8.0 — can it analyze my .NET 9 / .NET 10 project?
Yes. net8.0 is the tool's own runtime floor — the Roslyn 5.x packages it builds on require it — not a ceiling on what it can analyze. RollForward lets the installed tool run on newer .NET runtimes, and MSBuildWorkspace loads each project's real target framework from its csproj, so one install analyzes solutions targeting .NET 8, 9, 10, and beyond.
Development
Adding New Tools
Add the method to the matching
src/RoslynService.*.cspartial (Navigation, Analysis, Refactoring, CallAnalysis, …) and return through the shared response envelope:
public async Task<object> YourToolAsync(string param1, int? param2 = null,
CancellationToken cancellationToken = default)
{
EnsureSolutionLoaded();
// Your logic...
return CreateSuccessResponse(
data: new { /* results */ },
suggestedNextTools: new[] { "next_tool_hint" }
);
}Register one
ToolDefinitioninsrc/ToolRegistry.cs— its name, description, input schema, theReadOnlyflag (mutating tools passReadOnly: falseand receive adestructiveHintannotation), and a handler that binds arguments throughJsonRpcParametersand calls your method. The registry drives bothtools/listand dispatch; there is no separate switch to edit. Two tests keep it honest:ToolsListGoldenTestslocks the published schema byte-for-byte (re-capture the golden when a schema change is intentional), andToolSchemaParityTestsasserts every parameter the handler reads is declared in the schema.Build and publish:
dotnet build -c Release
dotnet publish -c Release -o ./publishAdd both test levels — a unit test of the
RoslynServicemethod against a deterministic fixture, AND a wire test through the MCP dispatcher (intests/SharpLensMcp.Tests/Mcp/) with exact value locks plus an error path. This is non-negotiable; see Testing.
Testing
Every test must satisfy the Testing Charter (C1–C9) in tests/SharpLensMcp.Tests/TESTING.md — the standing contract. The headline rules:
Lock exact values (C1): assert a concrete name / count / substring / error code /
(line, column)— neverNotBeNull/> 0/ a type-only check as the sole assertion.Both levels per tool (C4): a unit test against a
Fixtures/*.csfixture and a dispatcher (wire) test that unwrapscontent[0].text, plus an error path.Right casing (C3): in-process Newtonsoft yields PascalCase
error.Code/meta.TotalCount; the MCP wire yields camelCase. Read the casing your test's path actually produces.Deterministic (C7): the suite is serialized via
xunit.runner.json; fixture mutators always restore; the timeout test uses a forced-cancellation seam, not a timing race.Out-of-process spine (C6):
StdioIntegrationTestsvalue-pins one tool per category over the real binary and runs thetools/listgolden over the stdio pipe.Pre-commit gate (C9): build-clean + green is necessary but not sufficient — re-read each changed test and confirm it fails on a wrong answer.
Run the suite:
dotnet test -c ReleaseKey Files
File | Purpose |
| Tool implementations split by concern across ~30 partials (Navigation, Analysis, Refactoring, Inspection, Validation, TypeDiscovery, Discovery, ExternalApi, Quality, Metrics, CodeActions, CodeGeneration, Compound, CallAnalysis, ExceptionFlow, StackTrace, ApiSurface, SimilarCode, …) — each file's name predicts its contents |
| MCP protocol mechanics: JSON-RPC parse loop, |
| The tool surface: one |
| Typed JSON-RPC argument accessors and the |
| Typed records used by the audit composite, constructor generator, and signature-change parser (one type per file) |
License
MIT - See LICENSE for details.
Maintenance
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/pzalutski-pixel/sharplens-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server