SharpLens

io.github.pzalutski-pixel由 GitHub 帳號 pzalutski-pixel 發布v1.5.3更新於 Oct 26, 2026

67 semantic C#/.NET analysis tools via Roslyn: navigation, refactoring, codegen, audit.

已驗證STDIO僅桌面開發者工具資料與分析

概覽

AI 產生的概覽

本機 MCP 伺服器,透過 Roslyn 讓 AI 助理對 C#/.NET 方案進行語意分析:導覽、重構、程式碼產生與程式碼稽核。

可以做什麼
  • 導覽與搜尋符號:定義、參考、實作、呼叫端、呼叫圖、型別階層、多載、屬性與 XML 文件
  • 分析程式碼:編譯器與分析器診斷、變更影響、資料流與控制流、複雜度指標、無用程式碼、循環相依、公開 API 差異
  • 重構與產生:重新命名、變更簽章、擷取方法或介面、整理 using、格式化、套用程式碼動作、加入空值檢查、相等性成員與測試骨架
  • 品質稽核:上帝物件、未被測試的程式碼、非同步問題、架構規則、命名違規、未使用的相依套件
  • 檢視工作區:載入方案、同步已編輯檔案、查看專案結構、相依圖、NuGet 參考與產生的程式碼
適用情境
適合助理在 C#/.NET 程式庫上工作、需要純文字搜尋或 LSP 無法提供的編譯器級精確答案時使用,例如影響分析、無用程式碼、複雜度指標,或帶預覽的方案層級安全重構。
執行需求
以 stdio 在本機執行,可透過 .NET 全域工具或 npx 安裝。需要 .NET 8.0 SDK 或更新版本,以及支援 MCP 的用戶端。需將 DOTNET_SOLUTION_PATH 設為 .sln、.slnx 或 .slnf 檔案,或先呼叫 load_solution。選用設定包括 SHARPLENS_LOG_LEVEL、SHARPLENS_TIMEOUT_SECONDS、SHARPLENS_MAX_DIAGNOSTICS、SHARPLENS_ABSOLUTE_PATHS 與 SHARPLENS_ENABLE_SEMANTIC_CACHE。未宣告任何驗證機制。
安裝前請注意
許多工具會寫入原始碼檔案:重構、程式碼修正、格式化與產生類工具會修改 .cs 檔案,建議使用預覽模式並搭配版本控制。在伺服器之外變更的檔案必須以 sync_documents 同步,否則結果會過期。伺服器會在記憶體中保存方案副本,載入方案會執行 MSBuild 還原,可能經由網路取得 NuGet 套件。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 SharpLens,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

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

Via NuGet (Recommended)

bash
dotnet tool install -g SharpLensMcp

Then run with:

bash
sharplens

Via npm

bash
npx -y sharplens-mcp

Build from Source

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

Claude Code Setup

  1. Install the tool (pick one):
bash
dotnet tool install -g SharpLensMcp# ornpx -y sharplens-mcp
  1. Create .mcp.json in your project root:
