Dotnet Coverage Mcp

io.github.Hyeonu-Cha由 GitHub 帳號 Hyeonu-Cha 發布v2.1.0更新於 Nov 20, 2026

MCP server for .NET coverage: run tests, parse Cobertura, find uncovered branches, append tests.

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

概覽

AI 產生的概覽

本機 MCP 伺服器,讓助理執行 .NET 測試、讀取 Cobertura 覆蓋率、找出未覆蓋分支與缺口、比較兩次執行並附加測試程式碼。

可以做什麼
  • 探索原始碼檔案並依行數預算分批,並分析測試目標的相依性、方法與難以控制的呼叫
  • 執行含覆蓋率的 dotnet test,回傳通過/失敗/略過數量、失敗詳情與 Cobertura 報告路徑
  • 彙總類別與方法覆蓋率、依目標覆蓋率檢查單一檔案、列出未覆蓋分支
  • 報告各檔案的覆蓋率缺口及可補足缺口的方法,並與基準比較覆蓋率變化
  • 偵測測試專案的框架、執行器、覆蓋率收集器與模擬套件
  • 將 C# 測試程式碼附加或插入測試檔案,並清理工作階段產物
適用情境
適合在 AI 用戶端內提升或檢查 .NET 儲存庫的測試覆蓋率,尤其是反覆迭代:先跑一次測試、找出缺口、撰寫測試、再跑並比較。也適合在撰寫測試前了解測試專案的技術堆疊。
執行需求
以本機 stdio 程序執行;需安裝 .NET 10 或更新版本,測試專案需有覆蓋率收集器(VSTest 上為 coverlet.collector,Microsoft.Testing.Platform 上為 Microsoft.Testing.Extensions.CodeCoverage)。可安裝為全域 .NET 工具或從原始碼執行。建議將 COVERAGE_MCP_ALLOWED_ROOT 設為儲存庫根目錄;可選 COVERAGE_MCP_DOTNET_TEST_TIMEOUT_MS 與 COVERAGE_MCP_HANG_TIMEOUT_SECONDS 調整逾時。
安裝前請注意
若未設定 COVERAGE_MCP_ALLOWED_ROOT,伺服器會接受任意檔案系統路徑,建議設定以限制存取範圍。它會執行 dotnet test,並可能從 NuGet 連網還原套件。append_test_code 會寫入測試檔案,run_tests_with_coverage 與 get_coverage_diff 會寫入產物;cleanup_session 會刪除工作階段狀態與 TestResults 目錄。多個代理同時對同一測試專案執行會爭用建置輸出。

安裝

在 SourceWeft 中

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

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

其他 MCP 客戶端

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

README

dotnet-coverage-mcp

[build] [tests] [NuGet] [License: MIT]

An MCP (Model Context Protocol) server that gives AI assistants — Claude Code, Gemini CLI, and others — direct access to .NET test-coverage tooling. Run dotnet test, parse Cobertura XML, identify uncovered branches, diff coverage between runs, and append test code — all over stdio.

Purpose

This server lets an AI assistant run unit tests, collect coverage data, and analyse results — all without leaving the chat. Instead of manually running dotnet test and parsing reports, the AI can call the server's tools directly to:

  • Discover source files and build smart batches by line budget
  • Run a filtered set of tests and collect coverage
  • Read compact, AI-optimised coverage summaries (method-level line/branch rates)
  • Check per-file coverage against a configurable target rate (default 80%)
  • Identify uncovered branches as structured JSON
  • Diff coverage between runs to see only what changed
  • Append new test code to an existing test file with atomic writes

How It Works

The server starts as a console process and communicates over stdio using the MCP protocol. An MCP-compatible client (Claude Code, Gemini CLI, etc.) launches the process and calls its tools as if they were functions.

AI Client  <--stdio/MCP-->  dotnet-coverage-mcp  <--shell-->  dotnet test

Available Tools

Tools are named here as MCP clients list and call them.

