Skip to main content
Glama

SharpLensMcp

NuGet npm License: MIT

Un servidor del Protocolo de Contexto de Modelo (MCP) que proporciona 92 herramientas optimizadas para IA para análisis semántico de código .NET/C#, navegación, refactorización y generación de código utilizando Microsoft Roslyn.

Construido para agentes de codificación de IA: proporciona una comprensión del código precisa a nivel de compilador que la IA no puede inferir solo con leer los archivos fuente.

Instalación

Vía NuGet (Recomendado)

dotnet tool install -g SharpLensMcp

Luego ejecute con:

sharplens

Vía npm

npx -y sharplens-mcp

Compilar desde el código fuente

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

Related MCP server: LSP-MCP

Configuración de Claude Code

  1. Instale la herramienta (elija una):

dotnet tool install -g SharpLensMcp
# or
npx -y sharplens-mcp
  1. Cree .mcp.json en la raíz de su proyecto:

{
  "mcpServers": {
    "sharplens": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "sharplens-mcp"],
      "env": {
        "DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"
      }
    }
  }
}
  1. Reinicie Claude Code para cargar el servidor MCP

  2. Verifique pidiéndole a Claude que ejecute una verificación de estado en el servidor Roslyn

¿Por qué usar esto con Claude Code?

Claude Code tiene soporte nativo de LSP para navegación básica (ir a definición, buscar referencias). SharpLensMcp añade análisis semántico profundo:

Capacidad

LSP nativo

SharpLensMcp

Ir a definición

✅

✅

Buscar referencias

✅

✅

Encontrar métodos asíncronos que faltan CancellationToken

❌

✅

Análisis de impacto (¿qué se rompe?)

❌

✅

Detección de código muerto

❌

✅

Métricas de complejidad

❌

✅

Refactorización segura con vista previa

❌

✅

Operaciones por lotes

❌

✅

Configuración

Variable de Entorno

Descripción

Valor por Defecto

DOTNET_SOLUTION_PATH

Ruta al archivo .sln o .slnx para cargar automáticamente al inicio

Ninguno (debe llamar a load_solution)

SHARPLENS_ABSOLUTE_PATHS

Usar rutas absolutas en lugar de relativas

false (rutas relativas ahorran tokens)

SHARPLENS_LOG_LEVEL

Nivel de detalle del registro: Trace, Debug, Information, Warning, Error

Information

SHARPLENS_TIMEOUT_SECONDS

Tiempo de espera para operaciones de larga duración

30

SHARPLENS_MAX_DIAGNOSTICS

Máximo de diagnósticos a devolver

100

SHARPLENS_ENABLE_SEMANTIC_CACHE

Habilitar almacenamiento en caché del modelo semántico

true (establecer a false para deshabilitar)

Las grafías ROSLYN_* de las últimas cuatro variables anteriores a la versión 1.6.0 todavía se leen como respaldo durante una versión; la grafía SHARPLENS_* prevalece cuando ambas están configuradas.

Si DOTNET_SOLUTION_PATH no está configurado, debe llamar a la herramienta load_solution antes de usar otras herramientas.

Migración desde nombres de herramientas 1.5.x

Los nombres de las herramientas ya no llevan el prefijo roslyn: — los dos puntos violan el patrón de nombre de herramienta MCP (^[a-zA-Z0-9_-]{1,64}$), que algunos clientes aplican. Cada herramienta conserva su nombre sin el prefijo:

Nombre 1.5.x

Nombre 1.6.0

roslyn:load_solution

load_solution

roslyn:get_diagnostics

get_diagnostics

roslyn:rename_symbol

rename_symbol

...misma regla para todas las herramientas...

eliminar el prefijo roslyn:

tools/list publica solo los nuevos nombres. Las llamadas que usan los antiguos nombres con prefijo todavía se aceptan como alias durante una versión y se eliminarán en la siguiente.

Consejos de Configuración para Agentes de IA

Los modelos de IA pueden tener un sesgo entrenado hacia el uso de sus herramientas nativas (Grep, Read, LSP) en lugar de las herramientas del servidor MCP, incluso cuando SharpLensMcp proporciona mejores capacidades.

Para garantizar un uso óptimo de las herramientas:

  1. Claude Code: Añada a CLAUDE.md de su proyecto:

    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) references
  2. Otros clientes MCP: Configure la prioridad de las herramientas en el mensaje del sistema de su agente

El análisis semántico de Roslyn es más preciso que la búsqueda basada en texto, especialmente para métodos sobrecargados, clases parciales y jerarquías de herencia.

Responsabilidad del Agente: Sincronización de Documentos

Importante: SharpLensMcp mantiene una representación en memoria de su solución para consultas rápidas. Cuando los archivos se modifican externamente (a través de herramientas de Edición/Escritura), el agente es responsable de sincronizar los cambios.

Cuándo llamar a sync_documents:

Acción

¿Llamar a sync_documents?

Usó la herramienta Editar para modificar archivos .cs

✅ Sí

Usó la herramienta Escribir para crear nuevos archivos .cs

✅ Sí

Eliminó archivos .cs

✅ Sí

