Back to MCP Servers

Sharplens

58 semantic C#/.NET analysis tools via Roslyn. Navigation, refactoring, find usages, and code intelligence for AI agents.

developer-toolsaiagent
By pzalutski-pixel
228Updated 2 weeks agoC#MIT

Installation

npx -y sharplens-mcp

Configuration

{
  "mcpServers": {
    "sharplens-mcp": {
      "command": "npx",
      "args": ["-y", "sharplens-mcp"]
    }
  }
}

How to use

  1. Run the installation command above (if needed)
  2. Open your Claude Code settings file (~/.claude/settings.json)
  3. Add the configuration to the mcpServers section
  4. Restart Claude Code to apply changes

SharpLensMcp

NuGet npm License: MIT

A Model Context Protocol (MCP) server providing 67 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 SharpLensMcp

Then run with:

sharplens

Via npm

npx -y sharplens-mcp

Build from Source

dotnet build -c Release
dotnet publish -c Release -o ./publish

Claude Code Setup

  1. Install the tool (pick one):
dotnet tool install -g SharpLensMcp
# or
npx -y sharplens-mcp
  1. Create .mcp.json in your project root:
{
  "mcpServers": {
    "sharplens": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "sharplens-mcp"],
      "env": {
        "DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"
      }
    }
  }
}
  1. Restart Claude Code to load the MCP server

  2. 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:

CapabilityNative LSPSharpLensMcp
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 VariableDescriptionDefault
DOTNET_SOLUTION_PATHPath to .sln or .slnx file to auto-load on startupNone (must call load_solution)
SHARPLENS_ABSOLUTE_PATHSUse absolute paths instead of relativefalse (relative paths save tokens)
ROSLYN_LOG_LEVELLogging verbosity: Trace, Debug, Information, Warning, ErrorInformation
ROSLYN_TIMEOUT_SECONDSTimeout for long-running operations30
ROSLYN_MAX_DIAGNOSTICSMaximum diagnostics to return100
ROSLYN_ENABLE_SEMANTIC_CACHEEnable semantic model cachingtrue (set to false to disable)

If DOTNET_SOLUTION_PATH is not set, you must call the load_solution tool before using other tools.

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:

  1. Claude Code: Add to your project's CLAUDE.md:

    For C# code analysis, prefer SharpLensMcp tools over native tools:
    - Use `roslyn:search_symbols` instead of Grep for finding symbols
    - Use `roslyn:get_method_source` instead of Read for viewing methods
    - Use `roslyn:find_references` for semantic (not text) references
  2. Other 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:

ActionCall sync_documents?
Used Edit tool to modify .cs filesYes
Used Write tool to create new .cs filesYes
Deleted .cs filesYes
Used SharpLensMcp refactoring tools (rename, extract, etc.)❌ No (auto-updated)
Modified .csproj files❌ No (use load_solution instead)

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

  • 67 Semantic Analysis Tools - Navigation, refactoring, code generation, diagnostics, discovery, audit/quality
  • AI-Optimized Descriptions - Clear USAGE/OUTPUT/WORKFLOW patterns
  • Structured Responses - Consistent success/error/data format with suggestedNextTools
  • Zero-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 (19 tools)

ToolDescription
get_symbol_infoSemantic info at position
go_to_definitionJump to symbol definition
find_referencesAll references; each classified read/write/invocation/cast/typeof/nameof/attribute; optional kind filter
find_implementationsInterface/abstract implementations
find_callersImpact analysis - who calls this?
get_call_graphMulti-hop callers/callees graph with depth bound + cycle detection
get_type_hierarchyInheritance chain
search_symbolsGlob pattern search (*Handler, Get*)
semantic_queryMulti-filter search (async, public, etc.)
get_type_membersAll members by type name
get_type_members_batchMultiple types in one call
get_method_signatureDetailed signature by name
get_derived_typesFind all subclasses
get_base_typesFull inheritance chain
get_attributesList attributes on a symbol
get_containing_memberEnclosing symbol at position
get_method_overloadsAll overloads of a method
find_attribute_usagesFind types/members by attribute
get_external_type_infoInspect NuGet/BCL/external assembly types — members + XML docs