ToolDescription
get_source_filesDiscover .cs files from a file, folder, or .csproj project. For a folder or project, files that are not test targets (entry points, DI registration, generated code, data-only models, test projects) are left out, counted per kind in excludedByKind and sampled under excluded with the reason; a .csproj scope also stops at nested projects. Returns file metadata (lines, method count) and smart batches grouped by lineBudget, 10 batches per call (moreBatches counts the rest, skipBatches gets them).
run_tests_with_coverageRun dotnet test with code coverage (coverlet on VSTest; Microsoft's CodeCoverage extension when global.json selects Microsoft.Testing.Platform). Returns pass/fail/skip counts and the path to the Cobertura XML that every other coverage tool reads. Distinguishes testsFailed (with each failure's message and stack, coverage kept), noTestsMatched, buildError (compiler errors only), projectBusy (the build's output files were held by another build, IDE or test host; run again) and testRunAborted (a test crashed or hung the test host: the reason, the crash's message and frames, and the tests that had not finished; no coverage is offered for such a run). A test project with several target frameworks writes one report per framework; they are merged into one, where code covered on any framework counts as covered. Supports forceRestore and sessionId for concurrent isolation.
get_coverage_summarySummarise class/method coverage from the Cobertura XML, sorted worst-first by branch coverage: totalClasses, the 25 worst classes (or topN), and in moreClasses how many were left out. Optional belowTarget/topN/methodsPerClass filters trim the response to what still needs work.
get_file_coverageGet coverage for a single source file from Cobertura XML. Returns allMeetTarget (true when all classes meet the configured targetRate for both line and branch coverage; default 0.8) and the file's path on this machine. Supports sessionId.
describe_test_targetFor a source file, per class: constructor dependencies with how to provide each in a test (mock, NullLogger, Options.Create, real instance for sealed/concrete classes, SQLite for a DbContext), public/internal methods with signatures and decision points, calls a test can't control (DateTime.Now, File.*, Guid.NewGuid()...) with the usual seam, a suggested test type with reasons, and existing test files. Syntax-only.
get_test_environmentDetect a test project's stack: framework (xUnit v2/v3, NUnit, MSTest) with the attributes to use, runner (VSTest or Microsoft.Testing.Platform), coverage collector, mocking and assertion libraries, integration-test packages, plus warnings such as a missing coverage collector. Reads obj/project.assets.json when restored.
get_coverage_gapsFor a scope (file, folder, .csproj or list), report per file whether it meets targetRate on lines and branches, and for each file below it the fewest methods that close its gap, with uncovered line ranges, uncovered branches and the source around them. One call per test cycle. Non-target files are skipped as in get_source_files.
get_uncovered_branchesFind uncovered branch conditions for methods matching a given name. Returns all matching methods with partial name support. Supports sessionId.
get_coverage_diffCompare current Cobertura XML against baseline. Shows method-level changes including new and removed methods. Supports sessionId for concurrent isolation.
append_test_codeInsert or append C# test code into a test file. Rejects code that is not valid C# member syntax with syntaxError, and a member the class already declares (same name and parameter types) with duplicateMember, leaving the file unchanged; sending exactly the same code again inserts nothing. Supports anchor-based insertion with whitespace-tolerant fallback matching; a fallback insertion that would break a file that compiled is refused with insertFailed. The inserted code is laid out like the members around it (indentation, the file's line endings, one blank line between members). Uses atomic writes to prevent file corruption.
cleanup_sessionRemove session state files and the TestResults-* directories the tool created (never the bare TestResults that dotnet test and Visual Studio use). Pass the sessionId you ran with to remove that session's artifacts; omit it to remove the single-agent ones (TestResults-mcp/, .coverage-state, .coverage-prev.xml) plus other sessions' artifacts older than maxAgeMinutes (default 120).