Usó herramientas de refactorización de SharpLensMcp (renombrar, extraer, etc.)

❌ No (se actualiza automáticamente)

Modificó archivos .csproj

❌ No (use load_solution en su lugar)

Uso:

# After editing specific files
sync_documents(filePaths: ["src/MyClass.cs", "src/MyService.cs"])

# After bulk changes - sync all documents
sync_documents()

¿Por qué este diseño?

Esto refleja cómo funciona LSP (Protocolo de Servidor de Lenguaje) - el cliente (editor) notifica al servidor de los cambios. Este enfoque:

  • Elimina condiciones de carrera (el agente controla el tiempo)

  • Evita la complejidad del observador de archivos y peculiaridades de la plataforma

  • Es más rápido que una recarga completa de la solución

  • Da a los agentes control explícito sobre el estado del espacio de trabajo

Si no sincroniza: Las consultas pueden devolver datos obsoletos (firmas de métodos antiguas, archivos nuevos faltantes, etc.)

Características

  • 92 Herramientas de Análisis Semántico - Navegación, refactorización, generación de código, diagnósticos, descubrimiento, auditoría/calidad

  • Descripciones Optimizadas para IA - Patrones claros de USO/SALIDA/FLUJO DE TRABAJO

  • Respuestas Estructuradas - Formato consistente success/error/data con suggestedNextTools

  • Coordenadas Basadas en Cero - Advertencias claras para prevenir errores de uno en uno

  • Modo de Vista Previa - Refactorización segura con vista previa antes de aplicar

  • Operaciones por Lotes - Múltiples consultas en una sola llamada para reducir el uso de contexto

Categorías de Herramientas

Navegación y Descubrimiento (24 herramientas)

Herramienta

Descripción

get_symbol_info

Información semántica en una posición

go_to_definition

Saltar a la definición del símbolo

find_references

Todas las referencias; cada una clasificada lectura/escritura/invocación/cast/typeof/nameof/atributo; filtro opcional kind

find_implementations

Implementaciones de interfaz/abstractas

find_callers

Análisis de impacto - ¿quién llama a esto?

get_call_graph

Grafo de llamantes/llamados de múltiples saltos con límite de profundidad + detección de ciclos

find_path_between

Accesibilidad + la(s) ruta(s) de llamada(s) de conexión entre dos métodos; sigue el envío, con barreras y un punto de control

get_type_hierarchy

Cadena de herencia

search_symbols

Búsqueda con patrón glob (*Handler, Get*)

semantic_query

Búsqueda con múltiples filtros (asíncrono, público, etc.)

get_type_members

Todos los miembros por nombre de tipo

get_type_members_batch

Múltiples tipos en una sola llamada

get_method_signature

Firma detallada por nombre

get_derived_types

Encontrar todas las subclases

get_base_types

Cadena de herencia completa

get_attributes

Listar atributos en un símbolo

get_containing_member

Símbolo contenedor en una posición

get_method_overloads

Todas las sobrecargas de un método

find_attribute_usages

Encontrar tipos/miembros por atributo

get_external_type_info

Inspeccionar tipos de ensamblados NuGet/BCL/externos — miembros + documentación XML

resolve_stack_trace

Mapear un seguimiento de pila pegado a archivo/línea/símbolo, con desorden deshecho

get_extension_methods

Extensiones que se aplican a un tipo — clásicas y bloques de C# 14

get_documentation

Documentación XML completa para un símbolo con <inheritdoc> expandido

get_super_method

Navegar al miembro base / miembros de interfaz que un miembro implementa

Análisis (17 herramientas)

Herramienta

Descripción

get_diagnostics

Errores/advertencias del compilador + hallazgos de analizadores configurados (StyleCop, Roslynator, NetAnalyzers); coincide con CI

diff_api_surface

Informe de cambios disruptivos de API pública vs una referencia de git

get_exception_flow

Qué excepciones pueden escapar de un método y dónde se capturan

find_similar_code

Búsqueda de similitud estructural (huellas de fichas token)

remove_unused_code

Calcular eliminaciones de código muerto + usings recién no utilizados (solo generación)

find_dead_branches

Bloques básicos inalcanzables por método (CFG real, no heurísticas)

add_missing_imports

Calcular los usings que corrigen CS0246/CS0103 (solo generación)

analyze_data_flow

Asignaciones y uso de variables

analyze_control_flow

Ramificación/accesibilidad

analyze_change_impact

¿Qué se rompe si se cambia?

check_type_compatibility

¿Puede A asignarse a B?

get_outgoing_calls

¿Qué llama este método?

find_unused_code

Detección de código muerto

validate_code

Verificación de compilación sin escribir

get_complexity_metrics

Complejidad ciclomática, anidamiento, LOC, cognitiva

find_circular_dependencies

Detección de ciclos en proyectos y espacios de nombres

get_missing_members

Miembros de interfaz/abstractos no implementados

Reestructuración (16 herramientas)

Herramienta

Descripción

rename_symbol

Renombrar seguro en toda la solución

change_signature

Agregar/eliminar/reordenar parámetros

extract_method

Extraer con análisis de flujo de datos

extract_interface

Generar interfaz a partir de una clase

generate_constructor

