Skip to main content
Glama

SharpLensMcp

NuGet npm License: MIT

Microsoft Roslynを使用した.NET/C#のセマンティックコード解析、ナビゲーション、リファクタリング、コード生成のための62個のAI最適化ツールを提供するModel Context Protocol (MCP) サーバーです。

AIコーディングエージェント向けに構築されており、AIがソースファイルを読み取るだけでは推論できない、コンパイラ精度のコード理解を提供します。

インストール

NuGet経由 (推奨)

dotnet tool install -g SharpLensMcp

次に以下を実行します:

sharplens

npm経由

npx -y sharplens-mcp

ソースからビルド

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

Related MCP server: LSP-MCP

Claude Codeの設定

  1. ツールをインストールします (いずれかを選択):

dotnet tool install -g SharpLensMcp
# or
npx -y sharplens-mcp
  1. プロジェクトのルートに .mcp.json を作成します:

{
  "mcpServers": {
    "sharplens": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "sharplens-mcp"],
      "env": {
        "DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"
      }
    }
  }
}
  1. Claude Codeを再起動してMCPサーバーを読み込みます

  2. ClaudeにRoslynサーバーのヘルスチェックを実行するよう依頼して確認します

なぜClaude Codeでこれを使用するのか?

Claude Codeは、基本的なナビゲーション(定義への移動、参照の検索)に対してネイティブのLSPサポートを備えています。SharpLensMcpは、深いセマンティック解析を追加します:

機能

ネイティブLSP

SharpLensMcp

定義への移動

✅

✅

参照の検索

✅

✅

CancellationTokenが欠落している非同期メソッドの検索

❌

✅

影響分析 (何が壊れるか?)

❌

✅

デッドコード検出

❌

✅

複雑性メトリクス

❌

✅

プレビュー付きの安全なリファクタリング

❌

✅

バッチ操作

❌

✅

設定

環境変数

説明

デフォルト

DOTNET_SOLUTION_PATH

起動時に自動読み込みする .sln または .slnx ファイルへのパス

なし (load_solution を呼び出す必要あり)

SHARPLENS_ABSOLUTE_PATHS

相対パスの代わりに絶対パスを使用

false (相対パスはトークンを節約します)

ROSLYN_LOG_LEVEL

ログの詳細度: Trace, Debug, Information, Warning, Error

Information

ROSLYN_TIMEOUT_SECONDS

長時間実行される操作のタイムアウト

30

ROSLYN_MAX_DIAGNOSTICS

返される診断の最大数

100

ROSLYN_ENABLE_SEMANTIC_CACHE

セマンティックモデルのキャッシュを有効化

true (無効にするには false に設定)

DOTNET_SOLUTION_PATH が設定されていない場合は、他のツールを使用する前に load_solution ツールを呼び出す必要があります。

AIエージェント設定のヒント

AIモデルは、SharpLensMcpの方が優れた機能を提供している場合でも、ネイティブツール(Grep、Read、LSP)を使用するように学習上のバイアスがかかっている可能性があります。

最適なツール使用を確実にするために:

  1. Claude Code: プロジェクトの CLAUDE.md に以下を追加します:

    For C# code analysis, prefer SharpLensMcp tools over native tools:
    - Use `roslyn:search_symbols` instead of Grep for finding symbols
    - Use `roslyn:get_method_source` instead of Read for viewing methods
    - Use `roslyn:find_references` for semantic (not text) references
  2. その他のMCPクライアント: エージェントのシステムプロンプトでツールの優先順位を設定します

Roslynによるセマンティック解析は、特にオーバーロードされたメソッド、部分クラス、継承階層において、テキストベースの検索よりも正確です。

エージェントの責任:ドキュメントの同期

重要: SharpLensMcpは、高速なクエリのためにソリューションのメモリ内表現を保持します。ファイルが外部から(Edit/Writeツール経由で)変更された場合、変更を同期するのはエージェントの責任です。

sync_documents を呼び出すタイミング:

アクション

sync_documentsを呼び出すか?

Editツールを使用して.csファイルを変更した

✅ はい

Writeツールを使用して新しい.csファイルを作成した

✅ はい

.csファイルを削除した

✅ はい

SharpLensMcpのリファクタリングツール(名前変更、抽出など)を使用した

❌ いいえ (自動更新されます)

.csprojファイルを変更した

❌ いいえ (load_solution を使用してください)

使用方法:

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

# After bulk changes - sync all documents
sync_documents()

なぜこの設計なのか?

これはLSP(Language Server Protocol)の仕組みを反映しています。クライアント(エディタ)がサーバーに変更を通知します。このアプローチは:

  • 競合状態を排除します(エージェントがタイミングを制御)

  • ファイル監視の複雑さやプラットフォームの癖を回避します

  • ソリューション全体の再読み込みよりも高速です

  • エージェントにワークスペース状態の明示的な制御を与えます

同期しない場合: クエリが古いデータ(古いメソッドシグネチャ、新しいファイルの欠落など)を返す可能性があります。

機能

  • 62個のセマンティック解析ツール - ナビゲーション、リファクタリング、コード生成、診断、発見

  • AI最適化された説明 - 明確なUSAGE/OUTPUT/WORKFLOWパターン

  • 構造化されたレスポンス - suggestedNextTools を含む一貫した success/error/data 形式

  • ゼロベースの座標 - 1ズレエラーを防ぐための明確な警告

  • プレビューモード - 適用前にプレビューで安全にリファクタリング

  • バッチ操作 - コンテキスト使用量を削減するための1回の呼び出しでの複数ルックアップ