Protocol details

  • Tool annotations. The six query tools are marked readOnlyHint + idempotentHint, so clients that auto-approve read-only tools won't prompt for them. run_tests_with_coverage, append_test_code and get_coverage_diff write files but are not destructive. Only cleanup_session is destructiveHint: true. Only run_tests_with_coverage is openWorldHint: true, since a restore can reach NuGet.
  • Errors. A tool error comes back as {"error": "...", "errorType": "..."} text in a result flagged isError: true, so clients show it as a failed call. errorType is a stable name to branch on (fileNotFound, pathNotAllowed, testsFailed, buildError, duplicateMember, ...).
  • Server instructions. The initialize result carries a short workflow (environment → run → gaps → append → repeat) that clients put in the model's context.
  • Progress. When the client sends a progress token, run_tests_with_coverage reports milestones while dotnet test runs: restore, each project built, tests started, the result line.

Batch Workflow

For projects with many source files, the recommended workflow is:

  1. Discover — Call get_source_files on a folder or .csproj to get all files and smart batches
  2. Run once — Call run_tests_with_coverage without a filter (runs every test) to collect coverage across all files
  3. Find the gaps — Call get_coverage_gaps for the batch: per file below target, the methods to test, with the uncovered branches and source around them (no test re-run)
  4. Write tests — Use append_test_code to add test methods
  5. Re-run and diff — Run tests once, call get_coverage_diff to verify improvement
  6. Repeat — Continue until batch files meet the target rate (default 80%) or 3 cycles with no improvement, then move to next batch
  7. Clean up — Once the goal is reached, call cleanup_session (with the same sessionId, if you used one) to remove TestResults-mcp/ or TestResults-{hash}/ and the session state files. These are not deleted automatically — they persist until cleanup_session is called.

This minimises dotnet test invocations (the main bottleneck) while still tracking per-file progress.

Concurrency

Multiple AI agents can run in parallel by passing a sessionId to each tool call, which isolates their coverage artifacts:

  • Isolated output directories — run_tests_with_coverage creates TestResults-{hash}/ per session, preventing one agent from deleting another's XML mid-parse
  • Scoped state files — Coverage state is written to .mcp-coverage/.coverage-state-{hash}, so ResolveCoberturaPath resolves to the correct XML for each session
  • Scoped baselines — get_coverage_diff stores baselines as .coverage-prev-{hash}.xml per session
  • Atomic writes — All file writes (state files and test code) use write-to-temp-then-rename to prevent corruption from race conditions or process crashes

Limitation — build outputs are not session-scoped. sessionId isolates coverage artifacts, not the .NET build. dotnet test compiles the target project into its shared obj/ and bin/, which are not per-session, so two agents running run_tests_with_coverage against the same test project at the same time collide on those outputs. The run that loses returns projectBusy (its build hit CS2012/MSB3027, "being used by another process"), not buildError, and succeeds when run again after the other build finishes. Run parallel agents against different test projects, or on separate working copies of the repo. Multiple agents on one project are fine as long as their dotnet test builds don't overlap.

Without sessionId, tools use shared defaults — safe for single-agent use.

Requirements

  • .NET 10 (or later) to run the tool — https://dotnet.microsoft.com/download. The projects it tests do not have to be .NET 10: net8.0 and net9.0 test projects work, including in a repository whose global.json pins an older SDK, and so do test projects with several target frameworks (the end-to-end tests run one targeting net8.0;net10.0). As with any dotnet test, the runtime the tests target must be installed.

  • A coverage collector in the test project. On VSTest (the default), coverlet.collector. On Microsoft.Testing.Platform, Microsoft.Testing.Extensions.CodeCoverage, plus Microsoft.Testing.Extensions.TrxReport for per-failure details. MTP is used when the repository's global.json sets "test": { "runner": "Microsoft.Testing.Platform" }, which the .NET 10 SDK requires for MTP projects anyway. get_test_environment reports what a project has and what is missing.

  • An MCP-compatible client (Claude Code, Gemini CLI, etc.)

  • COVERAGE_MCP_ALLOWED_ROOT — recommended. Set to your repository root to restrict every tool's filesystem access to that subtree. Any path passed by the client outside this root is rejected with pathNotAllowed. When unset, the server logs a warning once and accepts any path (backward-compatible, but not recommended for shared environments).

    bash
    export COVERAGE_MCP_ALLOWED_ROOT=/path/to/your/repo