A partir de campos/propiedades

move_type_to_file

Calcular el contenido para mover un tipo a su propio archivo (solo generación)

split_type

Calcular una división de clase parcial para miembros seleccionados (solo generación)

organize_usings

Ordenar y eliminar no utilizados

organize_usings_batch

Organizar por lotes varios archivos

format_document_batch

Formatear por lotes archivos en el proyecto

get_code_actions_at_position

Todas las refactorizaciones de Roslyn en una posición

apply_code_action_by_title

Aplicar cualquier refactorización por título

implement_missing_members

Generar stubs de interfaz

encapsulate_field

Campo a propiedad

inline_variable

Pasar variable temporal a inline

extract_variable

Extraer expresión a variable

Generación de Código (3 herramientas)

Herramienta

Descripción

add_null_checks

Generar protecciones ArgumentNullException

generate_equality_members

Equals/GetHashCode/operadores

generate_test_stub

Esqueleto de prueba compilable para un método (framework auto-detectado)

Herramientas Compuestas (7 herramientas)

Herramienta

Descripción

get_type_overview

Información completa del tipo en una sola llamada

analyze_method

Firma + llamantes + llamadas salientes + ubicación

get_file_overview

Resumen del archivo con diagnósticos

get_method_source

Código fuente por nombre

get_method_source_batch

Varias fuentes de método en una sola llamada

get_instantiation_options

Cómo crear un tipo

get_project_health

Panel de auditoría compuesto: diagnósticos + no usado + acoplamiento + cobertura por proyecto

Auditoría y Calidad (10 herramientas)

Herramienta

Descripción

find_god_objects

Detectar tipos sobreacoplados mediante umbrales de acoplamiento eferente + aferente + recuento de miembros

find_untested_code

Encontrar superficie pública no alcanzada por ningún [Fact]/[Theory]/[Test]/[TestMethod]

find_tests

Qué pruebas cubren un símbolo — el inverso de find_untested_code

find_type_instantiations

Dónde se construye un tipo (new T)

find_pattern_usages

Dónde aparece un tipo en is/as/coincidencia de patrones

find_throw_sites

Dónde se lanza un tipo de excepción (opcionalmente derivado)

find_catch_blocks

Dónde se captura un tipo de excepción (opcionalmente mediante una cláusula base)

find_async_issues

async void / bloqueo-en-async / CancellationToken no reenviado

check_architecture

Imponer reglas de dependencia de espacios de nombres/proyectos sobre el grafo de tipos

find_naming_violations

Auditoría de nomenclatura que respeta las reglas de .editorconfig, con valores predeterminados convencionales

Descubrimiento (3 herramientas)

Herramienta

Descripción

get_di_registrations

Escanear registros de servicios de DI

find_reflection_usage

Detectar uso de reflexión/dinámico

find_interceptors

Superficie de redirección de llamadas [InterceptsLocation], código generado incluido

Infraestructura (12 herramientas)

Herramienta

Descripción

health_check

Estado del servidor + fidelidad de carga (bandera partial, proyectos declarados vs cargados, loadFailures) — verificar sin recargar

find_unused_dependencies

PackageReferences/ProjectReferences que el compilador nunca necesita

fix_all

Calcular la corrección para cada instancia de un id de diagnóstico (solo generación)

load_solution

Cargar .sln/.slnx; informa cargas parciales (partial + loadFailures) para que los proyectos descartados / referencias no resueltas no pasen desapercibidas

sync_documents

Sincronizar cambios de archivos en la solución cargada

get_project_structure

Estructura de la solución

dependency_graph

Dependencias del proyecto

get_code_fixes

Correcciones disponibles para un diagnóstico

apply_code_fix

Aplicar una corrección de código específica

get_nuget_dependencies

Listado de paquetes NuGet por proyecto

get_source_generators

Listar generadores de origen activos

get_generated_code

Ver código fuente generado

Otros Clientes MCP

Para clientes MCP distintos de Claude Code, agréguelo a su configuración:

{
  "mcpServers": {
    "sharplens": {
      "command": "sharplens",
      "args": [],
      "env": {
        "DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"
      }
    }
  }
}

Uso

  1. Cargar una solución: Llame a load_solution con la ruta al archivo .sln o .slnx (o establezca DOTNET_SOLUTION_PATH)

  2. Analizar código: Use cualquiera de las 92 herramientas para navegación, análisis, refactorización, auditoría

  3. Refactorizar de forma segura: Previsualice los cambios antes de aplicarlos con preview: true

Arquitectura

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

Requisitos

  • .NET 8.0 SDK o posterior — funciona con .NET 8, 9, 10 y versiones futuras. Analiza cualquier proyecto/solución .NET 8+.

  • Agente de IA compatible con MCP

Preguntas Frecuentes

¿Por qué la herramienta apunta a net8.0? ¿Puede analizar mi proyecto .NET 9 / .NET 10?

Sí. net8.0 es el piso de tiempo de ejecución de la herramienta: los paquetes Roslyn 5.x en los que se basa lo requieren, no es un techo sobre lo que puede analizar. RollForward permite que la herramienta instalada se ejecute en versiones más recientes de .NET, y MSBuildWorkspace carga el marco de destino real de cada proyecto desde su csproj, por lo que una instalación analiza soluciones dirigidas a .NET 8, 9, 10 y posteriores.

