SharpLensMcp 1.5.3

dotnet tool install --global SharpLensMcp --version 1.5.3
                    
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 SharpLensMcp --version 1.5.3
                    
This package contains a .NET tool you can call from the shell/command line.
#tool dotnet:?package=SharpLensMcp&version=1.5.3
                    
nuke :add-package SharpLensMcp --version 1.5.3
                    

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

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:

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
DOTNET_SOLUTION_PATH Path to .sln or .slnx file to auto-load on startup None (must call load_solution)
SHARPLENS_ABSOLUTE_PATHS Use absolute paths instead of relative false (relative paths save tokens)
ROSLYN_LOG_LEVEL Logging verbosity: Trace, Debug, Information, Warning, Error Information
ROSLYN_TIMEOUT_SECONDS Timeout for long-running operations 30
ROSLYN_MAX_DIAGNOSTICS Maximum diagnostics to return 100
ROSLYN_ENABLE_SEMANTIC_CACHE Enable semantic model caching true (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:

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

Tool Description
get_symbol_info Semantic info at position
go_to_definition Jump to symbol definition
find_references All references; each classified read/write/invocation/cast/typeof/nameof/attribute; optional kind filter
find_implementations Interface/abstract implementations
find_callers Impact analysis - who calls this?
get_call_graph Multi-hop callers/callees graph with depth bound + cycle detection
get_type_hierarchy Inheritance chain
search_symbols Glob pattern search (*Handler, Get*)
semantic_query Multi-filter search (async, public, etc.)
get_type_members All members by type name
get_type_members_batch Multiple types in one call
get_method_signature Detailed signature by name
get_derived_types Find all subclasses
get_base_types Full inheritance chain
get_attributes List attributes on a symbol
get_containing_member Enclosing symbol at position
get_method_overloads All overloads of a method
find_attribute_usages Find types/members by attribute
get_external_type_info Inspect NuGet/BCL/external assembly types — members + XML docs

Analysis (11 tools)

Tool Description
get_diagnostics Compiler errors/warnings + configured analyzer findings (StyleCop, Roslynator, NetAnalyzers); matches CI
analyze_data_flow Variable assignments and usage
analyze_control_flow Branching/reachability
analyze_change_impact What breaks if changed?
check_type_compatibility Can A assign to B?
get_outgoing_calls What does this method call?
find_unused_code Dead code detection
validate_code Compile check without writing
get_complexity_metrics Cyclomatic, nesting, LOC, cognitive
find_circular_dependencies Project and namespace cycle detection
get_missing_members Unimplemented interface/abstract members

Refactoring (14 tools)

Tool Description
rename_symbol Safe rename across solution
change_signature Add/remove/reorder parameters
extract_method Extract with data flow analysis
extract_interface Generate interface from class
generate_constructor From fields/properties
organize_usings Sort and remove unused
organize_usings_batch Batch organize multiple files
format_document_batch Batch format files in project
get_code_actions_at_position All Roslyn refactorings at position
apply_code_action_by_title Apply any refactoring by title
implement_missing_members Generate interface stubs
encapsulate_field Field to property
inline_variable Inline temp variable
extract_variable Extract expression to variable

Code Generation (2 tools)

Tool Description
add_null_checks Generate ArgumentNullException guards
generate_equality_members Equals/GetHashCode/operators

Compound Tools (7 tools)

Tool Description
get_type_overview Full type info in one call
analyze_method Signature + callers + outgoing calls + location
get_file_overview File summary with diagnostics
get_method_source Source code by name
get_method_source_batch Multiple method sources in one call
get_instantiation_options How to create a type
get_project_health Composite audit dashboard: diagnostics + unused + coupling + coverage per project

Audit & Quality (2 tools)

Tool Description
find_god_objects Detect over-coupled types via efferent + afferent coupling + member-count thresholds
find_untested_code Find public surface not reached by any [Fact]/[Theory]/[Test]/[TestMethod]

Discovery (2 tools)

Tool Description
get_di_registrations Scan DI service registrations
find_reflection_usage Detect reflection/dynamic usage

Infrastructure (10 tools)

Tool Description
health_check Server status
load_solution Load .sln/.slnx for analysis
sync_documents Sync file changes into loaded solution
get_project_structure Solution structure
dependency_graph Project dependencies
get_code_fixes Available fixes for a diagnostic
apply_code_fix Apply a specific code fix
get_nuget_dependencies NuGet package listing per project
get_source_generators List active source generators
get_generated_code 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

  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

File Purpose
src/RoslynService.cs + src/RoslynService.*.cs partials Tool implementations split by concern: Navigation, Analysis, Refactoring, Inspection, Validation, TypeDiscovery, Discovery, ExternalApi, Quality, CodeActions, CodeGeneration, Compound
src/McpServer.cs MCP protocol, tool definitions, dispatcher (uses typed JsonRpcParameters helper)
src/JsonRpcParameters.cs + JsonRpcInvalidParamsException.cs Typed JSON-RPC argument accessors and the -32602 Invalid params exception they raise
src/QualityAuditData.cs, ConstructorMember.cs, SignatureChange.cs Typed records used by the audit composite, constructor generator, and signature-change parser

License

MIT - See LICENSE for details.

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 was computed.  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
1.5.3 133 5/20/2026
1.5.2 666 4/17/2026
1.5.1 206 4/16/2026
1.5.0 296 4/8/2026
1.4.2 122 4/8/2026
1.4.1 101 4/8/2026
1.4.0 111 4/4/2026
1.3.2 153 3/26/2026
1.3.1 97 3/26/2026
1.3.0 96 3/25/2026
1.2.5 603 1/12/2026
1.2.4 127 1/1/2026
1.2.3 112 12/29/2025
1.2.2 121 12/28/2025
1.2.1 111 12/27/2025
1.2.0 109 12/27/2025
1.1.1 116 12/27/2025
1.1.0 111 12/27/2025
1.0.0 111 12/27/2025

v1.5.3
Added:
- get_external_type_info
- get_call_graph
- find_untested_code
- find_god_objects
- get_project_health
Changed:
- get_diagnostics runs DiagnosticAnalyzers by default
- find_references reports cast kind + filter
- health_check uses standard {success,data,meta} envelope
- change_signature, extract_method, apply_code_fix apply on preview:false
Fixed:
- get_source_generators surfaces real generator type
- get_instantiation_options externalFactories on generator projects
- get_code_actions_at_position returns real refactorings
- search_symbols pagination, find_god_objects coupling
- JSON-RPC notification compliance
- 15 more (see CHANGELOG.md)
Tests: 127 → 543
v1.5.2: Run source generators so tools see generator-produced code (#7). Fixes phantom CS0117, missed references, wrong unused-code results for projects with generators.
v1.5.1: Fixed notifications/initialized breaking MCP client connections (#6).
v1.5.0: Added 7 discovery tools: attribute usages, DI registrations, reflection detection, circular dependencies, NuGet dependencies, source generators, generated code viewer.
v1.4.2: Split release workflow into separate jobs for reliability. MCP Registry publishing.
v1.4.1: Added MCP Registry publishing. Listed on registry.modelcontextprotocol.io.
v1.4.0: Fixed JSON-RPC id handling to accept string and integer per spec. npm launcher now pins version.
v1.3.2: Added npm README and badge.
v1.3.1: Added npm wrapper package (npx -y sharplens-mcp) for MCP ecosystem discoverability.
v1.3.0: Fixed MSBuild locator for .NET 9/10+. RollForward enabled. Upgraded MSBuildLocator to 1.11.2. Works with .NET 8+.
v1.2.5: Added .slnx solution format support. Upgraded to Roslyn 5.0.0.
v1.2.4: Added GitHub Actions CI/CD for trusted builds. Source Link enabled for source traceability.
v1.2.3: Fixed sync_documents adding unwanted Compile Include entries to .csproj files.
v1.2.2: Added sync_documents for agent-controlled document synchronization after external edits.
v1.2.1: Relative paths by default (saves tokens). Cross-platform path normalization.
v1.2.0: Added get_method_source_batch for batch method lookups. Enhanced analyze_method with includeOutgoingCalls parameter.
v1.1.1: Documentation update - Added Claude Code setup guide and configuration reference.
v1.1.0: Added 10 new tools (57 total).