roslyn-codelens-mcp
Roslyn CodeLens MCP Server
A Roslyn-powered MCP server providing deep semantic analysis and code transformation for .NET solutions, exposing over 50 tools for AI agents to browse, understand, test, refactor, and enforce rules on .NET codebases.
Code Navigation & Search
go_to_definition— Find where any symbol is defined (file + line)find_references— Find all references to a symbol, tagged by kind (read, write, invocation, etc.)search_symbols— Fuzzy/substring search for types, methods, properties, and fieldsfind_implementations— Find all classes/structs implementing an interface or extending a classfind_callers— Find every call site for a method, property, or constructorget_type_hierarchy— Walk base classes, interfaces, and derived typesanalyze_change_impact— Show all files, projects, and call sites affected by changing a symbolget_call_graph— Transitive caller/callee graph, depth-bounded with cycle detection
Code Understanding & Context
get_symbol_context— One-shot context dump for any type (namespace, base class, interfaces, members)get_type_overview— Comprehensive type overview: context + hierarchy + diagnostics in one callanalyze_method— Method signature + callers + outgoing calls in one callget_file_overview— Types defined in a file + file-scoped diagnosticsget_method_source— Full declaration source (docs, attributes, signature, body) for one or many membersget_overloads— Every overload of a method or constructor with full parameter detailget_operators— Every user-defined operator and conversion operator on a typeget_extension_methods— Every extension member applicable to a type (including BCL LINQ)get_instantiation_options— Constructors, static factories, DI registrations, and required members for a type
Dependency & Architecture Analysis
get_project_dependencies— Project reference graph (direct and transitive)get_di_registrations— Scan for DI service registrations (AddSingleton, AddTransient, etc.)find_circular_dependencies— Detect cycles in project or namespace dependency graphscheck_architecture— Enforce layering rules (forbid/allowOnly) against the real semantic type graphget_nuget_dependencies— List NuGet package references per projectfind_event_subscribers— Every += / -= site for an event symbol
Testing & Coverage
find_tests_for_symbol— List xUnit/NUnit/MSTest methods that exercise a production symbolget_test_summary— Per-project inventory of test methods with framework, attribute kind, and production symbols referencedfind_uncovered_symbols— Public methods/properties no test transitively reaches, sorted by cyclomatic complexitygenerate_test_skeleton— Emit a compilable test-class skeleton for a method or type
Diagnostics & Code Quality
get_diagnostics— List compiler errors, warnings, and Roslyn analyzer diagnosticsget_code_fixes— Get available code fixes with structured text edits for any diagnosticget_complexity_metrics— Cyclomatic and cognitive complexity + max nesting depth per memberfind_naming_violations— Check .NET naming convention compliancefind_async_violations— Detect sync-over-async, async void misuse, missing awaits, fire-and-forget tasksfind_disposable_misuse— Detect IDisposable/IAsyncDisposable instances at risk of leakingfind_large_classes— Find oversized types by member or line countfind_god_objects— Types combining high size with high cross-namespace couplingfind_unused_symbols— Dead code detection via reference analysisfind_reflection_usage— Detect dynamic/reflection-based usagefind_obsolete_usage— Every call site referencing [Obsolete]-marked symbolsget_project_health— Composite audit aggregating 7 quality dimensions per project
Exception & Control Flow Analysis
get_exception_flow— What exceptions can escape a method (walks callees, propagates through try/catch)find_throw_sites— Every place an exception type is thrownfind_catch_blocks— Every catch for an exception type, with rethrow/empty/filter flagsanalyze_data_flow— Variable read/write/capture analysis within a statement rangeanalyze_control_flow— Branch/loop reachability analysis within a statement range
Refactoring & Code Actions
get_code_actions— Discover available refactorings and fixes at any positionapply_code_action— Execute any Roslyn refactoring by title, with preview moderename_symbol— Solution-wide safe rename with preview mode and conflict reportingchange_signature— Add, remove, and reorder method parameters with full call-site rewriting
API Surface & Breaking Changes
get_public_api_surface— Enumerate every public/protected type and member in production projectsfind_breaking_changes— Diff the current API against a baseline JSON or DLLfind_attribute_usages— Find types and members decorated with a specific attribute
Source Generators & External Assemblies
get_source_generators— List source generators and their output per projectget_generated_code— Inspect generated source code from source generatorsinspect_external_assembly— Browse types, members, and XML docs from closed-source NuGet packagespeek_il— Decompile any method to ilasm-style IL bytecode
Stack Trace Resolution
resolve_stack_trace— Map a pasted .NET stack trace to file/line/symbol, undoing compiler name mangling
Solution Management
list_solutions— List all loaded solutions and which is activeset_active_solution— Switch the active solutionload_solution— Load an additional .sln/.slnx at runtimeunload_solution— Unload a solution to free memoryrebuild_solution— Force a full reload of the analyzed solution
Background Tasks
start_background_task— Queue a long-running tool to run in the backgroundget_task_status— Poll the status of a background tasklist_running_tasks— List background tasks running or completed within the last 5 minutes
Security & Trust
trust_solution— Authorize a solution to run Roslyn analyzerslist_trusted_paths— Inspect the persistent trust storerevoke_trust— Revoke a previously-granted trust for a solution path
Provides deep semantic analysis of .NET codebases, allowing for the exploration of type hierarchies, call graphs, dependency injection registrations, diagnostics, and automated code fixes.
Enables the inspection and listing of NuGet package dependencies and references across projects within a .NET solution.
Roslyn CodeLens MCP Server
A Roslyn-based MCP server that gives AI agents deep semantic understanding of .NET codebases — type hierarchies, call graphs, DI registrations, diagnostics, refactoring, and more.
Hosted deployment
A hosted deployment is available on Fronteir AI.
Related MCP server: mcp-deepcontext
Features
find_implementations — Find all classes/structs implementing an interface or extending a class
find_callers — Find every call site for a method, property, or constructor
find_event_subscribers — Every += / -= site for an event symbol, with resolved handler and subscribe/unsubscribe tag
find_tests_for_symbol — List xUnit/NUnit/MSTest methods that exercise a production symbol; opt-in transitive walk through helpers
get_test_summary — Per-project inventory of test methods with framework, attribute kind, data-row count, location, and production symbols referenced
find_uncovered_symbols — Public methods and properties no test transitively reaches; sorted by cyclomatic complexity for prioritization
generate_test_skeleton — Emit a compilable test-class skeleton (as text) for a method or type. Auto-detects xUnit/NUnit/MSTest; surfaces constructor dependencies as TodoNotes; returns a suggested file path. Closes the loop with
find_uncovered_symbolsget_type_hierarchy — Walk base classes, interfaces, and derived types
get_di_registrations — Scan for DI service registrations. Reads generic (
AddSingleton<IFoo, Foo>()), single-generic,typeofpair and factory-lambda formsget_instantiation_options — "How do I construct this type?" in one call: constructors with full parameter detail, static factory methods declared anywhere in the solution (including on a separate factory type), DI registrations, and
requiredmembers. PassfromProjectto learn whether that project can actually reach each option — it honoursInternalsVisibleTo, so it answers "can my test project call this internal constructor?"get_project_dependencies — Get the project reference graph
get_symbol_context — One-shot context dump for any type
get_public_api_surface — Enumerate every public/protected type and member in production projects; flat, deterministically-sorted list suitable for API review or breaking-change baselines.
find_breaking_changes — Diff the current API against a baseline JSON or DLL; report removed members, kind changes, and accessibility changes with Breaking/NonBreaking severity.
find_reflection_usage — Detect dynamic/reflection-based usage
get_exception_flow — What exceptions can escape a method: walks callees depth-bounded, propagates each throw up through every enclosing try/catch, and reports what still escapes with its propagation path; metadata callees contribute their documented exceptions
find_throw_sites — Every place an exception type is thrown, optionally including derived types; rethrows flagged
find_catch_blocks — Every catch for a type, optionally via base clauses; flags filtered, rethrowing, and empty (swallowing) handlers
find_references — Find all references to any symbol (types, methods, properties, fields, events), each tagged with a kind (
read,write,readwrite,invocation,method_group,object_creation,cast,type_check,typeof,base_type,type_constraint,type_argument,declaration,attribute,nameof,xml_doc) and reported per occurrence with a column; filter server-side withkinds(e.g.["write","readwrite"]for mutation sites)go_to_definition — Find the source file and line where a symbol is defined
get_method_source — Full declaration source (XML docs, attributes, signature, body — original formatting) for one or many members by name in a single call: methods (all overloads), constructors, properties, indexers, fields, events; per-item statuses (
ok/notFound/ambiguous/metadata/unsupportedKind) so a batch never fails wholesaleresolve_stack_trace — Map a pasted .NET stack trace to file/line/symbol, undoing compiler name mangling (async/iterator state machines, lambdas, local functions, generic arity); handles inner-exception chains, log-prefixed lines, and Demystifier traces
get_diagnostics — List compiler errors, warnings, and Roslyn analyzer diagnostics
get_code_fixes — Get available code fixes with structured text edits for any diagnostic
search_symbols — Fuzzy workspace symbol search by name
get_nuget_dependencies — List NuGet package references per project
find_attribute_usages — Find types and members decorated with a specific attribute
find_obsolete_usage — Every
[Obsolete]call site grouped by deprecation message and severity, errors first; for planning migrationsfind_circular_dependencies — Detect cycles in project or namespace dependency graphs
check_architecture — Enforce layering rules you supply (
forbidandallowOnly) against the real semantic type graph rather thanusingdirectives; violations are grouped per boundary with a reference count and example sitesget_complexity_metrics — Cyclomatic complexity, cognitive complexity and max nesting depth per member (methods, constructors, properties, indexers, operators). Cyclomatic counts paths and starts at 1; cognitive measures how hard the code is to follow and starts at 0.
metricpicks which one the threshold and sort use — cognitive is the better refactoring-priority signal, cyclomatic the better test-budget onefind_naming_violations — Check .NET naming convention compliance
find_async_violations — Sync-over-async,
async voidmisuse, missing awaits, fire-and-forget tasks; per-violation report with severityfind_disposable_misuse —
IDisposable/IAsyncDisposableinstances not wrapped inusing/await using/returned/assigned to field; severity error/warning per violation.find_large_classes — Find oversized types by member or line count
find_god_objects — Types combining high size with high cross-namespace coupling; sharper signal than raw size for SRP violations
find_unused_symbols — Dead code detection via reference analysis. Auto-filters test methods (xUnit/NUnit/MSTest), MCP tool entry points, source-generator output, MEF-composed services, and interop-laid-out fields; filter counts surface in
summary.filteredOutget_project_health — Composite audit aggregating 7 quality dimensions per project (complexity, large classes, naming, unused symbols, reflection, async violations, disposable misuse) with counts and top-N hotspots inline
get_source_generators — List source generators and their output per project
get_generated_code — Inspect generated source code from source generators
inspect_external_assembly — Browse types, members, and XML docs from closed-source NuGet packages and referenced assemblies
peek_il — Decompile any method to ilasm-style IL bytecode from closed-source or generated assemblies
get_code_actions — Discover available refactorings and fixes at any position (extract method, rename, inline variable, and more)
apply_code_action — Execute any Roslyn refactoring by title, with preview mode (returns a diff before writing to disk)
rename_symbol — Solution-wide safe rename of a type or member via Roslyn's Renamer, with preview mode, conflict reporting, and a freshness check against on-disk edits
change_signature — Add, remove, and reorder a method's parameters and rewrite every call site; handles named/optional arguments,
paramsand extension methods, and reports the overrides and interface implementations it cascaded tolist_solutions — List all loaded solutions and which one is currently active
set_active_solution — Switch the active solution by partial name (all subsequent tools operate on it)
load_solution — Load an additional .sln/.slnx at runtime and make it the active solution
unload_solution — Unload a loaded solution to free memory
rebuild_solution — Force a full reload of the analyzed solution
start_background_task — Queue a long-running tool (currently
rebuild_solution) to run in the background; returns ataskIdto pollget_task_status — Get the current status, result, or error of a background task by its
taskIdlist_running_tasks — List background tasks running or completed within the last 5 minutes
trust_solution — Authorize a solution to run Roslyn analyzers (required before
get_diagnosticswithincludeAnalyzers: true)list_trusted_paths — Inspect the persistent trust store + session-trusted solutions
revoke_trust — Revoke a previously-granted trust for a solution path
analyze_data_flow — Variable read/write/capture analysis within a statement range (declared, read, written, always assigned, captured, flows in/out)
analyze_control_flow — Branch/loop reachability analysis within a statement range (start/end reachability, return statements, exit points)
analyze_change_impact — Show all files, projects, and call sites affected by changing a symbol — combines find_references and find_callers
get_type_overview — Compound tool: type context + hierarchy + file diagnostics in one call
analyze_method — Compound tool: method signature + callers + outgoing calls in one call
get_overloads — Every overload of a method/constructor (source + metadata) with full parameter and modifier detail in one call
get_extension_methods — Every extension member applicable to a type — including arrays, nullables and tuples — from the solution and referenced assemblies (so LINQ shows up), using Roslyn's own applicability rules; covers C# 14
extensionblocks including properties and static membersget_operators — Every user-defined operator and conversion operator on a type (source + metadata) with kind, signature, parameters, and source location. Includes synthesized record equality and .NET 7+ checked variants
get_call_graph — Transitive caller/callee graph for a method, depth-bounded with cycle detection
get_file_overview — Compound tool: types defined in a file + file-scoped diagnostics in one call
Response shape
All list-returning tools wrap their results in a uniform envelope:
{
"items": [ ... ],
"totalCount": 142,
"truncated": false,
"limit": 500,
"summary": { ... }
}When truncated is true, the items are the top N by the tool's natural sort order (severity-first, worst-first, by-project, etc.) — usually that's exactly what you want. Raise limit only if the missing tail items matter for the task.
Tools that include a summary aggregate today:
get_diagnostics—{ error, warning, info, hidden }countsfind_references—{ byProject: { name: count }, byKind: { kind: count } }find_callers,find_attribute_usages—{ byProject: { name: count } }search_symbols,find_reflection_usage—{ byKind: {...} }find_unused_symbols—{ byKind, filteredOut: { testMethod, testContainer, mcpTool, generated, composition, interop } }find_naming_violations—{ byRule: {...} }get_complexity_metrics—{ max, avg, overThreshold, maxCognitive }(the first three describe the selectedmetric)
Single-object tools (get_type_overview, get_symbol_context, apply_code_action, etc.) return their bespoke shape directly — the envelope only wraps list-returning tools.
Error responses
When a tool can't proceed (symbol not resolved, solution not trusted, file not found, ambiguous match, etc.), the response is an isError: true content block carrying a structured JSON body:
{
"code": "SolutionNotTrusted",
"message": "Solution 'Foo.sln' is not trusted for analyzer execution. ...",
"details": { "solutionPath": "C:\\Foo.sln" }
}Error codes (switch on code to handle each):
SymbolNotFound— type / method / property could not be resolved.SolutionNotTrusted—get_diagnosticsorget_code_fixesrequested analyzers but the solution hasn't been authorized viatrust_solution.AmbiguousMatch—set_active_solution/unload_solutionmatched multiple solutions;details.matcheslists them.FileNotFound— file path or baseline doesn't exist (or isn't in any loaded project).ProjectNotFound— solution name didn't match any loaded solution.InvalidArgument— caller-supplied input was malformed, unsupported, or out of range.Internal— unexpected error not modeled above;messagecarries the underlying exception text.
Cancellation: the MCP framework's native cancellation is honored. Cancelling a tools/call request mid-flight terminates the operation; long-running tools (get_diagnostics with analyzers, get_code_actions, apply_code_action, get_code_fixes) check the token at hot-loop boundaries.
External Assemblies
Metadata-origin symbols (from NuGet packages and referenced assemblies) are first-class citizens:
Tier 1 — Navigation (
find_references,find_callers,find_implementations): Accepts closed-source type and member names. Resolves them from assembly metadata and reports all source-level usage sites.Tier 2 — Inspection (
inspect_external_assembly): Browse namespaces, types, members, and XML doc comments from any referenced assembly without decompiling.Tier 3 — IL (
peek_il): Decompile a specific method to annotated ilasm-style IL using ICSharpCode.Decompiler — useful for understanding the internals of NuGet libraries.
Location-returning results include an Origin field (source or metadata) and an IsGenerated flag to distinguish hand-written code from closed-source or generated output.
Runtime configuration
ROSLYN_CODELENS_OPEN_PROJECT_TIMEOUT_SECONDS— per-project MSBuild load timeout (default300). When a project exceeds this duration during workspace open, it's recorded as aSkippedProjectsentry withkind: "Timeout"and the rest of the solution still loads. Useful when a legacy or malformed project wedges theBuildHost-net472subprocess.
Security: Trust Model
get_diagnostics and get_code_fixes can load Roslyn analyzers — DLLs that execute in-process. To prevent untrusted analyzers from running automatically, this server uses a VS/Rider-style trust model:
Solutions passed on the CLI at startup are auto-trusted for the current session.
Other solutions must be explicitly trusted via the
trust_solutionMCP tool.Analyzer DLLs must come from the user's NuGet global packages folder, the dotnet SDK install dir, or the solution's own
bin/obj. Other paths are skipped.
Use the list_trusted_paths and revoke_trust tools to inspect and manage trust state. Persistent trust is stored at %APPDATA%\roslyn-codelens\trust.json.
See SECURITY.md for the full threat model.
Quick Start
npx (any MCP client)
{
"mcpServers": {
"roslyn-codelens": {
"type": "stdio",
"command": "npx",
"args": ["-y", "roslyn-codelens-mcp"]
}
}
}The npm package ships no server code — it is a launcher that installs the RoslynCodeLens.Mcp
.NET global tool at a matching version and execs it, so the .NET 10 SDK must be on PATH.
Subsequent starts skip the install entirely and work offline.
VS Code / Visual Studio (via dnx)
Add to your MCP settings (.vscode/mcp.json or VS settings):
{
"servers": {
"roslyn-codelens": {
"type": "stdio",
"command": "dnx",
"args": ["RoslynCodeLens.Mcp", "--yes"]
}
}
}Claude Code Plugin
claude install gh:MarcelRoozekrans/roslyn-codelens-mcp.NET Global Tool
dotnet tool install -g RoslynCodeLens.McpThen add to your MCP client config:
{
"mcpServers": {
"roslyn-codelens": {
"command": "roslyn-codelens-mcp",
"args": [],
"transport": "stdio"
}
}
}Docker
Runs without a .NET SDK on the host; the solution is bind-mounted at /workspace.
docker build -t roslyn-codelens-mcp .
docker run -i --rm -v "$PWD:/workspace" roslyn-codelens-mcpThe mounted solution must be restored for MSBuildWorkspace to resolve its
references, and tool output reports container paths rather than host paths — see
docs/site/docs/getting-started/docker.md.
Usage
The server automatically discovers .sln files by walking up from the current directory. You can also pass one or more solution paths directly:
# Single solution
roslyn-codelens-mcp /path/to/MySolution.sln
# Multiple solutions — switch between them with set_active_solution
roslyn-codelens-mcp /path/to/A.sln /path/to/B.slnWhen multiple solutions are loaded, use list_solutions to see what's available and set_active_solution("B") to switch context. The first path is active by default.
Performance
All type lookups use pre-built reverse inheritance maps, member indexes, and attribute indexes for O(1) access. Benchmarked on an i9-12900HK with .NET 10.0.7:
Tool | Latency | Memory |
| 2.1 µs | 576 B |
| 2.5 µs | 720 B |
| 2.8 µs | 1.5 KB |
| 3.5 µs | 1.3 KB |
| 3.7 µs | 2.7 KB |
| 4.1 µs | 1.0 KB |
| 16 µs | 23 KB |
| 19 µs | 1.6 KB |
| 72 µs | 904 B |
| 78 µs | 24 KB |
| 115 µs | 14 KB |
| 159 µs | 35 KB |
| 265 µs | 3.5 KB |
| 478 µs | 16 KB |
| 564 µs | 259 KB |
| 705 µs | 19 KB |
| 781 µs | 25 KB |
| 792 µs | 54 KB |
| 797 µs | 101 KB |
| 822 µs | 99 KB |
| 849 µs | 48 KB |
| 885 µs | 247 KB |
| 1.1 ms | 104 KB |
| 1.1 ms | 34 KB |
| 3.5 ms | 286 KB |
| 3.8 ms | 224 KB |
| 3.9 ms | 557 KB |
| 5.8 ms | 333 KB |
| 7.0 ms | 335 KB |
| 8.4 ms | 396 KB |
| 10 ms | 337 KB |
| 12 ms | 399 KB |
| 15 ms | 788 KB |
| 23 ms | 1.0 MB |
| 28 ms | 1013 KB |
| 33 ms | 1.3 MB |
Solution loading (one-time) | ~4.1 s | 16 MB |
Hot Reload
The server watches .cs, .csproj, .props, and .targets files for changes. When a change is detected, affected projects are lazily re-compiled on the next tool query — only stale projects and their downstream dependents are re-compiled, not the full solution.
Location-returning tools include an IsGenerated flag to distinguish source-generator output from hand-written code.
Requirements
.NET 10 SDK
A .NET solution with compilable projects
Project compatibility
The server analyses every project that MSBuildWorkspace can load under the .NET SDK runtime.
Supported: SDK-style projects (<Project Sdk="...">), any target framework — net48, net6.0, net8.0, net10.0, etc. .NET Framework targets work fine as long as the csproj uses the SDK-style format.
Skipped (with a warning, not a crash): legacy non-SDK-style projects (<Project ToolsVersion="..." xmlns="http://schemas.microsoft.com/developer/msbuild/2003">, typically .NET Framework projects authored in older versions of Visual Studio). These rely on Microsoft.Common.props imports from the .NET Framework MSBuild that ships with Visual Studio, which is not available in the .NET SDK MSBuild runtime.
When a solution contains legacy projects, the server:
Loads every SDK-style project normally — all tools work for those.
Skips each legacy project and records it in
LoadedSolution.SkippedProjects.Surfaces the skipped list via
list_solutions(theSkippedProjectsarray on eachSolutionInfo) and in the return message ofload_solution. Each entry includes the project name, kind (Legacy), and reason.
To analyse a legacy project, convert it to SDK-style format (see Microsoft's migration guide) or open the solution from a Visual Studio Developer Command Prompt so the full Visual Studio MSBuild is on PATH.
Development
dotnet build
dotnet test
dotnet run --project benchmarks/RoslynCodeLens.Benchmarks -c ReleaseThird-party licenses
ICSharpCode.Decompiler — MIT license (v8+). Used for IL disassembly in the
peek_iltool.
License
MIT
Maintenance
Related MCP Servers
- AlicenseAqualityAmaintenanceA Model Context Protocol (MCP) server providing 62 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.Last updated6230MIT
- Alicense-qualityDmaintenanceMCP server enabling symbol-aware semantic search in Claude Code, allowing precise location of functions, types, and implementations via a symbol graph and embeddings.Last updated9MIT
- FlicenseAqualityCmaintenanceMinimal MCP server bridging a Roslyn C# language server to AI agents, exposing tools for diagnostics, call hierarchy, and type hierarchy.Last updated21
- Alicense-qualityDmaintenanceCode intelligence MCP server for Claude Code providing multi-project code graph, semantic search, session history, knowledge base, and web search.Last updated3MIT
Related MCP Connectors
Augments MCP Server - A comprehensive framework documentation provider for Claude Code
Hosted MCP server connecting claude.ai, ChatGPT and other AI apps to your own computer
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/MarcelRoozekrans/roslyn-codelens-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server