Optional settings, also environment variables:

VariableDefaultEffect
COVERAGE_MCP_DOTNET_TEST_TIMEOUT_MS600000 (10 min)Longest a whole dotnet test run may take before it is stopped (timeout).
COVERAGE_MCP_HANG_TIMEOUT_SECONDS30Longest a single test may run before it counts as hung and the run is stopped (VSTest; reported as testRunAborted). Raise it for long-running integration tests.

Install

Install the server as a global .NET tool from NuGet:

bash
dotnet tool install --global dotnet-coverage-mcp

After install, the dotnet-coverage-mcp command is on your PATH.

Build & Run (from source)

bash
cd <path-to-dotnet-coverage-mcp>
# Restore dependenciesdotnet restore
# Builddotnet build
# Rundotnet run

The server will start and wait for MCP messages over stdin/stdout.

MCP Client Configuration

After installing the global tool (dotnet tool install --global dotnet-coverage-mcp), register the server with your MCP client. Set COVERAGE_MCP_ALLOWED_ROOT to the repository you want the server to operate on.

Claude Code

bash
claude mcp add coverage --env COVERAGE_MCP_ALLOWED_ROOT=/path/to/your/repo -- dotnet-coverage-mcp

Claude Desktop

Add to claude_desktop_config.json (Settings → Developer → Edit Config):

json
{  "mcpServers": {    "coverage": {      "command": "dotnet-coverage-mcp",      "env": {        "COVERAGE_MCP_ALLOWED_ROOT": "/path/to/your/repo"      }    }  }}

Cursor

Add to ~/.cursor/mcp.json (global) or .cursor/mcp.json (per-project):

json
{  "mcpServers": {    "coverage": {      "command": "dotnet-coverage-mcp",      "env": {        "COVERAGE_MCP_ALLOWED_ROOT": "/path/to/your/repo"      }    }  }}

VS Code (GitHub Copilot)

Add to .vscode/mcp.json:

json
{  "servers": {    "coverage": {      "type": "stdio",      "command": "dotnet-coverage-mcp",      "env": {        "COVERAGE_MCP_ALLOWED_ROOT": "/path/to/your/repo"      }    }  }}

Run from source

To run from source instead of the global tool, use dotnet run:

json
{  "mcpServers": {    "coverage": {      "command": "dotnet",      "args": ["run", "--project", "<path-to-dotnet-coverage-mcp>"],      "transport": "stdio"    }  }}

Or point directly at the compiled executable:

json
{  "mcpServers": {    "coverage": {      "command": "<path-to-dotnet-coverage-mcp>\\bin\\Debug\\net10.0\\DotNetCoverageMcp.exe",      "transport": "stdio"    }  }}

Tool Parameters

get_source_files

ParameterTypeRequiredDescription
pathstringYesPath to a .cs file, folder, .csproj project, or a comma-separated list of .cs files. Files you name directly are always kept, even ones a folder scan would exclude
lineBudgetintNoMax total lines per batch (default: 300). Small files are grouped together; large files get their own batch.
skipBatchesintNoBatches to skip (default 0). At most 10 batches come back per call; when moreBatches is above 0, call again with the number received so far. The batches are the same on every call.

run_tests_with_coverage

ParameterTypeRequiredDescription
testProjectPathstringYesPath to the .csproj test project. Resolved to a rooted path and required to end in .csproj and exist; anything else (e.g. a CLI option) is rejected with invalidParameter or fileNotFound.
filterstringNoPassed to dotnet test --filter. A plain name matches tests whose fully qualified name contains it (OrderServiceTests, OrderServiceTests.PlacesOrder); full VSTest expressions also work (OrderTests|PaymentTests, Category=Unit). Omit or pass * to run every test. A filtered run's coverage covers only the tests that ran and replaces the previous report, so files those tests don't reach show as uncovered until the next full run.
workingDirstringNoWorking directory; defaults to the project directory
forceRestoreboolNoWhen true, skips the --no-restore flag. Use after scaffolding a new test project or adding NuGet packages.
sessionIdstringNoIsolates the output directory (TestResults-{hash}/) and state files for concurrent multi-agent use. Without it, results go to TestResults-mcp/.
includeClassstringNoRestrict coverage collection to types matching this name (coverlet Include filter, applied via a generated runsettings file passed with --settings). Independent of filter — pass an explicit value to scope coverage; omit it to collect coverage for everything the run touches. Namespace-qualified names are not supported.