Desarrollo

Agregar Nuevas Herramientas

  1. Agregue el método a la parcial src/RoslynService.*.cs correspondiente (Navegación, Análisis, Refactorización, CallAnalysis, …) y devuelva a través del sobre de respuesta compartido:

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" }
    );
}
  1. Registra una ToolDefinition en src/ToolRegistry.cs — su nombre, descripción, esquema de entrada, el indicador ReadOnly (las herramientas mutantes pasan ReadOnly: false y reciben una anotación destructiveHint), y un manejador que vincula los argumentos a través de JsonRpcParameters y llama a tu método. El registro impulsa tanto tools/list como el envío; no hay un conmutador separado que editar. Dos pruebas lo mantienen honesto: ToolsListGoldenTests bloquea el esquema publicado byte por byte (vuelve a capturar el golden cuando un cambio de esquema es intencional), y ToolSchemaParityTests afirma que cada parámetro que el manejador lee está declarado en el esquema.

  2. Compila y publica:

dotnet build -c Release
dotnet publish -c Release -o ./publish
  1. Agrega ambos niveles de prueba — una prueba unitaria del método RoslynService contra un fixture determinista, Y una prueba de cable a través del despachador MCP (en tests/SharpLensMcp.Tests/Mcp/) con bloqueos de valor exacto más una ruta de error. Esto no es negociable; consulta Pruebas.

Pruebas

