convez.ai
MCP ServerProdutividadeAvançado
mdziadowiec

DotNetLensMCP

mdziadowiec/DotNetLensMCP

Análise semântica precisa e refatoração segura para codebases .NET com IA

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP com 74 ferramentas otimizadas para IA que fornece análise semântica de código .NET usando Roslyn. Suporta navegação, refatoração, geração de código e análise de qualidade em C# e VB.NET, com capacidades que excedem LSP nativo como detecção de código morto, análise de fluxo de dados e decompilação de IL.

Instalação

$npx convez-ai mdziadowiec/DotNetLensMCP

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
3
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 4 meses
Versão
—
Issues abertas
0
Contribuidores
1

Casos de uso

  • Análise de impacto em refatorações de código .NET
  • Detecção de código morto e violações de padrão em C# e VB.NET
  • Geração automática de construtores, igualdade e verificações nulas
  • Inspeção de assemblies externos via decompilação ILSpy
  • Análise de complexidade e detecção de dependências circulares

Veredito

Ferramenta madura e robusta para equipes .NET que precisam de análise de código em nível compilador. A cobertura de 74 ferramentas especializadas e suporte bidirecional C#/VB.NET a tornam excepcional para refatoração segura e qualidade de código, embora exija .NET 10 SDK e tenha limitações em VB.NET para geração de código.

README

A tradução para o português deste README ainda está na fila.

DotNetLensMcp

License

A Model Context Protocol (MCP) server providing 74 AI-optimized tools for .NET semantic code analysis, navigation, refactoring, and code generation using Microsoft Roslyn.

DotNetLensMcp is a fork of sharplens-mcp extended with VB.NET support and ILSpy-backed decompilation tools ported from roslyn-codelens-mcp. Semantic and symbol-level tools work across both C# and VB.NET. Syntax-level refactoring and code generation remain C#-only with graceful "not supported" responses for .vb files.

Built for AI coding agents — provides compiler-accurate code understanding that AI cannot infer from reading source files alone.

Features

  • 74 tools — Navigation, analysis, refactoring, code generation, quality analysis, decompilation, and diagnostics
  • C# and VB.NET support — Navigation, analysis, quality analysis, and decompilation work across both languages; code generation and most refactoring are C# only
  • Compiler-accurate analysis — Powered by Roslyn; resolves semantic references, not text matches
  • ILSpy decompilation — Browse IL bytecode and external assembly APIs without access to source
  • Preview mode — Inspect refactoring changes before applying them
  • Batch operations — Multiple lookups in one call to reduce context usage
  • Structured responses — Consistent success/error/data format with suggestedNextTools to chain tools efficiently

Why Use This with Claude Code?

Claude Code's built-in LSP covers basic navigation. DotNetLensMcp adds compiler-accurate analysis that LSP and text search cannot provide:

CapabilityNative LSPDotNetLensMcp
Impact analysis — what callers/types break if this changes?❌✅
Dead code detection❌✅
Data flow & control flow analysis❌✅
Complexity metrics (cyclomatic, cognitive, nesting depth)❌✅
Circular dependency detection❌✅
Call graph traversal❌✅
Async violations (async void, .Result/.Wait() blocking)❌✅
IDisposable misuse detection❌✅
Naming violations, god objects & large class detection❌✅
Safe refactoring with preview before apply❌✅
Code generation (constructors, equality members, null checks)❌✅
IL decompilation & external assembly inspection❌✅
Source generator introspection❌✅
DI registration scanning❌✅
Batch lookups in one call❌✅

Language Support

CapabilityC#VB.NET
Navigation & discovery✅✅
Analysis✅✅ (9/11 tools)
Refactoring✅✅ (2/15 tools)
Code generation✅❌
Quality analysis✅✅ (8/10 tools)
Decompilation✅✅

Unsupported tools return a structured VB_NOT_SUPPORTED error — they never crash or return misleading output.

Requirements

  • .NET 10.0 SDK or later — required to build and run the MCP server
  • Analyzes .NET solutions containing C# projects, VB.NET projects, or both, including projects targeting earlier supported .NET TFMs
  • MCP-compatible AI agent

Installation

git clone https://github.com/mdziadowiec/DotNetLensMCP
cd DotNetLensMCP
dotnet publish src -c Release -o ./publish

Run with:

dotnet publish/DotNetLensMcp.dll

For the upstream NuGet/npm packages (dotnet tool install -g SharpLensMcp / npx -y sharplens-mcp), see the original sharplens-mcp repository. Those packages do not include VB.NET support.

Configuration

Environment VariableDescriptionDefault
DOTNET_SOLUTION_PATHPath to .sln or .slnx file to auto-load on startupNone (must call load_solution)
DOTNETLENS_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 Roslyn operations (compilation, reference search); returns a structured TIMEOUT error when exceeded30
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.

Claude Code Setup

  1. Build and publish (see Installation)

  2. Create .mcp.json in your project root:

{
  "mcpServers": {
    "dotnetlens": {
      "type": "stdio",
      "command": "dotnet",
      "args": ["/absolute/path/to/publish/DotNetLensMcp.dll"],
      "env": {
        "DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln"
      }
    }
  }
}
  1. Restart Claude Code to load the MCP server

  2. Verify by asking Claude to run a health check on the Roslyn server

CLAUDE.md tip

Add to your project's CLAUDE.md to steer Claude toward the semantic tools:

For .NET code analysis (C# and VB.NET), prefer DotNetLensMcp tools over native tools:

Navigation & lookup:
- Use `roslyn_search_symbols` instead of Grep for finding types, methods, and members by name
- Use `roslyn_go_to_definition` to jump to any symbol's declaration
- Use `roslyn_get_method_source` instead of Read for viewing a method body without opening the full file
- Use `roslyn_get_type_members` to inspect all members of a type before reading its source

Impact analysis:
- Use `roslyn_find_references` for semantic (not text) references — won't miss renamed symbols
- Use `roslyn_find_callers` before changing a method signature to see all call sites
- Use `roslyn_analyze_change_impact` to predict what breaks before making a change

Code quality:
- Use `roslyn_find_async_violations` to detect async void / .Result blocking / fire-and-forget
- Use `roslyn_find_disposable_misuse` to catch IDisposable variables declared without using
- Use `roslyn_get_diagnostics` to get compiler errors/warnings for a file

After editing files with Edit or Write tools, always call `roslyn_sync_documents` to keep the
Roslyn workspace in sync before running further analysis tools.

VB.NET support is noted in each tool's description — tools that don't support it say so explicitly.

Agent Responsibility: Document Synchronization

DotNetLensMcp maintains an in-memory representation of your solution. When files are modified externally (via Edit/Write tools), the agent must synchronize changes. This applies equally to .cs and .vb files.

ActionCall sync_documents?
Used Edit tool to modify .cs or .vb files✅ Yes
Used Write tool to create new source files✅ Yes
Deleted source files✅ Yes
Used DotNetLensMcp refactoring tools (rename, extract, etc.)❌ No (auto-updated)
Modified .csproj or .vbproj files❌ No (use load_solution instead)
# After editing specific files
sync_documents(filePaths: ["src/MyClass.cs", "src/MyModule.vb"])

# After bulk changes - sync all documents
sync_documents()

Tool Reference

✅ full support · ❌ returns VB_NOT_SUPPORTED · ⚠️ VB files skipped silently (no error)

Navigation & Discovery (17 tools)

ToolDescriptionC#VB.NET
get_symbol_infoSemantic info at position✅✅
go_to_definitionJump to symbol definition✅✅
find_referencesAll references across solution✅✅
find_implementationsInterface/abstract implementations✅✅
find_callersImpact analysis — who calls this?✅✅
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✅✅

Analysis (11 tools)

ToolDescriptionC#VB.NET
get_diagnosticsCompiler errors/warnings✅✅
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✅✅
get_complexity_metricsCyclomatic, nesting, LOC, cognitive✅✅
find_circular_dependenciesProject and namespace cycle detection✅✅
get_missing_membersUnimplemented interface/abstract members✅✅
analyze_data_flowVariable assignments and usage✅❌
analyze_control_flowBranching/reachability✅❌
validate_codeCompile check without writing✅✅

Refactoring (15 tools)

ToolDescriptionC#VB.NET
rename_symbolSafe rename across solution✅✅
change_signatureAdd/remove/reorder parameters✅❌
extract_methodExtract with data flow analysis✅❌
extract_interfaceGenerate interface from class✅❌
organize_usingsSort and remove unused✅❌
organize_usings_batchBatch organize across project✅⚠️
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✅❌
get_code_fixes / apply_code_fixDiagnostic-driven fixes✅❌

Code Generation (3 tools)

ToolDescriptionC#VB.NET
add_null_checksGenerate ArgumentNullException guards✅❌
generate_equality_membersEquals/GetHashCode/operators✅❌
generate_constructorGenerate constructor from fields/properties✅❌

Compound Tools (6 tools)

ToolDescriptionC#VB.NET
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✅✅

Discovery (2 tools)

ToolDescriptionC#VB.NET
get_di_registrationsScan DI service registrations✅⚠️
find_reflection_usageDetect reflection/dynamic usage✅⚠️

Quality Analysis (10 tools)

ToolDescriptionC#VB.NET
find_large_classesTypes exceeding member-count or line-count thresholds✅✅
get_public_api_surfaceEnumerate all public/protected types and members✅✅
get_operatorsUser-defined operators and conversions on a type✅✅
find_obsolete_usageEvery [Obsolete] call site grouped by severity✅✅
get_call_graphBFS caller/callee graph, depth-bounded, cycle-safe✅✅
find_async_violationsasync void, .Result/.Wait() blocking, fire-and-forget✅✅
find_disposable_misuseIDisposable variables declared without using✅✅
find_event_subscribersAll +=/-= handlers for an event✅✅
find_naming_violationsPascalCase, _field, IInterface convention checks✅⚠️
find_god_objectsLarge types with high outgoing namespace coupling✅⚠️

Decompilation (2 tools)

ToolDescriptionC#VB.NET
peek_ilDisassemble a method from a referenced assembly to MSIL bytecode✅✅
inspect_external_assemblyBrowse the public API surface of any referenced assembly✅✅

Infrastructure (8 tools)

ToolDescriptionC#VB.NET
health_checkServer status✅✅
load_solutionLoad .sln/.slnx (mixed-language solutions supported)✅✅
sync_documentsSync file changes into loaded solution✅✅
get_project_structureSolution structure (shows language per project)✅✅
dependency_graphProject dependencies✅✅
get_nuget_dependenciesNuGet package listing per project✅✅
get_source_generatorsList active source generators✅✅
get_generated_codeView generated source code✅✅

Architecture

MCP Client (AI Agent)
        | stdin/stdout (JSON-RPC 2.0)
        v
   DotNetLensMcp
   - Protocol handling
   - 74 AI-optimized tools
   - VB.NET language guards
        |
        v
Microsoft.CodeAnalysis (Roslyn)
  - MSBuildWorkspace
  - Microsoft.CodeAnalysis.CSharp
  - Microsoft.CodeAnalysis.VisualBasic   ← VB.NET support
  - SemanticModel / SymbolFinder

Development

Project Structure

File / FolderPurpose
src/RoslynService.csCore workspace service, language helpers, compilation cache, source-generator handling
src/RoslynService/Language/C#/VB strategy-pattern implementations; language-specific helpers
src/RoslynService/Navigation/Symbol navigation tools (C#+VB)
src/RoslynService/Analysis/Diagnostics, project structure, organize/format tools
src/RoslynService/Refactoring/Refactoring tools (C# only, guarded)
src/RoslynService/CodeActions/Code actions (C# only, guarded)
src/RoslynService/CodeGeneration/Code generation tools (C# only, guarded)
src/RoslynService/Compound/Data/control-flow compound tools (C# only, guarded)
src/RoslynService/TypeDiscovery/Type/member queries (C#+VB)
src/RoslynService/Discovery/Discovery tools for attributes, DI, reflection, packages, and source generators
src/RoslynService/QualityAnalysis/Quality analysis tools — large classes, god objects, naming, async/disposable violations, call graph, etc.
src/RoslynService/Decompilation/ILSpy-backed tools — peek IL, inspect external assembly; PEFileCache, IlDisassemblerAdapter helpers
src/McpServer.csMCP protocol loop and JSON-RPC handling
src/ToolCatalog.csMCP tool definitions and input schemas
src/McpToolCallHandler.csTool routing and argument mapping
src/ErrorCodes.csStructured error code constants (includes VB_NOT_SUPPORTED)

Adding New Tools

  1. Add method to the appropriate src/RoslynService/<Category>/ file:
public async Task<object> YourToolAsync(string filePath, int? param = null)
{
    EnsureSolutionLoaded();

    // Guard VB.NET if the tool uses C#-specific syntax APIs
    if (await GetCSharpOnlyToolErrorAsync(filePath, "your_tool") is { } unsupportedLanguageError)
        return unsupportedLanguageError;

    // Your logic...
    return CreateSuccessResponse(
        data: new { /* results */ },
        suggestedNextTools: new[] { "next_tool_hint" }
    );
}
  1. Add tool definition to src/ToolCatalog.cs

  2. Add routing in src/McpToolCallHandler.cs

  3. Write tests — add a VB.NET variant in tests/DotNetLensMcp.Tests/VbNetTests.cs if the tool should support VB.NET, or assert VB_NOT_SUPPORTED if it should not. ToolCatalogTests verifies catalog entries are routed.

VB.NET Guard Pattern

All C# syntax-level tools use a document-language guard immediately after EnsureSolutionLoaded():

if (await GetCSharpOnlyToolErrorAsync(filePath, "tool_name") is { } unsupportedLanguageError)
    return unsupportedLanguageError;

The guard resolves the Roslyn Document and checks document.Project.Language, with a .vb path fallback only when the document cannot be resolved. VbNotSupportedResponse returns a structured error with code VB_NOT_SUPPORTED and a descriptive message explaining which tools do support VB.NET.

Running Tests

# All tests
dotnet test

# VB.NET tests only
dotnet test --filter "FullyQualifiedName~VbNetTests"

The VB.NET integration tests load tests/DotNetLensMcp.Tests/TestSolutions/VbNetSample/ (a standalone VB.NET library) and TestSolutions/MixedSample/ (a mixed C#+VB.NET solution).

Credits

  • sharplens-mcp by Peter Zalutski — core MCP server architecture, Roslyn workspace integration, and C# analysis tools that this project is forked from.
  • roslyn-codelens-mcp by Marcel Roozekrans — ILSpy-backed decompilation tools (roslyn_peek_il, roslyn_inspect_external_assembly) ported into this fork.
  • ILSpy / ICSharpCode.Decompiler — MSIL disassembly engine (MIT).

License

Apache 2.0 — See LICENSE and NOTICE for details.

Ver o original no GitHub

Bom para

Relacionados