get_coverage_summary

ParameterTypeRequiredDescription
coberturaXmlPathstringYesPath to coverage.cobertura.xml (returned by run_tests_with_coverage). Falls back to .mcp-coverage/.coverage-state if not found.
belowTargetdoubleNoWhen set (a fraction in [0,1], e.g. 0.8), consider only classes whose line OR branch coverage is below this threshold. Omit for all classes.
topNintNoReturn only the N lowest-branch-coverage classes (results are sorted worst-first). Default 25; moreClasses counts the rest.
methodsPerClassintNoKeep at most this many lowest-branch-coverage methods per class, trimming the rest. Omit to keep all methods.
sessionIdstringNoResolves the session-scoped state file for concurrent isolation.

get_file_coverage

ParameterTypeRequiredDescription
coberturaXmlPathstringYesPath to coverage.cobertura.xml (falls back to .mcp-coverage/.coverage-state if not found)
sourceFileNamestringYesFile to look up: an absolute path (as get_source_files returns), a repo-relative path (Services/ExampleService.cs) or a bare name (ExampleService.cs). Matched on whole path segments; a bare name found in several folders returns ambiguous with the candidates. The response's sourceFile is the file that matched, as a path on this machine (joined to the report's <source> root where coverlet records relative names).
sessionIdstringNoResolves session-scoped state file for concurrent isolation.
targetRatedoubleNoCoverage threshold (0.0–1.0) used to compute allMeetTarget. Default 0.8.

describe_test_target

ParameterTypeRequiredDescription
sourceFilePathstringYesFull path to the .cs file to be tested

Dependencies are classified from where their types are declared in the file's project (interface, abstract, sealed, DbContext subclass...), falling back to well-known framework types and the I-prefix convention for external types. Classes without public/internal methods (records, DTOs, exceptions) are not listed.

get_test_environment

ParameterTypeRequiredDescription
testProjectPathstringYesFull path to the test project's .csproj

Returns a one-line summary (e.g. xunit 2.9.3 on VSTest, coverlet.collector, Moq + FluentAssertions), the detected packages, conventions (test, data-driven, setup and teardown attributes for the framework) and warnings.

get_coverage_gaps

ParameterTypeRequiredDescription
coberturaXmlPathstringYesPath to coverage.cobertura.xml (falls back to .mcp-coverage/.coverage-state if not found)
pathstringYesScope: a .cs file, folder, .csproj, or comma-separated list of .cs files (e.g. a batch)
targetRatedoubleNoPer-file target (0.0–1.0) for both line and branch coverage. Default 0.8.
maxFilesintNoBelow-target files returned in detail, smallest gap first; the rest are listed with rates only. Default 5, at most 20.
maxMethodsPerFileintNoMaximum methods returned per file. Default 5, at most 20.
includeSourceboolNoInclude the source lines around each gap (2 lines of context, at most 30 per method). Default true.
sessionIdstringNoResolves the session-scoped state file for concurrent isolation.

Methods are ranked by how many uncovered lines and branch outcomes they hold, counting only the metric that is still below target, and picked until the file's gap is closed (closesGap). Files are named by their full paths, as the scope gives them. Files in the scope with no coverage data are listed under notInReport. A file edited after the coverage run is marked sourceChangedSinceRun: true and its source left out, since the report's line numbers may no longer match it; run the tests again first.

get_uncovered_branches

ParameterTypeRequiredDescription
coberturaXmlPathstringYesPath to coverage.cobertura.xml (falls back to .mcp-coverage/.coverage-state if not found)
methodNamestringYesMethod name as written in source (partial match supported; returns all matching methods). Async methods, lambdas and local functions are reported under the method they belong to; overloads are labelled Name (line N).
sessionIdstringNoResolves session-scoped state file for concurrent isolation.