Cada prueba debe cumplir con la Carta de Pruebas (C1–C9) en tests/SharpLensMcp.Tests/TESTING.md — el contrato vigente. Las reglas principales:

  • Bloquea valores exactos (C1): afirma un nombre / recuento / subcadena / código de error / (línea, columna) concreto — nunca NotBeNull / > 0 / una verificación solo de tipo como la única aserción.

  • Ambos niveles por herramienta (C4): una prueba unitaria contra un fixture Fixtures/*.cs y una prueba de despachador (cable) que desempaqueta content[0].text, más una ruta de error.

  • Mayúsculas correctas (C3): Newtonsoft en proceso produce error.Code / meta.TotalCount en PascalCase; el cable MCP produce camelCase. Lee las mayúsculas que la ruta de tu prueba realmente produce.

  • Determinista (C7): el conjunto se serializa a través de xunit.runner.json; los mutadores de fixture siempre restauran; la prueba de tiempo de espera utiliza una costura de cancelación forzada, no una carrera de temporización.

  • Columna vertebral fuera de proceso (C6): StdioIntegrationTests fija el valor de una herramienta por categoría sobre el binario real y ejecuta el golden tools/list a través de la tubería stdio.

  • Puerta de pre-commit (C9): compilación limpia + verde es necesaria pero no suficiente — vuelve a leer cada prueba modificada y confirma que falla con una respuesta incorrecta.

Ejecuta el conjunto:

dotnet test -c Release

Archivos Clave

Archivo

Propósito

src/RoslynService.cs + los parciales src/RoslynService.*.cs

Implementaciones de herramientas divididas por área de interés en ~30 parciales (Navegación, Análisis, Refactorización, Inspección, Validación, Descubrimiento de Tipos, Descubrimiento, API Externa, Calidad, Métricas, Acciones de Código, Generación de Código, Compuesto, Análisis de Llamadas, Flujo de Excepciones, Traza de Pila, Superficie de API, Código Similar, …) — el nombre de cada archivo predice su contenido

src/McpServer.cs

Mecánica del protocolo MCP: bucle de análisis JSON-RPC, negociación initialize, tiempo de espera por llamada, mapeo de errores en banda vs protocolo

src/ToolRegistry.cs + src/ToolDefinition.cs

La superficie de la herramienta: un registro ToolDefinition por herramienta (nombre, esquema, indicador ReadOnly, manejador). Impulsa el orden de tools/list y la búsqueda de envío

src/JsonRpcParameters.cs + JsonRpcInvalidParamsException.cs

Accesores de argumentos JSON-RPC tipados y la excepción -32602 Invalid params que generan

src/*Data.cs / registros *Entry.cs, ConstructorMember.cs, SignatureChange.cs

Registros tipados utilizados por el compuesto de auditoría, el generador de constructores y el analizador de cambios de firma (un tipo por archivo)

Licencia

MIT - Consulta LICENSE para más detalles.

Available Tools

62 tools
roslyn:add_null_checksA

Add ArgumentNullException.ThrowIfNull guard clauses for nullable parameters.

USAGE: Position cursor on a method with reference type parameters. OUTPUT: Generated guard clauses inserted at method start. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), preview.

roslyn:analyze_change_impactA

Analyze what would break if you change a symbol. Identifies breaking changes before you make them.

USAGE: analyze_change_impact(filePath, line, column, changeType="rename|changeType|addParameter|removeParameter") OUTPUT: List of impacted locations, whether change is safe, and specific issues at each location. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), changeType (required), +1 more.

roslyn:analyze_control_flowA

Analyze branching and reachability in a code region.

Returns: entryPoints, exitPoints, returnStatements, endPointIsReachable.

USAGE: analyze_control_flow("path/to/file.cs", startLine=10, endLine=25)

Inputs: endLine (required), filePath (required), startLine (required).

roslyn:analyze_data_flowB

Analyze variable assignments and usage in a code region.

Returns: variablesDeclared, alwaysAssigned, dataFlowsIn/Out, readInside/Outside, writtenInside/Outside, captured.

USAGE: analyze_data_flow("path/to/file.cs", startLine=10, endLine=25)

Inputs: endLine (required), filePath (required), startLine (required).

roslyn:analyze_methodA

Get comprehensive method analysis in ONE CALL: signature + callers + outgoing calls + location.

USAGE: analyze_method("MyService", "ProcessData") or analyze_method("MyClass", "Calculate", includeCallers=true, includeOutgoingCalls=true)

Inputs: typeName (required), methodName (required), maxCallers, includeCallers, +2 more.

roslyn:apply_code_action_by_titleA

Apply a code action by its title. Supports exact and partial matching.

USAGE: apply_code_action_by_title(filePath, line, column, title) OUTPUT: Changed files with preview or applied changes WORKFLOW: (1) Call get_code_actions_at_position first, (2) Apply with preview=true, (3) Apply with preview=false IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), title (required), column (required), filePath (required), +3 more.

roslyn:apply_code_fixA

Apply automated code fix for a diagnostic. WORKFLOW: (1) Call with no fixIndex to list available fixes, (2) Call with fixIndex and preview=true to preview changes, (3) Call with preview=false to apply. IMPORTANT: Uses ZERO-BASED coordinates.

Inputs: line (required), column (required), filePath (required), diagnosticId (required), +2 more.

roslyn:change_signatureA

Change a method signature and preview impact on all call sites.

ACTIONS: add (new param), remove, rename, reorder parameters. WORKFLOW: (1) Call with preview=true (default) to see affected call sites, (2) Review changes, (3) Call with preview=false to apply. OUTPUT: oldSignature, newSignature, list of call sites needing updates. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), changes (required), filePath (required), +1 more.

roslyn:check_type_compatibilityA

Check if one type can be assigned to another. Use before generating assignments or casts.

USAGE: check_type_compatibility(sourceType="MyDerivedClass", targetType="MyBaseClass") OUTPUT: compatible (bool), requiresCast (bool), conversionKind, and explanation of why/why not.

Inputs: sourceType (required), targetType (required).

roslyn:dependency_graphA

Visualize project dependencies as a graph. Shows which projects reference which, detects circular dependencies.

OUTPUT: format="json" returns structured data with nodes/edges. format="mermaid" returns diagram syntax. USE CASE: Understand solution architecture, find circular dependencies, plan refactoring.

Inputs: format.

roslyn:encapsulate_fieldA

Convert a field to a property with getter/setter.

USAGE: Position cursor on a field declaration. OUTPUT: Generated property wrapping the field. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), preview.

roslyn:extract_interfaceA

Generate an interface from a class or struct. Extracts all public instance members (methods, properties, events).

USAGE: Position on class declaration, provide interfaceName="IMyService". OUTPUT: Generated interface code ready to insert. Useful for dependency injection and testability. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), interfaceName (required), +1 more.

roslyn:extract_methodA

Extract selected statements into a new method. Uses data flow analysis to determine parameters and return type.

USAGE: Specify startLine/endLine range containing complete statements inside a method. OUTPUT: extractedCode (the new method), replacementCode (the call to insert), detected parameters and return type. WORKFLOW: (1) Preview with preview=true, (2) Apply with preview=false. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: endLine (required), filePath (required), startLine (required), methodName (required), +2 more.

roslyn:extract_variableA

Extract an expression to a local variable.

USAGE: Position cursor on or select an expression. OUTPUT: Expression extracted to a new local variable. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), endLine, +2 more.

roslyn:find_attribute_usagesA

Find all types and members decorated with a specific attribute.

USAGE: find_attribute_usages(attributeName: "Authorize") USAGE: find_attribute_usages(attributeName: "HttpGet", projectName: "MyApi")

OUTPUT: List of symbols with the attribute, their kind, arguments, and source location. Use for: finding all API endpoints, authorization points, serialization config, test fixtures.

Inputs: attributeName (required), maxResults, projectName.

roslyn:find_callersA

Find all methods/properties that call or reference a specific symbol (inverse of find_references). Essential for impact analysis: 'If I change this method, what code will be affected?' IMPORTANT: Uses ZERO-BASED coordinates.

Inputs: line (required), column (required), filePath (required), maxResults.

roslyn:find_circular_dependenciesA

Detect cycles in project or namespace dependency graphs.

USAGE: find_circular_dependencies() — project-level cycles USAGE: find_circular_dependencies(level: "namespace") — namespace-level cycles

OUTPUT: Dependency graph with any detected cycles listed. Use for: architecture analysis, identifying tightly coupled components.

Inputs: level.

roslyn:find_implementationsA

Find all implementations of an interface or abstract class. Returns implementing types with their locations. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), maxResults.

roslyn:find_referencesA

Find all references to a symbol across the entire solution. Returns file paths, line numbers, and code context for each reference. IMPORTANT: Uses ZERO-BASED coordinates (editor line 10 = pass line 9).

Inputs: line (required), column (required), filePath (required), maxResults.

roslyn:find_reflection_usageA

Detect dynamic/reflection-based type and method usage that is invisible to static reference searches.

USAGE: find_reflection_usage() USAGE: find_reflection_usage(projectName: "MyApp", maxResults: 50)

OUTPUT: List of reflection API calls with the API used, context, and location. Use for: finding hidden dependencies before refactoring, security audits, understanding dynamic behavior.

Inputs: maxResults, projectName.

roslyn:find_unused_codeA

Find unused types, methods, properties, and fields in a project or entire solution. Returns symbols with zero references (excluding their declaration).

USAGE: find_unused_code() for entire solution, or find_unused_code(projectName="MyProject") for specific project. OUTPUT: List of unused symbols with location, kind, and accessibility. Default limit: 50 results.

Inputs: maxResults, projectName, includePrivate, includeInternal, +1 more.

roslyn:format_document_batchB

Format multiple documents in a project using Roslyn's NormalizeWhitespace. Ensures consistent indentation, spacing, and line breaks. PREVIEW mode by default - set preview=false to apply changes.

Inputs: preview, projectName, includeTests.

roslyn:generate_constructorA

Generate a constructor from fields and/or properties of a type.

USAGE: Position on class/struct declaration. Use includeProperties=true for auto-properties. OUTPUT: constructorCode string ready to paste, parameter list, and field assignments. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), includeProperties, +1 more.

roslyn:generate_equality_membersA

Generate Equals, GetHashCode, and == / != operators for a type.

USAGE: Position cursor on a class or struct declaration. OUTPUT: Generated equality members comparing all instance fields and properties. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), preview, +1 more.

roslyn:get_attributesB

Find all symbols with specific attributes.

USAGE:

  • Find obsolete: get_attributes("Obsolete")

  • Find serializable: get_attributes("Serializable")

  • Scope to project: get_attributes("Obsolete", scope="project:MyProject")

  • Scope to file: get_attributes("Obsolete", scope="file:MyClass.cs")

Inputs: attributeName (required), scope, maxResults.

roslyn:get_base_typesA

Get full inheritance chain BY NAME.

USAGE: get_base_types("MyService") returns: MyService → BaseService → ... → Object

Inputs: typeName (required).

roslyn:get_code_actions_at_positionA

Get ALL available code actions (fixes + refactorings) at a position. This is the master tool that exposes 100+ Roslyn refactorings.

USAGE: get_code_actions_at_position(filePath, line, column) or with selection: add endLine, endColumn OUTPUT: List of actions with title, kind (fix/refactoring), equivalenceKey WORKFLOW: (1) Call this to see available actions, (2) Use apply_code_action_by_title to apply one IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), endLine, +3 more.

roslyn:get_code_fixesA

Get available code fixes for a specific diagnostic. Returns list of fix titles and descriptions. WORKFLOW: (1) get_diagnostics to find issues, (2) get_code_fixes to see options, (3) apply_code_fix to fix.

Inputs: line (required), column (required), filePath (required), diagnosticId (required).

roslyn:get_complexity_metricsA

Get complexity metrics for a method or entire file.

METRICS: cyclomatic (decision points), nesting (max depth), loc (lines), parameters (count), cognitive (Sonar-style) USAGE: get_complexity_metrics(filePath) for file, or add line/column for specific method OUTPUT: Per-method breakdown with all requested metrics IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: filePath (required), line, column, metrics.

roslyn:get_containing_memberA

Get information about the containing method/property/class at a position. Returns the enclosing symbol's name, kind, and signature. Useful for understanding context. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required).

roslyn:get_derived_typesA

Find all types inheriting from a base type BY NAME.

USAGE:

  • Find all subclasses: get_derived_types("BaseService")

  • Direct children only: get_derived_types("BaseClass", includeTransitive=false)

Inputs: baseTypeName (required), maxResults, includeTransitive.

roslyn:get_diagnosticsA

Get compiler errors, warnings, and info messages for a file or entire project. Returns: list of diagnostics with id, message, severity, and location. Use before committing to catch issues.

Inputs: filePath, severity, projectPath, includeHidden.

roslyn:get_di_registrationsA

Scan for dependency injection service registrations (AddScoped, AddTransient, AddSingleton, etc.).

USAGE: get_di_registrations() USAGE: get_di_registrations(projectName: "MyApi")

OUTPUT: List of DI registrations with lifetime, service type, implementation type, and location. Use for: understanding service wiring, finding missing registrations, auditing lifetimes.

Inputs: projectName.

roslyn:get_file_overviewA

Get comprehensive file overview in ONE CALL: diagnostics summary + type declarations + namespace + line count.

USAGE: get_file_overview("path/to/MyClass.cs")

Inputs: filePath (required).

roslyn:get_generated_codeA

View the source code produced by a source generator.

USAGE: get_generated_code(projectName: "MyApp", generatedFileName: "MyType.g.cs")

OUTPUT: Full source code of the generated file. Use get_source_generators first to discover available generated files.

Inputs: projectName (required), generatedFileName (required).

roslyn:get_instantiation_optionsA

Get all ways to create an instance of a type: constructors, factory methods, and builder patterns.

USAGE: get_instantiation_options(typeName="HttpClient") OUTPUT: List of constructors with signatures, static factory methods, and hints (e.g., "implements IDisposable").

Inputs: typeName (required).

roslyn:get_method_overloadsA

Get all overloads of a method. Returns list of signatures with parameter details. Use when you need to choose between overloads. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required).

roslyn:get_method_signatureB

Get detailed method signature BY NAME including parameters, return type, nullability, and modifiers.

USAGE: get_method_signature("MyClass", "ProcessData") or with overload selection: get_method_signature("MyClass", "ProcessData", overloadIndex=1)

Inputs: typeName (required), methodName (required), overloadIndex.

roslyn:get_method_sourceA

Get the actual source code of a method by type and method name. Eliminates need for file Read.

USAGE: get_method_source(typeName="MyService", methodName="ProcessData") OUTPUT: Full method source including signature, body, location (file + line numbers), and line count.

Inputs: typeName (required), methodName (required), overloadIndex.

roslyn:get_method_source_batchA

Get source code for multiple methods in a single call (batch optimization).

USAGE: get_method_source_batch(methods: [{typeName: 'ServiceA', methodName: 'Process'}, {typeName: 'ServiceB', methodName: 'Handle'}]) OUTPUT: Results array with source for each method, plus errors array for any that failed. BENEFIT: One call instead of multiple - reduces round trips when tracing code flows.

Inputs: methods (required), maxMethods.

roslyn:get_missing_membersA

Get all interface and abstract members that must be implemented for a type.

USAGE: Position on a class that implements interfaces or extends abstract classes. OUTPUT: List of missing members with exact signatures ready to copy. Use before implementing interfaces. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required).

roslyn:get_nuget_dependenciesA

List NuGet package references per project with versions.

USAGE: get_nuget_dependencies() USAGE: get_nuget_dependencies(projectName: "MyApp")

OUTPUT: List of projects with their NuGet packages, versions, and asset settings. Use for: dependency audits, version checks, understanding external dependencies.

Inputs: projectName.

roslyn:get_outgoing_callsA

Get all methods and properties that a method calls. Helps understand method dependencies and behavior. Returns list of called symbols with locations. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), maxDepth.

roslyn:get_project_structureA

Get solution/project structure. IMPORTANT: For large solutions (100+ projects), use summaryOnly=true or projectNamePattern to avoid token limit errors. Maximum output is limited to 25,000 tokens.

Inputs: maxProjects, summaryOnly, includeDocuments, includeReferences, +1 more.

roslyn:get_source_generatorsA

List active source generators and their generated output per project.

USAGE: get_source_generators() USAGE: get_source_generators(projectName: "MyApp")

OUTPUT: List of generators with their assembly info and generated files. Use for: understanding generated code, debugging generator issues.

Inputs: projectName.

roslyn:get_symbol_infoA

Get detailed semantic information about a symbol at a specific position. IMPORTANT: Uses ZERO-BASED coordinates. If your editor shows 'Line 14, Column 5', pass line=13, column=4. Returns symbol kind, type, namespace, documentation, and location.

Inputs: line (required), column (required), filePath (required).

roslyn:get_type_hierarchyA

Get the inheritance hierarchy (base types and derived types) for a type. Returns baseTypes chain and derivedTypes list. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), maxDerivedTypes.

roslyn:get_type_membersA

Get all members (methods, properties, fields, events) of a type BY NAME.

USAGE PATTERNS:

  • Basic: get_type_members("MyClass") - list all members

  • With inheritance: get_type_members("MyService", includeInherited=true)

  • Filter by kind: get_type_members("MyClass", memberKind="Method")

  • Verbosity control: verbosity="summary" (names only), "compact" (default, + signatures), "full" (+ docs, attrs)

WORKS WITH: Fully-qualified ("MyNamespace.MyClass"), simple ("MyClass"), or partial names.

Inputs: typeName (required), verbosity, maxResults, memberKind, +1 more.

roslyn:get_type_members_batchA

Get members for multiple types in a single call (batch optimization).

USAGE: get_type_members_batch(typeNames: ['ServiceA', 'ServiceB', 'ControllerC']) OUTPUT: Results for each type with members, or error if type not found BENEFIT: One call instead of multiple - reduces context usage for AI agents

Inputs: typeNames (required), verbosity, memberKind, includeInherited, +1 more.

roslyn:get_type_overviewA

Get comprehensive type overview in ONE CALL: type info + base types (first 3) + member counts.

USAGE: get_type_overview("MyService") - returns everything you need to understand a type quickly.

Inputs: typeName (required).

roslyn:go_to_definitionA

Fast navigation to symbol definition. Returns the definition location without finding all references. IMPORTANT: Uses ZERO-BASED coordinates (editor line 10 = pass line 9).

Inputs: line (required), column (required), filePath (required).

roslyn:health_checkA

Check the health and status of the Roslyn MCP server and workspace. Returns: server status, solution loaded state, project count, and memory usage. Call this first to verify the server is ready.

Inputs: no named parameters.

roslyn:implement_missing_membersA

Generate stub implementations for interface/abstract members.

USAGE: Position cursor on class declaration that implements interface or extends abstract class. OUTPUT: Generated stub code for all missing members. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), preview.

roslyn:inline_variableA

Inline a variable, replacing all usages with its value.

USAGE: Position cursor on a variable declaration or usage. OUTPUT: Variable removed and all usages replaced with the expression. IMPORTANT: Uses ZERO-BASED coordinates (editor line - 1).

Inputs: line (required), column (required), filePath (required), preview.

roslyn:load_solutionA

Load a .NET solution for analysis. MUST be called before using any other analysis tools. Returns: projectCount, documentCount, and load time. Use health_check to verify current state.

Inputs: solutionPath (required).

roslyn:organize_usingsA

Sort and remove unused using directives in a file. Returns the modified file content. Automatically removes unused usings and sorts alphabetically.

Inputs: filePath (required).

roslyn:organize_usings_batchA

Organize using directives for multiple files in a project. Supports file pattern filtering (e.g., '.cs', 'Services/.cs'). PREVIEW mode by default - set preview=false to apply changes.

Inputs: preview, filePattern, projectName.

roslyn:rename_symbolA

Safely rename a symbol (type, method, property, etc.) across the entire solution. Uses Roslyn's semantic analysis to ensure all references are updated. SUPPORTS PREVIEW MODE - always preview first! IMPORTANT: Uses ZERO-BASED coordinates. Default shows first 20 files with summary verbosity.

Inputs: line (required), column (required), newName (required), filePath (required), +3 more.

roslyn:search_symbolsA

Search for types, methods, properties, etc. by name across the solution. Supports glob patterns (e.g., 'Handler' finds classes ending with 'Handler', 'Get' finds symbols starting with 'Get'). Use ? for single character wildcard. PAGINATION: Returns totalCount and hasMore. Use offset to paginate through results.

Inputs: query (required), kind, offset, maxResults, +1 more.

roslyn:semantic_queryA

Advanced semantic code query with multiple filters. Find symbols based on their semantic properties.

EXAMPLES:

  • Async methods without CancellationToken: isAsync=true, parameterExcludes=["CancellationToken"]

  • Public static methods: accessibility="Public", isStatic=true

  • Classes with [Obsolete]: kinds=["Class"], attributes=["ObsoleteAttribute"]

FILTERS: All specified filters are combined with AND logic. Omit a filter to skip it. Returns symbol details with locations.

Inputs: type, kinds, isAsync, isStatic, +7 more.

roslyn:sync_documentsA

Synchronize document changes from disk into the loaded solution. Call this after using Edit/Write tools to ensure Roslyn has fresh content.

USAGE:

  • sync_documents(filePaths: ["src/Foo.cs", "src/Bar.cs"]) - sync specific files

  • sync_documents() - sync ALL documents (refresh entire solution)

WHEN TO CALL:

  • After using Edit tool to modify .cs files

  • After using Write tool to create new .cs files

  • After deleting .cs files

  • NOT needed after using SharpLensMcp refactoring tools (they auto-update)

HANDLES: Modified files (updates content), new files (adds to solution), deleted files (removes from solution). Much faster than load_solution - only updates documents, doesn't re-parse projects.

Inputs: filePaths.

roslyn:validate_codeA

Check if code would compile without writing to disk. Use to validate generated code before applying.

USAGE: validate_code(code="public void Foo() {}", contextFilePath="path/to/file.cs") to check with existing usings. OUTPUT: compiles (bool), errors list with line numbers. Essential before inserting AI-generated code.

Inputs: code (required), standalone, contextFilePath.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 62 tools

    Disambiguation4/5

    Most tools have distinct purposes, but some pairs like find_references and find_callers could be confused without reading descriptions. Overall, the descriptions help differentiate.

    Naming Consistency4/5

    Tools use a consistent snake_case verb_noun pattern, with minor exceptions like 'go_to_definition' instead of 'get_definition'. The pattern is mostly uniform.

    Tool Count2/5

    With 62 tools, the surface is overly large. Many specialized and batch tools could be consolidated. This exceeds the typical well-scoped range of 3-15 tools.

    Completeness4/5

    The tool set covers a broad range of Roslyn features including analysis, refactoring, navigation, and diagnostics. Minor gaps exist (e.g., no individual add-using tool), but overall coverage is strong.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      A
      quality
      D
      maintenance
      Minimal MCP server bridging a Roslyn C# language server to AI agents, exposing tools for diagnostics, call hierarchy, and type hierarchy.
      1
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      A semantic map of your .NET solution for AI coding agents. Analyzes a solution with Roslyn into a queryable code graph exposing 11 read-only tools (find_symbol, impact_analysis, find_implementations, etc.) over MCP. 100% local, no telemetry, MIT licensed.
      25
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      A local .NET MCP server for coding agents, providing persistent semantic indexing, typed-graph DI wiring resolution, reduced context, and compiler-backed verification for .NET projects.
      37
      Apache 2.0