json
{  "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:

CapabilityNative LSPSharpLensMcp
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 VariableDescriptionDefault
DOTNET_SOLUTION_PATHPath 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 immediatelyNone (must call load_solution)
SHARPLENS_ABSOLUTE_PATHSUse absolute paths instead of relativefalse (relative paths save tokens)
SHARPLENS_LOG_LEVELLogging verbosity: Trace, Debug, Information, Warning, ErrorInformation
SHARPLENS_TIMEOUT_SECONDSTimeout for long-running operations30
SHARPLENS_MAX_DIAGNOSTICSMaximum diagnostics to return100
SHARPLENS_ENABLE_SEMANTIC_CACHECache the file-path to document lookuptrue (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 name1.6.0 name
roslyn:load_solutionload_solution
roslyn:get_diagnosticsget_diagnostics
roslyn:rename_symbolrename_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:

ActionCall 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 filessync_documents(filePaths: ["src/MyClass.cs", "src/MyService.cs"])
# After bulk changes - sync all documentssync_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)

ToolDescription
get_symbol_infoSemantic info at position
go_to_definitionJump to symbol definition
find_referencesAll references; each classified read/write/invocation/cast/typeof/nameof/attribute; optional kind filter
find_implementationsInterface/abstract implementations
find_callersImpact analysis - who calls this?
get_call_graphMulti-hop callers/callees graph with depth bound + cycle detection
find_path_betweenReachability + the connecting call path(s) between two methods; follows dispatch, with barriers and a checkpoint
get_type_hierarchyInheritance chain
search_symbolsGlob pattern search (*Handler, Get*)
semantic_queryMulti-filter search (async, public, etc.)
get_type_membersAll members by type name
get_type_members_batchMultiple types in one call
get_method_signatureDetailed signature by name
get_derived_typesFind all subclasses
get_base_typesFull inheritance chain
get_attributesList attributes on a symbol
get_containing_memberEnclosing symbol at position
get_method_overloadsAll overloads of a method
find_attribute_usagesFind types/members by attribute
get_external_type_infoInspect NuGet/BCL/external assembly types — members + XML docs
resolve_stack_traceMap a pasted stack trace to file/line/symbol, mangling undone
get_extension_methodsExtensions applying to a type — classic and C# 14 blocks
get_documentationFull XML docs for a symbol with <inheritdoc> expanded
get_super_methodNavigate to the base member / interface members a member implements

Analysis (17 tools)

ToolDescription
get_diagnosticsCompiler errors/warnings + configured analyzer findings (StyleCop, Roslynator, NetAnalyzers); matches CI
diff_api_surfacePublic-API breaking-change report vs a git ref
get_exception_flowWhich exceptions can escape a method, and where they're caught
find_similar_codeStructural similarity search (token-shingle fingerprints)
remove_unused_codeCompute dead-code removals + newly unused usings (generation-only)
find_dead_branchesUnreachable basic blocks per method (real CFG, not heuristics)
add_missing_importsCompute the usings that fix CS0246/CS0103 (generation-only)
analyze_data_flowVariable assignments and usage
analyze_control_flowBranching/reachability
analyze_change_impactWhat breaks if changed?
check_type_compatibilityCan A assign to B?
get_outgoing_callsWhat does this method call?
find_unused_codeDead code detection
validate_codeCompile check without writing
get_complexity_metricsCyclomatic, nesting, LOC, cognitive
find_circular_dependenciesProject and namespace cycle detection
get_missing_membersUnimplemented interface/abstract members

Refactoring (16 tools)

ToolDescription
rename_symbolSafe rename across solution
change_signatureAdd/remove/reorder parameters
extract_methodExtract with data flow analysis
extract_interfaceGenerate interface from class
generate_constructorFrom fields/properties
move_type_to_fileCompute the contents to move a type into its own file (generation-only)
split_typeCompute a partial-class split for selected members (generation-only)
organize_usingsSort and remove unused
organize_usings_batchBatch organize multiple files
format_document_batchBatch format files in project
get_code_actions_at_positionAll Roslyn refactorings at position
apply_code_action_by_titleApply any refactoring by title
implement_missing_membersGenerate interface stubs
encapsulate_fieldField to property
inline_variableInline temp variable
extract_variableExtract expression to variable

Code Generation (3 tools)

ToolDescription
add_null_checksGenerate ArgumentNullException guards
generate_equality_membersEquals/GetHashCode/operators
generate_test_stubCompilable test skeleton for a method (framework auto-detected)

Compound Tools (7 tools)

ToolDescription
get_type_overviewFull type info in one call
analyze_methodSignature + callers + outgoing calls + location
get_file_overviewFile summary with diagnostics
get_method_sourceSource code by name
get_method_source_batchMultiple method sources in one call
get_instantiation_optionsHow to create a type
get_project_healthComposite audit dashboard: diagnostics + unused + coupling + coverage per project

Audit & Quality (10 tools)

ToolDescription
find_god_objectsDetect over-coupled types via efferent + afferent coupling + member-count thresholds
find_untested_codeFind public surface no test reaches — tests detected as xUnit, NUnit, MSTest, TUnit, Reqnroll and SpecFlow discover them, with setup, fixtures and step bindings
find_testsWhich tests cover a symbol — the inverse of find_untested_code
find_type_instantiationsWhere a type is constructed (new T)
find_pattern_usagesWhere a type appears in is/as/pattern matches
find_throw_sitesWhere an exception type is thrown (optionally derived)
find_catch_blocksWhere an exception type is caught (optionally via a base clause)
find_async_issuesasync void / blocking-on-async / unforwarded CancellationToken
check_architectureEnforce namespace/project dependency rules over the type graph
find_naming_violationsNaming audit honoring .editorconfig rules, with conventional defaults

Discovery (3 tools)

ToolDescription
get_di_registrationsScan DI service registrations
find_reflection_usageDetect reflection/dynamic usage
find_interceptorsSurface [InterceptsLocation] call rerouting, generated code included

Infrastructure (12 tools)

ToolDescription
health_checkServer status + load fidelity (partial flag, declared-vs-loaded projects, loadFailures, loadWarnings, lastLoadFailure) — check without reloading
find_unused_dependenciesPackageReferences/ProjectReferences the compiler never needs
fix_allCompute the fix for every instance of a diagnostic id (generation-only)
load_solutionLoad .sln/.slnx/.slnf; reports partial loads (partial + loadFailures: dropped projects, failed restores, projects loaded without references) and MSBuild warnings (loadWarnings) separately
sync_documentsSync file changes into loaded solution
get_project_structureSolution structure
dependency_graphProject dependencies
get_code_fixesAvailable fixes for a diagnostic
apply_code_fixApply a specific code fix
get_nuget_dependenciesNuGet package listing per project
get_source_generatorsList active source generators
get_generated_codeView generated source code

Other MCP Clients

For MCP clients other than Claude Code, add to your configuration:

json
{  "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        |        vMicrosoft.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:
csharp
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:

bash
dotnet build -c Releasedotnet 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:

bash
dotnet test -c Release

Key Files

FilePurpose
src/RoslynService.cs + the src/RoslynService.*.cs partialsTool 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.csMCP protocol mechanics: JSON-RPC parse loop, initialize negotiation, per-call timeout, in-band vs protocol error mapping
src/ToolRegistry.cs + src/ToolDefinition.csThe tool surface: one ToolDefinition record per tool (name, schema, ReadOnly flag, handler). Drives tools/list order and dispatch lookup
src/JsonRpcParameters.cs + JsonRpcInvalidParamsException.csTyped JSON-RPC argument accessors and the -32602 Invalid params exception they raise
src/*Data.cs / *Entry.cs records, ConstructorMember.cs, SignatureChange.csTyped records used by the audit composite, constructor generator, and signature-change parser (one type per file)

License

MIT - See LICENSE for details.

來源:README.md,提交 35c4196

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v1.5.3最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分