get_coverage_diff

ParameterTypeRequiredDescription
coberturaXmlPathstringYesPath to the current coverage.cobertura.xml
workingDirstringNoDirectory for storing the baseline; defaults to the project folder the report belongs to (it walks up past TestResults*, coveragereport* and GUID folders)
sessionIdstringNoIsolates baseline as .coverage-prev-{hash}.xml and resolves session-scoped state file.

append_test_code

ParameterTypeRequiredDescription
testFilePathstringYesFull path to the target .cs test file. A path that is not a .cs file is rejected with invalidParameter.
codeToAppendstringYesC# code to insert. A member the target class already declares with the same name and parameter types is refused with duplicateMember; code that is already there exactly as given (a repeated call) inserts nothing.
insertAfterAnchorstringNoIf provided, inserts code after the last member containing this string (whitespace-tolerant), in whichever class holds it. If omitted, appends at the end of the target class.
targetClassstringNoSimple name of the class to insert into, nested classes included. If omitted, the file's test class is used: the last top-level class with test attributes ([Fact], [Test], [TestMethod], [TestFixture], ...), else the last top-level class.

cleanup_session

ParameterTypeRequiredDescription
workingDirstringYesProject working directory containing .mcp-coverage/ and TestResults artifacts
sessionIdstringNoWhen set, removes only state files and directories scoped to this session. When omitted, removes the single-agent artifacts whatever their age.
maxAgeMinutesintNoWhen sessionId is omitted, also removes other sessions' artifacts older than this many minutes. Default 120.

State Files

All state files are written to a .mcp-coverage/ subdirectory inside the working directory, keeping the project root clean. Add .mcp-coverage/ to the target repository's .gitignore.

FilePurpose
.coverage-stateDefault Cobertura XML path for single-agent use
.coverage-state-{hash}Session-scoped Cobertura XML path
.coverage-prev.xmlDefault coverage baseline for diff
.coverage-prev-{hash}.xmlSession-scoped coverage baseline

Plugin (Skills & Agent)

This repo includes a plugin/ directory with Claude Code skills and an agent definition for guided test coverage workflows:

plugin/├── plugin.json├── agents/│   └── test-coverage.agent.md└── skills/    ├── scaffold-test-files/     — Create test directories and files mirroring source structure    ├── run-coverage/            — Run tests and view coverage reports    ├── analyze-coverage-gaps/   — Find uncovered branches and compare diffs    └── improve-test-coverage/   — Iterative loop to reach 80% coverage

The skills support NUnit, xUnit, and MSTest with framework-agnostic reference docs in references/unit.md and references/integration.md.

Dependencies

PackageVersionPurpose
Microsoft.Extensions.Hosting10.0.15DI and hosting
ModelContextProtocol2.4.0MCP server framework
Microsoft.CodeAnalysis.CSharp5.12.0Roslyn AST for safe code insertion and accurate method counting (~15MB)

Security

dotnet-coverage-mcp runs as a local stdio process and validates every tool argument against COVERAGE_MCP_ALLOWED_ROOT to confine filesystem access. See SECURITY.md for the threat model, hardening recommendations, and how to report a vulnerability.

Contributing

Contributions are welcome. See CONTRIBUTING.md for development setup, pull request guidelines, and code conventions. Notable changes are tracked in CHANGELOG.md.

Releasing

Maintainer-only — release process, NuGet publishing, and MCP registry submission are documented in RELEASING.md.

來源:README.md,提交 642be01

工具

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

版本歷史

4
  1. v2.1.0最新Nov 20, 2026
  2. v2.0.7Nov 20, 2026
  3. v2.0.6Nov 19, 2026
  4. v0.1.1Sep 16, 2026

評分

已滿足適用檢查項的 50%

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

  • 近 30 天內可連通25 分

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

  • 已宣告認證方式10 分

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

  • 已列出工具15 分

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

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