ツールカテゴリ

ナビゲーションと発見 (17ツール)

ツール

説明

get_symbol_info

位置におけるセマンティック情報

go_to_definition

シンボル定義へジャンプ

find_references

ソリューション全体のすべての参照

find_implementations

インターフェース/抽象実装

find_callers

影響分析 - これを呼び出すのは誰か?

get_type_hierarchy

継承チェーン

search_symbols

グロブパターン検索 (*Handler, Get*)

semantic_query

マルチフィルター検索 (async, publicなど)

get_type_members

型名によるすべてのメンバー

get_type_members_batch

1回の呼び出しで複数の型

get_method_signature

名前による詳細なシグネチャ

get_derived_types

すべてのサブクラスを検索

get_base_types

完全な継承チェーン

get_attributes

シンボルの属性をリスト化

get_containing_member

位置における包含シンボル

get_method_overloads

メソッドのすべてのオーバーロード

find_attribute_usages

属性による型/メンバーの検索

解析 (11ツール)

ツール

説明

get_diagnostics

コンパイラエラー/警告

analyze_data_flow

変数の割り当てと使用状況

analyze_control_flow

分岐/到達可能性

analyze_change_impact

変更すると何が壊れるか?

check_type_compatibility

AはBに割り当て可能か?

get_outgoing_calls

このメソッドは何を呼び出すか?

find_unused_code

デッドコード検出

validate_code

書き込みなしのコンパイルチェック

get_complexity_metrics

循環的、ネスト、LOC、認知的

find_circular_dependencies

プロジェクトと名前空間の循環検出

get_missing_members

未実装のインターフェース/抽象メンバー

リファクタリング (14ツール)

ツール

説明

rename_symbol

ソリューション全体の安全な名前変更

change_signature

パラメータの追加/削除/並べ替え

extract_method

データフロー解析による抽出

extract_interface

クラスからインターフェースを生成

generate_constructor

フィールド/プロパティから

organize_usings

未使用の並べ替えと削除

organize_usings_batch

複数ファイルのバッチ整理

format_document_batch

プロジェクト内のファイルバッチフォーマット

get_code_actions_at_position

位置におけるすべてのRoslynリファクタリング

apply_code_action_by_title

タイトルによるリファクタリングの適用

implement_missing_members

インターフェーススタブの生成

encapsulate_field

フィールドからプロパティへ

inline_variable

一時変数のインライン化

extract_variable

式を変数に抽出

コード生成 (2ツール)

ツール

説明

add_null_checks

ArgumentNullExceptionガードを生成

generate_equality_members

Equals/GetHashCode/演算子

複合ツール (6ツール)

ツール

説明

get_type_overview

1回の呼び出しで完全な型情報

analyze_method

シグネチャ + 呼び出し元 + 呼び出し先 + 場所

get_file_overview

診断付きのファイル概要

get_method_source

名前によるソースコード

get_method_source_batch

1回の呼び出しで複数のメソッドソース

get_instantiation_options

型の作成方法

発見 (2ツール)

ツール

説明

get_di_registrations

DIサービス登録をスキャン

find_reflection_usage

リフレクション/動的使用を検出

インフラストラクチャ (10ツール)

ツール

説明

health_check

サーバーの状態

load_solution

解析用に.sln/.slnxを読み込み

sync_documents

読み込まれたソリューションにファイル変更を同期

get_project_structure

ソリューション構造

dependency_graph

プロジェクトの依存関係

get_code_fixes

診断に対して利用可能な修正

apply_code_fix

特定のコード修正を適用

get_nuget_dependencies

プロジェクトごとのNuGetパッケージリスト

get_source_generators

アクティブなソースジェネレーターをリスト化

get_generated_code

生成されたソースコードを表示

その他のMCPクライアント

Claude Code以外のMCPクライアントについては、設定に以下を追加してください:

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

使用方法

  1. ソリューションを読み込む: .sln または .slnx ファイルへのパスを指定して roslyn:load_solution を呼び出します(または DOTNET_SOLUTION_PATH を設定します)

  2. コードを解析する: ナビゲーション、解析、リファクタリングのための57個のツールのいずれかを使用します

  3. 安全にリファクタリングする: preview: true を指定して、適用前に変更をプレビューします

アーキテクチャ

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

要件

  • .NET 8.0 SDK以降 — .NET 8、9、10、および将来のバージョンで動作します。あらゆる.NET 8+プロジェクト/ソリューションを解析します。

  • MCP互換のAIエージェント

開発

新しいツールの追加

  1. src/RoslynService.cs にメソッドを追加します:

public async Task<object> YourToolAsync(string param1, int? param2 = null)
{
    EnsureSolutionLoaded();
    // Your logic...
    return CreateSuccessResponse(
        data: new { /* results */ },
        suggestedNextTools: new[] { "next_tool_hint" }
    );
}
  1. src/McpServer.cs の HandleListToolsAsync にツール定義を追加します

  2. src/McpServer.cs の HandleToolCallAsync switch文にルーティングを追加します

  3. ビルドと公開:

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

主要ファイル

ファイル

目的

src/RoslynService.cs

ツール実装 (57メソッド)

src/McpServer.cs

MCPプロトコル、ツール定義、ルーティング

ライセンス

MIT - 詳細については LICENSE を参照してください。

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

    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