Analysis (11 tools)

ToolDescription
get_diagnosticsCompiler errors/warnings + configured analyzer findings (StyleCop, Roslynator, NetAnalyzers); matches CI
analyze_data_flowVariable assignments and usage
analyze_control_flowBranching/reachability
analyze_change_impactWhat breaks if changed?
check_type_compatibilityCan A assign to B?
get_outgoing_callsWhat does this method call?
find_unused_codeDead code detection
validate_codeCompile check without writing
get_complexity_metricsCyclomatic, nesting, LOC, cognitive
find_circular_dependenciesProject and namespace cycle detection
get_missing_membersUnimplemented interface/abstract members

Refactoring (14 tools)

ToolDescription
rename_symbolSafe rename across solution
change_signatureAdd/remove/reorder parameters
extract_methodExtract with data flow analysis
extract_interfaceGenerate interface from class
generate_constructorFrom fields/properties
organize_usingsSort and remove unused
organize_usings_batchBatch organize multiple files
format_document_batchBatch format files in project
get_code_actions_at_positionAll Roslyn refactorings at position
apply_code_action_by_titleApply any refactoring by title
implement_missing_membersGenerate interface stubs
encapsulate_fieldField to property
inline_variableInline temp variable
extract_variableExtract expression to variable

Code Generation (2 tools)

ToolDescription
add_null_checksGenerate ArgumentNullException guards
generate_equality_membersEquals/GetHashCode/operators

Compound Tools (7 tools)

ToolDescription
get_type_overviewFull type info in one call
analyze_methodSignature + callers + outgoing calls + location
get_file_overviewFile summary with diagnostics
get_method_sourceSource code by name
get_method_source_batchMultiple method sources in one call
get_instantiation_optionsHow to create a type
get_project_healthComposite audit dashboard: diagnostics + unused + coupling + coverage per project

Audit & Quality (2 tools)

ToolDescription
find_god_objectsDetect over-coupled types via efferent + afferent coupling + member-count thresholds
find_untested_codeFind public surface not reached by any [Fact]/[Theory]/[Test]/[TestMethod]

Discovery (2 tools)

ToolDescription
get_di_registrationsScan DI service registrations
find_reflection_usageDetect reflection/dynamic usage

Infrastructure (10 tools)

ToolDescription
health_checkServer status
load_solutionLoad .sln/.slnx for analysis
sync_documentsSync file changes into loaded solution
get_project_structureSolution structure
dependency_graphProject dependencies
get_code_fixesAvailable fixes for a diagnostic
apply_code_fixApply a specific code fix
get_nuget_dependenciesNuGet package listing per project
get_source_generatorsList active source generators
get_generated_codeView 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

  1. Load a solution: Call roslyn:load_solution with path to .sln or .slnx file (or set DOTNET_SOLUTION_PATH)
  2. Analyze code: Use any of the 67 tools for navigation, analysis, refactoring, audit
  3. Refactor safely: Preview changes before applying with preview: true

Architecture

MCP Client (AI Agent)
        | stdin/stdout (JSON-RPC 2.0)
        v
   SharpLensMcp
   - Protocol handling
   - 67 AI-optimized tools
        |
        v
Microsoft.CodeAnalysis (Roslyn)
  - MSBuildWorkspace
  - SemanticModel
  - SymbolFinder

Requirements

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

Development

Adding New Tools

  1. Add method to src/RoslynService.cs:
public async Task<object> YourToolAsync(string param1, int? param2 = null)
{
    EnsureSolutionLoaded();
    // Your logic...
    return CreateSuccessResponse(
        data: new { /* results */ },
        suggestedNextTools: new[] { "next_tool_hint" }
    );
}
  1. Add tool definition to src/McpServer.cs in HandleListToolsAsync

  2. Add routing to src/McpServer.cs in HandleToolCallAsync switch

  3. Build and publish:

dotnet build -c Release
dotnet publish -c Release -o ./publish

Key Files

FilePurpose
src/RoslynService.cs + src/RoslynService.*.cs partialsTool implementations split by concern: Navigation, Analysis, Refactoring, Inspectio

View source on GitHub