dotnet-coverage-mcp
An MCP server that lets AI assistants (Claude Code, Gemini CLI, Cursor, Copilot) raise .NET test coverage without leaving the chat. It runs dotnet test, reads the Cobertura report, tells the agent which methods and branches still need tests, and inserts the tests it writes.
- Small answers. The agent gets compact JSON: the methods to test, their uncovered branches and the source around them. It never reads the raw coverage XML.
- Fewer test runs. One run covers a whole batch of files, and the gaps for all of them come back in one call.
- Tests that compile. It detects the project's test framework, mocking and assertion libraries, and how to construct each class under test.
Install
1. Install the tool (needs the .NET 10 SDK or later):
dotnet tool install --global dotnet-coverage-mcp
2. Add it to your MCP client. Set COVERAGE_MCP_ALLOWED_ROOT to the repository the server should work on.
claude mcp add coverage --env COVERAGE_MCP_ALLOWED_ROOT=/path/to/your/repo -- dotnet-coverage-mcp
Claude Desktop, Cursor, VS Code
Claude Desktop: add to claude_desktop_config.json (Settings → Developer → Edit Config).
Cursor: add to ~/.cursor/mcp.json (global) or .cursor/mcp.json (per project).
{
"mcpServers": {
"coverage": {
"command": "dotnet-coverage-mcp",
"env": {
"COVERAGE_MCP_ALLOWED_ROOT": "/path/to/your/repo"
}
}
}
}
VS Code (GitHub Copilot): add to .vscode/mcp.json.
{
"servers": {
"coverage": {
"type": "stdio",
"command": "dotnet-coverage-mcp",
"env": {
"COVERAGE_MCP_ALLOWED_ROOT": "/path/to/your/repo"
}
}
}
}
Run from source
cd <path-to-dotnet-coverage-mcp>
dotnet restore
dotnet build
dotnet run
The server starts and waits for MCP messages on stdin/stdout. To use it from a client, point the client at dotnet run:
{
"mcpServers": {
"coverage": {
"command": "dotnet",
"args": ["run", "--project", "<path-to-dotnet-coverage-mcp>"],
"transport": "stdio"
}
}
}
or at the compiled executable:
{
"mcpServers": {
"coverage": {
"command": "<path-to-dotnet-coverage-mcp>\\bin\\Debug\\net10.0\\DotNetCoverageMcp.exe",
"transport": "stdio"
}
}
}
Get started
Ask your assistant in plain words. The server sends the client a short workflow at startup, so the agent knows which tool comes next.
Bring every file in src/Orders to 80% line and branch coverage. The tests are in tests/Orders.Tests.
Which methods in OrderService.cs have no tests yet?
Bring src/Orders to 80% coverage, integration tests first, then unit tests for what's left. The tests are in tests/Orders.Tests.
The agent then works in a loop:
- Discover:
get_source_fileson a folder or.csprojlists the files to cover, grouped into batches. - Run once:
run_tests_with_coveragewithout a filter runs every test and collects coverage for all files. - Find the gaps:
get_coverage_gapsfor a batch returns, per file below target, the methods to test, with their uncovered branches and the source around them. No test re-run. - Write tests:
append_test_codeadds the test methods. - Re-run and diff: run the tests again;
get_coverage_diffshows what improved. - Repeat until the batch meets the target (80% by default) or 3 cycles bring no improvement, then move to the next batch.
- Clean up:
cleanup_sessionremovesTestResults-mcp/(orTestResults-{hash}/) and the state files. Nothing is deleted until it is called.
This keeps dotnet test runs, the slowest step, to a minimum while tracking progress per file.
Unit tests first, or integration tests first
With the plugin's improve-test-coverage skill, you choose which kind of test comes first. Unit tests first is the default; ask for integration-first to change it.
| Unit-first (default) | Integration-first (when asked) | |
|---|---|---|
| First | Unit tests, with every dependency mocked | Integration tests: your classes run together for real, EF Core on SQLite in-memory, only external services (HTTP APIs, storage, email) mocked |
| Then | Integration tests only for classes that need them (a DbContext dependency, a hosted service) | Unit tests for the gaps the integration tests didn't reach, usually error and catch branches |
Ask for it in plain words, as in the last example under Get started.
Either way, each class gets its own test files: OrderServiceUnitTests.cs and OrderServiceIntegrationTests.cs, or the suffix your test project already uses. Tests for different classes never go into one combined file, and each file sets up its own mocks.
How integration-first tests are built
- Services and repositories come from a
ServiceCollection: the app's ownAddXxx()registrations, with external services replaced by mocks. - Controllers are created from that same
ServiceCollection, without starting the app. When the app's host starts in tests,WebApplicationFactory<Program>also covers routing, model binding and authentication. - The database is SQLite in-memory: a new, empty database per test, created from your EF Core model and gone when the test ends. No SQL Server, Docker or files. When the model doesn't build on SQLite:
- If two schemas share a table name, schemas are folded into table names in the test project only.
- Otherwise,
UseInMemoryDatabaseis used. - If that fails too, the class is reported and skipped.
- Tests that save data check the response, then read the database again to confirm what was saved.
Requires
| For | Needs | Added by the agent if missing |
|---|---|---|
| Choosing the strategy | The plugin's improve-test-coverage skill (Claude Code). With the MCP server alone the tools still work, but no skill sets the order: say which tests you want first. | No |
| Mocking | Moq, NSubstitute or FakeItEasy in the test project, whichever it already uses | Yes |
A DbContext | Microsoft.EntityFrameworkCore.Sqlite in the test project | Yes |
Controllers through WebApplicationFactory | Microsoft.AspNetCore.Mvc.Testing, and an app whose host starts in tests | The package yes; host startup no (the agent falls back to creating controllers directly) |
What the agent reports instead of testing
The agent writes test files only and never changes your production code. Some things no test can fix, so it lists them in its final report instead of retrying:
| Reported | Why | Example |
|---|---|---|
| Possible bugs | A test failed because the code does something its name or callers don't imply. The agent doesn't change the test to match, which would lock the bug in. | OrderController.Get: returns 500 for an unknown id instead of 404 |
| Methods that need SQL Server | Stored procedures and raw SQL don't run on SQLite. | OrderRepository.GetMonthlyTotalsAsync: executes SQL Server stored procedures via SqlConnection/FromSqlRaw, not testable without a live SQL Server |
| Excluded files | Not test targets: entry points, DI registration, generated code, data-only models. | Program.cs |
| Files not in the report | The test project doesn't reference their project, so no test can cover them. |
Tools
Tools are named as MCP clients list and call them.
| Tool | Use it to |
|---|---|
get_test_environment | Detect the test framework, runner, coverage collector, and mocking and assertion libraries. |
describe_test_target | Learn how to construct a class in a test, and whether a unit or integration test fits. |
get_source_files | List the .cs files to cover in a file, folder or project, grouped into batches. |
run_tests_with_coverage | Run dotnet test with coverage and get the Cobertura report path. |
get_coverage_gaps | Get, per file below target, the methods and branches to test next. |
get_coverage_summary | See the classes with the worst coverage. |
get_file_coverage | Check one file against the target rate. |
get_uncovered_branches | See the uncovered branch conditions of a method. |
get_coverage_diff | Compare coverage with the previous run. |
append_test_code | Insert test methods into a test file. |
cleanup_session | Remove the test results and state files the server created. |
Full tool reference: what each tool returns, and its parameters
get_source_files
Discover .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).
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Path 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 |
lineBudget | int | No | Max total lines per batch (default: 300). Small files are grouped together; large files get their own batch. |
skipBatches | int | No | Batches 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
Run 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
testProjectPath | string | Yes | Path 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. |
filter | string | No | Passed 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. |
workingDir | string | No | Working directory; defaults to the project directory |
forceRestore | bool | No | When true, skips the --no-restore flag. Use after scaffolding a new test project or adding NuGet packages. |
sessionId | string | No | Isolates the output directory (TestResults-{hash}/) and state files for concurrent multi-agent use. Without it, results go to TestResults-mcp/. |
includeClass | string | No | Restrict 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_gaps
For 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
coberturaXmlPath | string | Yes | Path to coverage.cobertura.xml (falls back to .mcp-coverage/.coverage-state if not found) |
path | string | Yes | Scope: a .cs file, folder, .csproj, or comma-separated list of .cs files (e.g. a batch) |
targetRate | double | No | Per-file target (0.0–1.0) for both line and branch coverage. Default 0.8. |
maxFiles | int | No | Below-target files returned in detail, smallest gap first; the rest are listed with rates only. Default 5, at most 20. |
maxMethodsPerFile | int | No | Maximum methods returned per file. Default 5, at most 20. |
includeSource | bool | No | Include the source lines around each gap (2 lines of context, at most 30 per method). Default true. |
sessionId | string | No | Resolves 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_test_environment
Detect 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
testProjectPath | string | Yes | Full 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.
describe_test_target
For 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. Per class, testFiles names the test file to use for unit and integration tests: existing when one is found (closest to the source's folder when there are several), otherwise a fileName that follows the suffix most of the repository's test files use (UnitTests, Tests or Test; UnitTests on a tie or with none), with generic type parameters dropped. Syntax-only.
| Parameter | Type | Required | Description |
|---|---|---|---|
sourceFilePath | string | Yes | Full 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_coverage_summary
Summarise 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
coberturaXmlPath | string | Yes | Path to coverage.cobertura.xml (returned by run_tests_with_coverage). Falls back to .mcp-coverage/.coverage-state if not found. |
belowTarget | double | No | When 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. |
topN | int | No | Return only the N lowest-branch-coverage classes (results are sorted worst-first). Default 25; moreClasses counts the rest. |
methodsPerClass | int | No | Keep at most this many lowest-branch-coverage methods per class, trimming the rest. Omit to keep all methods. |
sessionId | string | No | Resolves the session-scoped state file for concurrent isolation. |
get_file_coverage
Get coverage for a single source file from Cobertura XML. Returns allMeetTarget (true when all classes meet targetRate for both line and branch coverage) and the file's path on this machine.
| Parameter | Type | Required | Description |
|---|---|---|---|
coberturaXmlPath | string | Yes | Path to coverage.cobertura.xml (falls back to .mcp-coverage/.coverage-state if not found) |
sourceFileName | string | Yes | File 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). |
sessionId | string | No | Resolves session-scoped state file for concurrent isolation. |
targetRate | double | No | Coverage threshold (0.0–1.0) used to compute allMeetTarget. Default 0.8. |
get_uncovered_branches
Find uncovered branch conditions for methods matching a given name. Returns all matching methods with partial name support.
| Parameter | Type | Required | Description |
|---|---|---|---|
coberturaXmlPath | string | Yes | Path to coverage.cobertura.xml (falls back to .mcp-coverage/.coverage-state if not found) |
methodName | string | Yes | Method 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). |
sessionId | string | No | Resolves session-scoped state file for concurrent isolation. |
get_coverage_diff
Compare current Cobertura XML against the baseline. Shows method-level changes including new and removed methods.
| Parameter | Type | Required | Description |
|---|---|---|---|
coberturaXmlPath | string | Yes | Path to the current coverage.cobertura.xml |
workingDir | string | No | Directory for storing the baseline; defaults to the project folder the report belongs to (it walks up past TestResults*, coveragereport* and GUID folders) |
sessionId | string | No | Isolates baseline as .coverage-prev-{hash}.xml and resolves session-scoped state file. |
append_test_code
Insert 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
testFilePath | string | Yes | Full path to the target .cs test file. A path that is not a .cs file is rejected with invalidParameter. |
codeToAppend | string | Yes | C# 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. |
insertAfterAnchor | string | No | If 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. |
targetClass | string | No | Simple 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
Remove session state files and the TestResults-* directories the tool created (never the bare TestResults that dotnet test and Visual Studio use).
| Parameter | Type | Required | Description |
|---|---|---|---|
workingDir | string | Yes | Project working directory containing .mcp-coverage/ and TestResults artifacts |
sessionId | string | No | When set, removes only state files and directories scoped to this session. When omitted, removes the single-agent artifacts (TestResults-mcp/, .coverage-state, .coverage-prev.xml) whatever their age. |
maxAgeMinutes | int | No | When sessionId is omitted, also removes other sessions' artifacts older than this many minutes. Default 120. |
Protocol details: annotations, errors, instructions, progress
- 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_codeandget_coverage_diffwrite files but are not destructive. Onlycleanup_sessionisdestructiveHint: true. Onlyrun_tests_with_coverageisopenWorldHint: true, since a restore can reach NuGet. - Errors. A tool error comes back as
{"error": "...", "errorType": "..."}text in a result flaggedisError: true, so clients show it as a failed call.errorTypeis a stable name to branch on (fileNotFound,pathNotAllowed,testsFailed,buildError,duplicateMember, ...). - Server instructions. The
initializeresult 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_coveragereports milestones whiledotnet testruns: restore, each project built, tests started, the result line.
Configuration
All settings are environment variables, set in the client's MCP configuration (see Install).
| Variable | Default | Effect |
|---|---|---|
COVERAGE_MCP_ALLOWED_ROOT | unset | Recommended. Restricts every tool's filesystem access to this folder. A path outside it is rejected with pathNotAllowed. When unset, the server logs a warning once and accepts any path. |
COVERAGE_MCP_DOTNET_TEST_TIMEOUT_MS | 600000 (10 min) | Longest a whole dotnet test run may take before it is stopped (timeout). |
COVERAGE_MCP_HANG_TIMEOUT_SECONDS | 30 | Longest 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. |
Requirements
- .NET 10 SDK or later to run the tool. The projects it tests do not have to be .NET 10:
net8.0andnet9.0test projects work, including in a repository whoseglobal.jsonpins an older SDK, and so do test projects with several target frameworks (the end-to-end tests run one targetingnet8.0;net10.0). As with anydotnet 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, plusMicrosoft.Testing.Extensions.TrxReportfor per-failure details. MTP is used when the repository'sglobal.jsonsets"test": { "runner": "Microsoft.Testing.Platform" }, which the .NET 10 SDK requires for MTP projects anyway.get_test_environmentreports what a project has and what is missing. - An MCP client such as Claude Code, Claude Desktop, Gemini CLI, Cursor or VS Code.
How it works
The client starts the server as a console process and calls its tools over stdio.
AI Client <--stdio/MCP--> dotnet-coverage-mcp <--process--> dotnet test
Several agents at once: sessionId
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_coveragecreatesTestResults-{hash}/per session, so one agent can't delete another's XML mid-parse. - Scoped state files: coverage state is written to
.mcp-coverage/.coverage-state-{hash}, so each session resolves to its own XML. - Scoped baselines:
get_coverage_diffstores baselines as.coverage-prev-{hash}.xmlper session. - Atomic writes: all file writes (state files and test code) use write-to-temp-then-rename, so a race or a crash can't leave a half-written file.
Limitation: build outputs are not session-scoped.
sessionIdisolates coverage artifacts, not the .NET build.dotnet testcompiles the target project into its sharedobj/andbin/, so two agents runningrun_tests_with_coverageagainst the same test project at the same time collide on those outputs. The run that loses returnsprojectBusy(its build hitCS2012/MSB3027, "being used by another process"), notbuildError, 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.
Without sessionId, tools use shared defaults, which is right for a single agent.
State files in .mcp-coverage/
All state files are written to a .mcp-coverage/ folder inside the working directory. Add .mcp-coverage/ to the target repository's .gitignore.
| File | Purpose |
|---|---|
.coverage-state | Default Cobertura XML path for single-agent use |
.coverage-state-{hash} | Session-scoped Cobertura XML path |
.coverage-prev.xml | Default coverage baseline for diff |
.coverage-prev-{hash}.xml | Session-scoped coverage baseline |
Dependencies
| Package | Version | Purpose |
|---|---|---|
Microsoft.Extensions.Hosting | 10.0.15 | DI and hosting |
ModelContextProtocol | 2.4.0 | MCP server framework |
Microsoft.CodeAnalysis.CSharp | 5.12.0 | Roslyn AST for safe code insertion and accurate method counting (~15MB) |
Plugin: skills and agent
The plugin/ folder holds Claude Code skills and an agent for guided coverage work. They support xUnit, NUnit and MSTest, with framework-agnostic reference docs in references/unit.md and references/integration.md.
What's in the plugin
| Skill / agent | For |
|---|---|
improve-test-coverage | The full loop: run, find gaps, write tests, repeat until every file reaches 80%. Unit tests first by default, or integration tests first with testStrategy: integration-first. |
analyze-coverage-gaps | Find uncovered branches and compare diffs. |
run-coverage | Run tests and view the coverage report. |
scaffold-test-files | Create test folders and files that mirror the source structure. |
test-coverage (agent) | Scaffolds test projects and files, then improves coverage by routing to the skills above. |
plugin/
├── plugin.json
├── agents/
│ └── test-coverage.agent.md
└── skills/
├── scaffold-test-files/
├── run-coverage/
├── analyze-coverage-gaps/
└── improve-test-coverage/
Security
The server runs as a local stdio process and checks every path argument against COVERAGE_MCP_ALLOWED_ROOT. 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. Maintainers: the release process is in RELEASING.md.