Skip to main content
Glama

SharpLensMcp

NuGet npm License: MIT

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

Related MCP server: LSP-MCP

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 a .sln, .slnx or .slnf file (or a directory holding exactly one) to auto-load on startup; the load runs beside the request loop, so initialize answers immediately

None (must call load_solution)

SHARPLENS_ABSOLUTE_PATHS

Use absolute paths instead of relative

false (relative paths save tokens)

SHARPLENS_LOG_LEVEL

Logging verbosity: Trace, Debug, Information, Warning, Error

Information

SHARPLENS_TIMEOUT_SECONDS

Timeout for long-running operations

30

SHARPLENS_MAX_DIAGNOSTICS

Maximum diagnostics to return

100

SHARPLENS_ENABLE_SEMANTIC_CACHE

Cache the file-path to document lookup

true (set to false to disable)

The pre-1.6.0 ROSLYN_* spellings of these variables are still read as a fallback; the SHARPLENS_* spelling wins when both are set. Boolean values are case-insensitive. A number that does not parse or is below its minimum falls back to the default, and one above its maximum is capped; each case logs a warning to stderr.

Multi-targeted projects

A project built for several target frameworks is one project to every tool: each result is reported once, with a targetFrameworks list where it exists only under some frameworks. projectName accepts the plain name (MyLib) for all frameworks, or a framework-qualified name (MyLib(net8.0)) for one.

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

roslyn:load_solution

load_solution

roslyn:get_diagnostics

get_diagnostics

roslyn:rename_symbol

rename_symbol

...same rule for all tools...

drop the roslyn: prefix

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:

  1. 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) 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()

A full sync also picks up new .cs files the project's compile items include. SharpLensMcp's apply tools write only the files an edit changes, keep each file's encoding and line endings, and refuse with STALE_DOCUMENT when a target file changed on disk since it was read — run sync_documents, then retry. They also refuse with UNSUPPORTED_ENCODING to write a file whose bytes its encoding cannot reproduce (a BOM-less file that is not valid UTF-8 on a system whose fallback code page is UTF-8, such as Linux); save it as UTF-8 first.

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

  • 92 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 (24 tools)

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

find_path_between

Reachability + the connecting call path(s) between two methods; follows dispatch, with barriers and a checkpoint

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

resolve_stack_trace

Map a pasted stack trace to file/line/symbol, mangling undone

get_extension_methods

Extensions applying to a type — classic and C# 14 blocks

get_documentation

Full XML docs for a symbol with <inheritdoc> expanded

get_super_method

Navigate to the base member / interface members a member implements

Analysis (17 tools)

Tool

Description

get_diagnostics

Compiler errors/warnings + configured analyzer findings (StyleCop, Roslynator, NetAnalyzers); matches CI

diff_api_surface

Public-API breaking-change report vs a git ref

get_exception_flow

Which exceptions can escape a method, and where they're caught

find_similar_code

Structural similarity search (token-shingle fingerprints)

remove_unused_code

Compute dead-code removals + newly unused usings (generation-only)

find_dead_branches

Unreachable basic blocks per method (real CFG, not heuristics)

add_missing_imports

Compute the usings that fix CS0246/CS0103 (generation-only)

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

move_type_to_file

Compute the contents to move a type into its own file (generation-only)

split_type

Compute a partial-class split for selected members (generation-only)

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 (3 tools)

Tool

Description

add_null_checks

Generate ArgumentNullException guards

generate_equality_members

Equals/GetHashCode/operators

generate_test_stub

Compilable test skeleton for a method (framework auto-detected)

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 (10 tools)

Tool

Description

find_god_objects

Detect over-coupled types via efferent + afferent coupling + member-count thresholds

find_untested_code

Find public surface no test reaches — tests detected as xUnit, NUnit, MSTest, TUnit, Reqnroll and SpecFlow discover them, with setup, fixtures and step bindings

find_tests

Which tests cover a symbol — the inverse of find_untested_code

find_type_instantiations

Where a type is constructed (new T)

find_pattern_usages

Where a type appears in is/as/pattern matches

find_throw_sites

Where an exception type is thrown (optionally derived)

find_catch_blocks

Where an exception type is caught (optionally via a base clause)

find_async_issues

async void / blocking-on-async / unforwarded CancellationToken

check_architecture

Enforce namespace/project dependency rules over the type graph

find_naming_violations

Naming audit honoring .editorconfig rules, with conventional defaults

Discovery (3 tools)

Tool

Description

get_di_registrations

Scan DI service registrations

find_reflection_usage

Detect reflection/dynamic usage

find_interceptors

Surface [InterceptsLocation] call rerouting, generated code included

Infrastructure (12 tools)

Tool

Description

health_check

Server status + load fidelity (partial flag, declared-vs-loaded projects, loadFailures, loadWarnings, lastLoadFailure) — check without reloading

find_unused_dependencies

PackageReferences/ProjectReferences the compiler never needs

fix_all

Compute the fix for every instance of a diagnostic id (generation-only)

load_solution

Load .sln/.slnx/.slnf; reports partial loads (partial + loadFailures: dropped projects, failed restores, projects loaded without references) and MSBuild warnings (loadWarnings) separately

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 load_solution with path to .sln or .slnx file (or set DOTNET_SOLUTION_PATH)

  2. Analyze code: Use any of the 92 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
   - 92 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

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

  1. Add the method to the matching src/RoslynService.*.cs partial (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" }
    );
}
  1. Register one ToolDefinition in src/ToolRegistry.cs — its name, description, input schema, the ReadOnly flag (mutating tools pass ReadOnly: false and receive a destructiveHint annotation), and a handler that binds arguments through JsonRpcParameters and calls your method. The registry drives both tools/list and dispatch; there is no separate switch to edit. Two tests keep it honest: ToolsListGoldenTests locks the published schema byte-for-byte (re-capture the golden when a schema change is intentional), and ToolSchemaParityTests asserts every parameter the handler reads is declared in the schema.

  2. Build and publish:

dotnet build -c Release
dotnet publish -c Release -o ./publish
  1. Add both test levels — a unit test of the RoslynService method against a deterministic fixture, AND a wire test through the MCP dispatcher (in tests/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) — never NotBeNull / > 0 / a type-only check as the sole assertion.

  • Both levels per tool (C4): a unit test against a Fixtures/*.cs fixture and a dispatcher (wire) test that unwraps content[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): StdioIntegrationTests value-pins one tool per category over the real binary and runs the tools/list golden 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 Release

Key Files

File

Purpose

src/RoslynService.cs + the src/RoslynService.*.cs partials

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

src/McpServer.cs

MCP protocol mechanics: JSON-RPC parse loop, initialize negotiation, per-call timeout, in-band vs protocol error mapping

src/ToolRegistry.cs + src/ToolDefinition.cs

The tool surface: one ToolDefinition record per tool (name, schema, ReadOnly flag, handler). Drives tools/list order and dispatch lookup

src/JsonRpcParameters.cs + JsonRpcInvalidParamsException.cs

Typed JSON-RPC argument accessors and the -32602 Invalid params exception they raise

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

Typed records used by the audit composite, constructor generator, and signature-change parser (one type per file)

License

MIT - See LICENSE for details.

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

    ActivitySlowing
    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