sharplens-mcp
SharpLensMcp
一个模型上下文协议(MCP)服务器,提供 92 个 AI 优化工具,用于使用 Microsoft Roslyn 进行 .NET/C# 语义代码分析、导航、重构和代码生成。
专为 AI 编码代理构建——提供编译器级别的精确代码理解,这是 AI 仅通过读取源文件无法推断的。
安装
通过 NuGet(推荐)
dotnet tool install -g SharpLensMcp然后运行:
sharplens通过 npm
npx -y sharplens-mcp从源码构建
dotnet build -c Release
dotnet publish -c Release -o ./publishRelated MCP server: LSP-MCP
Claude Code 设置
安装工具(任选其一):
dotnet tool install -g SharpLensMcp
# or
npx -y sharplens-mcp在项目根目录创建
.mcp.json:
{
"mcpServers": {
"sharplens": {
"type": "stdio",
"command": "npx",
"args": ["-y", "sharplens-mcp"],
"env": {
"DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"
}
}
}
}重启 Claude Code 以加载 MCP 服务器
验证:让 Claude 对 Roslyn 服务器运行健康检查
为何在 Claude Code 中使用此工具?
Claude Code 原生支持 LSP 以实现基本导航(跳转到定义、查找引用)。SharpLensMcp 增加了深度语义分析:
能力 | 原生 LSP | SharpLensMcp |
跳转到定义 | ✅ | ✅ |
查找引用 | ✅ | ✅ |
查找缺少 CancellationToken 的异步方法 | ❌ | ✅ |
影响分析(哪些会出错?) | ❌ | ✅ |
死代码检测 | ❌ | ✅ |
复杂度指标 | ❌ | ✅ |
带预览的安全重构 | ❌ | ✅ |
批量操作 | ❌ | ✅ |
配置
环境变量 | 描述 | 默认值 |
| 启动时自动加载的 | 无(必须调用 |
| 使用绝对路径而非相对路径 |
|
| 日志详细程度: |
|
| 长时间运行操作的超时时间 |
|
| 返回的最大诊断数 |
|
| 启用语义模型缓存 |
|
1.6.0 之前版本中最后四个变量的 ROSLYN_* 拼写仍会作为回退读取一个版本;当两者都设置时,SHARPLENS_* 拼写优先。
如果未设置 DOTNET_SOLUTION_PATH,则必须在使用其他工具前调用 load_solution 工具。
从 1.5.x 工具名称迁移
工具名称不再带有 roslyn: 前缀——冒号违反了 MCP 工具名称模式(^[a-zA-Z0-9_-]{1,64}$),某些客户端会强制执行该模式。每个工具都保留其名称,仅去掉前缀:
1.5.x 名称 | 1.6.0 名称 |
|
|
|
|
|
|
...所有工具遵循相同规则... | 去掉 |
tools/list 仅发布新名称。使用旧前缀名称的调用仍会作为一个版本被接受为别名,并将在下一个版本中移除。
AI 代理配置提示
AI 模型可能存在训练偏差,倾向于使用其原生工具(Grep、Read、LSP)而非 MCP 服务器工具,即使 SharpLensMcp 提供了更好的能力。
为确保最佳工具使用:
Claude Code:添加到项目的
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其他 MCP 客户端:在代理的系统提示中配置工具优先级
来自 Roslyn 的语义分析比基于文本的搜索更准确,尤其适用于重载方法、分部类和继承层次结构。
代理责任:文档同步
重要提示: SharpLensMcp 维护解决方案的内存表示以实现快速查询。当文件被外部修改(通过编辑/写入工具)时,代理负责同步更改。
何时调用 sync_documents:
操作 | 需要调用 sync_documents? |
使用编辑工具修改了 .cs 文件 | ✅ 是 |
使用写入工具创建了新的 .cs 文件 | ✅ 是 |
删除了 .cs 文件 | ✅ 是 |
使用了 SharpLensMcp 重构工具(重命名、提取等) | ❌ 否(自动更新) |
修改了 .csproj 文件 | ❌ 否(请改用 |
用法:
# After editing specific files
sync_documents(filePaths: ["src/MyClass.cs", "src/MyService.cs"])
# After bulk changes - sync all documents
sync_documents()为何如此设计?
这反映了 LSP(语言服务器协议)的工作方式——客户端(编辑器)通知服务器更改。这种方法:
消除竞态条件(代理控制时机)
避免文件监视器的复杂性和平台差异
比完全重新加载解决方案更快
让代理明确控制工作区状态
如果不进行同步: 查询可能返回过时数据(旧的方法签名、缺少新文件等)
功能
92 个语义分析工具 - 导航、重构、代码生成、诊断、发现、审计/质量
AI 优化描述 - 清晰的用法/输出/工作流模式
结构化响应 - 一致的
success/error/data格式,附带suggestedNextTools基于零的坐标 - 清晰的警告以防止差一错误
预览模式 - 应用前进行安全重构预览
批量操作 - 一次调用多次查找以减少上下文使用
工具类别
导航与发现(24 个工具)
工具 | 描述 |
| 位置处的语义信息 |
| 跳转到符号定义 |
| 所有引用;每个引用分类为读/写/调用/强制转换/typeof/nameof/属性;可选的 |
| 接口/抽象实现 |
| 影响分析——谁调用了这个? |
| 多跳调用者/被调用者图,带深度限制 + 循环检测 |
| 可达性 + 两个方法之间的连接调用路径;遵循调度,带有屏障和检查点 |
| 继承链 |
| 通配符模式搜索( |
| 多过滤器搜索(异步、公共等) |
| 按类型名称获取所有成员 |
| 一次调用获取多个类型 |
| 按名称获取详细签名 |
| 查找所有子类 |
| 完整继承链 |
| 列出符号上的属性 |
| 位置处的封闭符号 |
| 方法的所有重载 |
| 按属性查找类型/成员 |
| 检查 NuGet/BCL/外部程序集类型——成员 + XML 文档 |
| 将粘贴的堆栈跟踪映射到文件/行/符号,还原名称混淆 |
| 适用于类型的扩展方法——经典和 C# 14 块 |
| 符号的完整 XML 文档,包含展开的 |
| 导航到成员实现的基成员/接口成员 |
分析(17 个工具)
工具 | 描述 |
| 编译器错误/警告 + 已配置的分析器发现(StyleCop、Roslynator、NetAnalyzers);与 CI 匹配 |
| 与某个 git 引用相比的公共 API 破坏性变更报告 |
| 哪些异常可能从方法中逃逸,以及它们在哪里被捕获 |
| 结构相似性搜索(令牌分片指纹) |
| 计算死代码移除 + 新未使用的 using(仅生成) |
| 每个方法中不可达的基本块(真实 CFG,非启发式) |
| 计算修复 CS0246/CS0103 所需的 using(仅生成) |
| 变量赋值和使用 |
| 分支/可达性 |
| 如果更改会破坏什么? |
| A 能否赋值给 B? |
| 这个方法调用了什么? |
| 死代码检测 |
| 编译检查而不写入 |
| 圈复杂度、嵌套深度、代码行数、认知复杂度 |
| 项目和命名空间循环检测 |
| 未实现的接口/抽象成员 |
重构(16 个工具)
工具 | 描述 |
| 跨解决方案安全重命名 |
| 添加/删除/重新排序参数 |
| 提取方法 |
| 死代码检测 |
| 编译检查而不写入 |
| 圈复杂度、嵌套深度、代码行数、认知复杂度 |
| 项目和命名空间循环检测 |
| 未实现的接口/抽象成员 |
审计与质量(10 个工具)
工具 | 描述 |
| 通过传出耦合 + 传入耦合 + 成员数量阈值检测过度耦合的类型 |
| 查找未被任何 [Fact]/[Theory]/[Test]/[TestMethod] 覆盖的公共表面 |
| 哪些测试覆盖了一个符号——与 find_untested_code 相反 |
| 类型在哪里被构造( |
| 类型在 is/as/模式匹配中出现的位置 |
| 异常类型被抛出的位置(可选派生类型) |
| 异常类型被捕获的位置(可选通过基类子句) |
| async void / 阻塞异步 / 未转发的 CancellationToken |
| 在类型图上强制执行命名空间/项目依赖规则 |
| 命名审计,遵循 .editorconfig 规则,并带有常规默认值 |
发现(3 个工具)
工具 | 描述 |
| 扫描 DI 服务注册 |
| 检测反射/动态使用 |
| 显示 [InterceptsLocation] 调用重定向,包括生成的代码 |
基础设施(12 个工具)
工具 | 描述 |
| 服务器状态 + 加载保真度( |
| 编译器从未需要的 PackageReferences/ProjectReferences |
| 计算诊断 ID 的每个实例的修复(仅生成) |
| 加载 .sln/.slnx;报告部分加载( |
| 将文件更改同步到已加载的解决方案 |
| 解决方案结构 |
| 项目依赖 |
| 诊断的可用修复 |
| 应用特定的代码修复 |
| 每个项目的 NuGet 包列表 |
| 列出活动的源生成器 |
| 查看生成的源代码 |
其他 MCP 客户端
对于除 Claude Code 之外的 MCP 客户端,请添加到您的配置中:
{
"mcpServers": {
"sharplens": {
"command": "sharplens",
"args": [],
"env": {
"DOTNET_SOLUTION_PATH": "/path/to/your/Solution.sln (or .slnx)"
}
}
}
}用法
加载解决方案:使用
load_solution并传入.sln或.slnx文件路径(或设置DOTNET_SOLUTION_PATH)分析代码:使用 92 个工具中的任意一个进行导航、分析、重构、审计
安全重构:在应用之前使用
preview: true预览更改
架构
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要求
.NET 8.0 SDK 或更高版本 — 适用于 .NET 8、9、10 及未来版本。可分析任何 .NET 8+ 项目/解决方案。
兼容 MCP 的 AI 代理
常见问题
为什么工具以 net8.0 为目标——它能分析我的 .NET 9 / .NET 10 项目吗?
可以。net8.0 是工具自身的运行时下限——它依赖的 Roslyn 5.x 包需要此版本——而不是它能分析的上限。RollForward 允许已安装的工具在更新的 .NET 运行时上运行,而 MSBuildWorkspace 会从 csproj 加载每个项目的实际目标框架,因此一次安装即可分析面向 .NET 8、9、10 及更高版本的解决方案。
开发
添加新工具
将方法添加到匹配的
src/RoslynService.*.cs分部类(导航、分析、重构、调用分析……)并通过共享响应信封返回:
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" }
);
}在
src/ToolRegistry.cs中注册一个ToolDefinition—— 包括其名称、描述、输入模式、ReadOnly标志(可变工具传递ReadOnly: false并接收destructiveHint注解),以及一个通过JsonRpcParameters绑定参数并调用你的方法的处理程序。该注册表同时驱动tools/list和调度;无需单独编辑开关。两个测试确保其正确性:ToolsListGoldenTests锁定已发布模式的逐字节内容(当模式变更是有意为之时可重新捕获 golden 文件),而ToolSchemaParityTests断言处理程序读取的每个参数都在模式中声明。构建并发布:
dotnet build -c Release
dotnet publish -c Release -o ./publish添加两个测试层级 —— 针对确定性测试夹具的
RoslynService方法单元测试,以及通过 MCP 调度器(位于tests/SharpLensMcp.Tests/Mcp/)的连线测试,包含精确值锁定和错误路径。这是不可协商的;参见测试。
测试
每个测试必须满足 tests/SharpLensMcp.Tests/TESTING.md 中的测试章程(C1–C9) —— 这是长期有效的契约。主要规则如下:
锁定精确值(C1):断言具体的名称/计数/子字符串/错误代码/
(行, 列)—— 切勿仅使用NotBeNull/> 0/ 仅类型检查作为唯一断言。每个工具两个层级(C4):针对
Fixtures/*.cs夹具的单元测试和解包content[0].text的调度器(连线)测试,外加一个错误路径。正确的大小写(C3):进程内 Newtonsoft 生成 PascalCase 的
error.Code/meta.TotalCount;MCP 连线生成 camelCase。根据测试路径实际产生的大小写进行读取。确定性(C7):测试套件通过
xunit.runner.json序列化;夹具修改器始终恢复;超时测试使用强制取消的接缝,而非时序竞争。进程外主干(C6):
StdioIntegrationTests对每个类别的一个工具通过实际二进制文件进行值锁定,并通过 stdio 管道运行tools/listgolden 测试。提交前门控(C9):构建清理 + 通过是必要的但不充分 —— 重新阅读每个更改的测试,确认它在错误答案上会失败。
运行测试套件:
dotnet test -c Release关键文件
文件 | 用途 |
| 按关注点拆分的工具实现,分布在约 30 个分部类中(导航、分析、重构、检查、验证、类型发现、发现、外部 API、质量、指标、代码操作、代码生成、复合、调用分析、异常流、堆栈跟踪、API 表面、相似代码……)—— 每个文件的名称预示其内容 |
| MCP 协议机制:JSON-RPC 解析循环、 |
| 工具表面:每个工具一个 |
| 类型化的 JSON-RPC 参数访问器及其引发的 |
| 审计复合、构造函数生成器和签名变更解析器使用的类型化记录(每个文件一个类型) |
许可证
MIT - 详见 LICENSE。
Available Tools
62 toolsroslyn: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
Scored across 62 tools
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.
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.
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.
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
Related MCP Connectors
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
The Cortex MCP server provides read-only access to real-time engineering context from the Cortex developer portal, allowing AI coding assistants to answer natural language questions about your organization's catalog (microservices, libraries, domains, teams, infrastructure), scorecards (engineering standards and best practices), initiatives (goals and deadlines), and Engineering Intelligence metrics. It includes tools for querying documentation, tracking personal entities, and accessing AI-assisted insights across the entire Cortex ecosystem.
Nifty's MCP server — exposes tasks, projects, messages, and files as tools for AI agents.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Related MCP Servers
- AlicenseAqualityAmaintenanceRoslyn-based MCP server providing semantic code intelligence for .NET codebases — type hierarchies, call sites, DI registrations, and reflection usage for Claude Code6778MIT
- FlicenseAqualityDmaintenanceMinimal MCP server bridging a Roslyn C# language server to AI agents, exposing tools for diagnostics, call hierarchy, and type hierarchy.1-
- AlicenseNot gradedqualityBmaintenanceA 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.25MIT
- AlicenseNot gradedqualityBmaintenanceA 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.37Apache 2.0