dotnet-diagnostics
AGENTS.md4 starsChanged 57 days agoMITView on GitHub
Operating guide for AI coding agents (Copilot CLI, Codex, Claude Code, Cursor, etc.) working on this repository. Humans benefit too. dotnet-diagnostics-mcp is an MCP server that lets an LLM perform on-demand performance diagnostics on running .NET applications — locally or in a Kubernetes sidecar. Target processes on .NET 8/9/10 are officially supported and validated in CI (see docs/runtime-version-compat-matrix.md); .NET 6/7 targets are expected to work but are EOL and not CI-covered. Normal EventPipe and ClrMD diagnostics require no target code…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- .github/copilot-instructions.mdCopilot instructions
The file
We split this AGENTS.md into the rules it gives an agent
11 rules. About 0 are common, 5 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 43
All commands are run from the repo root.
- Very specific: line 81
Do not put the if: on the job (or use paths-ignore at the workflow level): a *skipped* required job never reports its context and deadlocks …
- Very specific: line 159
When any of the above bites, the diagnostic signature is: gh exits 0, no URL on stdout, no resource on the server.
- Very specific: line 173
Always give live tests ≥6s of duration for counters with intervalSeconds=1.
- Distinctive: line 192
Keep deadline, cap, and event-loss failures explicit.
- Distinctive: line 251
Follow the "split collector, unified drilldown" pattern: separate collectors per backend (e.g.
- Distinctive: line 262
All open work has a GitHub issue.
- Distinctive: line 266
When picking up an issue:
- Very specific: line 270
Build + run tests: before and after — dotnet build and dotnet test from the repo root.
- Very specific: line 281
Mandatory code review before flipping a PR out of draft: Use the task tool with agent_type: "code-review" against the staged / branch diff …
- Very specific: line 304
Worktree etiquette for parallel work: Create the branch on the remote first (git worktree add -b <branch> /tmp/<dir> origin/main) so the …
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
Operating guide for AI coding agents (Copilot CLI, Codex, Claude Code, Cursor, etc.) working on this repository. Humans benefit too.
What this project is
dotnet-diagnostics-mcp is an MCP server that lets an LLM perform on-demand performance diagnostics on running .NET applications — locally or in a Kubernetes sidecar. Target processes on .NET 8/9/10 are officially supported and validated in CI (see docs/runtime-version-compat-matrix.md); .NET 6/7 targets are expected to work but are EOL and not CI-covered. Normal EventPipe and ClrMD diagnostics require no target code changes or prior instrumentation. The explicit exception is collect_sample(kind="method-params"): an opt-in, privileged, security-gated dynamic profiler attach that temporarily instruments an allowlist of methods, and requires the target to be .NET 8+.
The server attaches to the .NET runtime diagnostic IPC socket and exposes a full 17-tool MCP surface: 13 tools by default plus 3 Kubernetes-orchestrator tools and discover_azure when their configuration gates are enabled. It supports either Streamable HTTP (default, with bearer-token auth — designed for sidecar / shared-deploy) or stdio (--stdio, recommended for local dev — the MCP client owns the process lifecycle, no daemon or bearer token; see issue #74).
The repo also ships dotnet-diagnostics-cli (src/DotnetDiagnostics.Cli, assembly name dotnet-diagnostics), a Core-only standalone CLI for humans / scripts / CI — one-shot sub-commands plus a stateful session REPL, no HTTP, no bearer, no daemon — and dotnet-diagnostics-benchmarkdotnet, an in-process BenchmarkDotNet diagnoser. All three packages publish from the same release tag. The CLI references Core only (asserted by NoServerReferenceTests); document it in docs/cli-reference.md, not the MCP tool reference.
Status: Phases 1–15 are complete. Active work is tracked in issue #551, Phase 16 — Roadmap.
Repository layout
src/
DotnetDiagnostics.Core/ — IPC + EventPipe primitives, no MCP knowledge
DotnetDiagnostics.Mcp/ — MCP tools, HTTP transport, bearer auth
DotnetDiagnostics.Cli/ — standalone CLI (dotnet-diagnostics-cli), Core only, one-shot + session REPL
DotnetDiagnostics.BenchmarkDotNet/ — in-process BenchmarkDotNet diagnoser built on Core
tests/
DotnetDiagnostics.Core.Tests/ — live process tests (spawn sample, attach, assert)
DotnetDiagnostics.Mcp.IntegrationTests/ — HTTP + MCP protocol tests
DotnetDiagnostics.Cli.Tests/ — CLI parsing, command, and session-REPL tests
DotnetDiagnostics.BenchmarkDotNet.Tests/ — diagnoser validation + documentation parity
samples/
CoreClrSample/ — minimal ASP.NET API used by Core tests
NativeAotSample/ — used to validate capability detection
BadCodeSample/ — 7 anti-pattern endpoints to exercise the LLM diagnostic loop
deploy/
Dockerfile — multi-stage publish; copies .editorconfig for analyzers
k8s/sample-sidecar.yaml — reference K8s topology
docs/
README.md, tool-reference.md, cli-reference.md, investigation-playbooks.md,
bad-code-scenarios.md, local-docker-sidecar.md, client-setup.md,
resource-boundedness.md, hotpaths/ (CPU/allocation hotpath profiling per collector)Build, test, run
All commands are run from the repo root.
# Build everything
dotnet build DotnetDiagnostics.slnx -c Release
# Run all tests (Core tests spawn a live sample process; require .NET 10 SDK on PATH)
dotnet test DotnetDiagnostics.slnx -c Release --no-build
# Run only the integration tests
dotnet test tests/DotnetDiagnostics.Mcp.IntegrationTests/ -c Release --no-build
# Run the MCP server locally (launch profile listens on http://localhost:5130)
dotnet run --project src/DotnetDiagnostics.Mcp -c Release
# Run the standalone CLI (Core-only; one-shot or `session` REPL)
dotnet run --project src/DotnetDiagnostics.Cli -c Release -- processes
dotnet run --project src/DotnetDiagnostics.Cli -c Release -- session
# Run a single live test
dotnet test tests/DotnetDiagnostics.Core.Tests/ -c Release --no-build \
--filter FullyQualifiedName~Counters_ReturnsSystemRuntimeMetricsThe orchestrator's end-to-end kind acceptance test is gated by
Category=KindIntegration and runs only when the
.github/workflows/kind-integration.yml job (or the manual reproduction
documented in docs/central-orchestrator-design.md)
sets DOTNET_DBG_MCP_KIND_TEST=1 plus its companion env vars. The standard
ci.yml server-integration leg filters Category!=KindIntegration so it
never appears as a misleading "Passed" no-op there.
CI docs-only fast path — gate STEPS, never the job. Branch protection
requires four contexts: Build & Test (ubuntu-latest), Build & Test
(windows-latest), Kind Integration (ubuntu-latest), Helm render smoke
(B5.5). A changes job (dorny/paths-filter, code = any non-*.md file
changed) lets docs-only PRs skip the expensive work — but each heavy job still
runs and gates its individual steps on needs.changes.outputs.code == 'true'.
Do not put the if: on the job (or use paths-ignore at the workflow
level): a skipped required job never reports its context and deadlocks the PR
in "Expected — Waiting" forever. A job whose needs succeeded but whose steps
all skip still reports success, which is what satisfies the required check.
The Kind workflow additionally caches Docker layers via type=gha; GHA cache is
branch-scoped (PRs read main's cache, write their own). Crash dumps upload only
on failure (if: ${{ failure() && … }}); TRX always.
In ci.yml, lightweight CLI, BenchmarkDotNet, and packaging checks run in
separate fast-test jobs alongside the serialized live-process suites, so their
results surface early. The existing Build & Test contexts aggregate both
groups; the full suite remains required. Test steps have explicit timeouts, and
evidence-verification and artifact-upload steps must still run after a test
failure or timeout.
On Windows, the five-minute inactivity watchdog requests full hang dumps as
well as crash dumps; failure uploads retain them for deadlock investigation.
Bearer token. The server reads MCP_BEARER_TOKEN from the environment. If unset, it
generates an ephemeral 32-byte hex token at startup and logs it as a warning — there is no
hard-coded default. The local docker walkthroughs explicitly pass MCP_BEARER_TOKEN=dev-token.
SDK version. global.json pins 10.0.201 with rollForward: latestFeature. Use the
SDK from global.json, not whatever is on PATH outside this repo.
Warnings as errors. Directory.Build.props sets TreatWarningsAsErrors=true for source
projects (test projects opt out). Analyzer warnings (CA1711, CA1852, CA1861, etc.) will fail
the build — fix them, do not suppress them globally.
Central package management. Package versions live in Directory.Packages.props. Project
files reference packages without a Version attribute. Add new packages to the central props
first.
Local Docker sidecar (matches K8s topology)
See docs/local-docker-sidecar.md for the canonical CoreClrSample
walkthrough, and docs/bad-code-scenarios.md for the BadCodeSample
walkthrough used to exercise the LLM diagnostic loop. Both use network diagmcp-net,
publish the MCP server on 127.0.0.1:18887, and require --user 0 on the sidecar (see UID
note below). Do not invent ad-hoc names or ports — drift between repos and docs is the #1
source of wasted debugging time here.
Critical conventions you must respect
These are the easy-to-break things that have cost us debugging time before.
🔌 Diagnostic socket UID — same UID, every time
The .NET diagnostic IPC socket at /tmp/dotnet-diagnostic-<pid> inherits the target app's UID. The MCP sidecar must run with the same UID or it gets ServerNotAvailableException: Permission denied.
- Local dev:
docker run --user 0 …on the sidecar (target runs as root). - K8s: pod-level
securityContextwith matchingrunAsUser+runAsGroup+fsGroup. Seedeploy/k8s/sample-sidecar.yaml.
🪪 CAP_SYS_PTRACE for live memory readers — UID alone is not enough on Linux
inspect_process(view="runtime-config"), collect_thread_snapshot, inspect_heap(source="live"), live capture_method_bytes, get_bytes(kind="module"), and the opt-in enrichment in collect_sample(kind="cpu", resolveMethodInstantiations=true) attach via ptrace(2). On Linux with kernel.yama.ptrace_scope=1 (Debian/Ubuntu/WSL default) same-UID peer attach is blocked. collect_process_dump instead writes through diagnostic IPC and does not require Linux CAP_SYS_PTRACE, although MCP authorization still requires its separate dump-write + ptrace bearer scopes and human approval.
- Docker (local):
--cap-add SYS_PTRACEon the sidecar container. - K8s:
capabilities.add: ["SYS_PTRACE"]on the sidecar container'ssecurityContext. Seedeploy/k8s/sample-sidecar.yaml. - Bare host, isolated personal-development only:
sudo sysctl -w kernel.yama.ptrace_scope=0relaxes a host-wide security boundary for all same-UID processes. Never use it on a shared or production host; prefer EventPipe, offline dump analysis, or a sidecar-scoped capability. Seedocs/consumer-install.md§ 1.5.
Failure usually surfaces as a structured PermissionDenied envelope (see #32); inspect_process(view="runtime-config") is best-effort and instead records the failed ClrMD attach in notes[]. EventPipe-based tools do not need CAP_SYS_PTRACE unless a caller explicitly enables a ClrMD enrichment such as resolveMethodInstantiations=true.
🐧 WSL2 perf quirks (host-side off-CPU sampling)
On WSL2 the bundled /usr/bin/perf wrapper matches $(uname -r) (e.g. 6.6.114.1-microsoft) against /usr/lib/linux-tools/<ver>/perf and fails when no exact match exists. The fix is to invoke the installed binary directly — e.g. /usr/lib/linux-tools/6.8.0-117-generic/perf — by exporting PERF= or by symlinking. Also note that kernel.perf_event_paranoid=2 (the WSL default) blocks sched:sched_switch tracepoints required by collect_sample(kind="off_cpu") on the host; lower it (sudo sysctl -w kernel.perf_event_paranoid=-1) or run the workload inside a container with --cap-add PERFMON, which is the topology the docker / K8s sidecar recipes already use.
🐚 Shell escapes when driving gh / git
Three pitfalls that have eaten hours of debugging in past sessions:
!in titles:gh issue create --title "MEX !deadlock equivalent"silently fails because bash history expansion runs inside double quotes. The command exits 0, nothing is created, no error printed. Use single-quoted titles for anything containing!, orset +Hin the same shell first.- Inline
--body "..."/-m "..."with markdown (backticks,$,!, heredoc-like patterns) hangs or silently truncates. Always use--body-file <path>/-F <path>for non-trivial messages. - Don't pipe
gh ... createoutput (| tail,| head,2>&1 | …). On non-success pathsghproduces no URL and the pipe masks the failure. Verify withgh pr view/gh issue list --searchafter every create.
When any of the above bites, the diagnostic signature is: gh exits 0, no URL on stdout, no resource on the server. Always confirm the resource exists before claiming the step completed.
🐳 .dockerignore must re-include .editorconfig
Our .dockerignore starts with * (deny-all) and re-includes specific paths. If you remove the !.editorconfig line, the publish breaks with CA1848/CA1873 errors because the analyzer suppressions live in .editorconfig. Same applies to !samples/ for sample images.
📝 Documentation is written in English
All committed docs (docs/**, README.md, AGENTS.md, XML-doc / [Description] strings, code comments) are English. The audience for the tool reference and tool descriptions is the LLM / MCP client. Do not introduce Portuguese (or any non-English) prose into committed files, even when the working conversation is in another language — translate before committing. If you find an existing non-English passage, normalize it to English as part of the change you are making.
⏱️ EventPipe session startup is not instant
EventPipe sessions take ~500ms–1s to fully start. Then EventCounters payloads arrive at EventCounterIntervalSec boundaries.
- Always give live tests ≥6s of
durationfor counters withintervalSeconds=1. - For exception/GC collection, start the session BEFORE the load that generates events.
# WRONG — exceptions collector starts after curl loop finishes
curl … & sleep 0; dotnet … collect_events(kind="exceptions")
# RIGHT — schedule load to happen during the collection window
( sleep 2; curl … ) &
dotnet … collect_events(kind="exceptions") # synchronous🧪 Live tests are real
tests/DotnetDiagnostics.Core.Tests/LiveCoreClrProcessTests.cs spawns the CoreClrSample webapi by invoking its published DLL directly (dotnet …/CoreClrSample.dll) and attaches to the resulting PID. The fixture deliberately avoids dotnet run, which creates a wrapper host process whose PID is not the application. Required: .NET 10 SDK on PATH, ability to bind to 127.0.0.1:0, and ~10s of runtime. CI runs both Linux and Windows runners.
Activity-based live tests must observe events from their own collection session before starting the target workload, rather than assume a fixed startup delay. GC progress witnesses span the EventPipe arm/stop acknowledgments as well as the collection itself; their deadline and sample cap must cover that whole lifecycle. Keep deadline, cap, and event-loss failures explicit.
The Core test assembly also has a private geometry-fixture entry point. The
strict inventory cases run in fresh child processes so the xUnit host's retained
heap does not consume their absolute harness RSS budget. Keep the executable
test-project setting; normal discovery still uses dotnet test. Process-wide
descriptor tests use an exclusive collection. Do not relax monitor limits to
accommodate unrelated tests.
💥 Linux host-crash flake (issues #147 / #685 / dotnet/runtime#128525) — historical
The xunit host used to segfault on ubuntu-latest under full-suite load — a native crash in a runtime thread, unified only by being the slowest tests in the serialized LiveProcess collection (see dotnet/runtime#128525 for the original mmap/munmap fault-address analysis). Root cause has since been identified in ClrMD. The two dedicated nightly reproduction workflows (linux-crash-repro-preload.yml's LD_PRELOAD mmap tracer and linux-crash-repro.yml's strace harness, plus their tools/linux-crash-repro/ helpers) are no longer needed and were retired in issue #857.
After upgrading to ClrMD 4.1.745802, the strict Linux gate completed 20 clean sequential Core/MCP rounds (#685). The ten formerly quarantined tests now use ordinary [Fact] attributes; no override environment variable is needed. Ordinary CI runs every suite once via scripts/ci-test.py: nonzero command exits, incomplete discovery/TRX inventories, failed/aborted run outcomes, and missing evidence fail the job without retries. scripts/clrmd-regression-tests.json preserves the historical required-Passed inventory for both ordinary CI and the optional revalidation gate. Legitimate unrelated platform skips and the intentional CrashGuard target crash remain allowed in ordinary CI. See docs/clrmd-linux-revalidation.md for evidence and limits; the concurrent aggregate-solution scenario in #879 is not established as resolved by sequential runs.
🧯 Resource-boundedness of long/high-volume captures
A capture must not scale unboundedly with duration or event volume — no OOM,
no hang, regardless of raw speed. Collectors enforce caps at the point of
insertion (inside the EventPipe callback), never by accumulating everything
and truncating at the end. Collectors surface a cap hit via an explicit
notes entry naming the constant and the drop/eviction count. Check
docs/resource-boundedness.md
for each collector's exact retention and reporting behavior. See that doc for
the full per-collector reference (caps, retention strategy, what's traded
away) from the audit in issues #604/#605/#606
(PRs #607–#614) — read it before adding a new bounded structure or extending
an existing one.
🔥 CPU/allocation hotpath profiling per collector
Complementary to the boundedness audit above: docs/hotpaths/README.md
profiles where CPU cycles and allocations actually go inside each collector's own code (not just
whether memory is bounded), via BenchmarkDotNet + EventPipeProfiler against real live sample
processes. From the audit in issue #616
(PRs #617–#619): almost every collector's exclusive CPU time is dominated by runtime wait/parking
frames, not avoidable managed work — no speculative micro-optimization was applied. Read it before
assuming a collector needs CPU tuning; add a new benchmark there instead of guessing at a hotpath.
🎯 One MCP tool per concept (17 tools)
Anthropic recommends ≤10 tools per LLM context. See
docs/research/mcp-tool-catalog-budget.md for the
measured context-window cost of the 13/17-tool surface (issue #791, refreshing #628). We have 17 tools: #213 consolidated
24 legacy aliases into 7 unified discriminator tools (inspect_process, collect_events, collect_sample,
query_snapshot, inspect_heap, list_orchestrator, get_bytes), discover_azure was added
alongside the cloud-integrations work (#16), plus 8 non-aliased tools
(collect_process_dump, collect_thread_snapshot, capture_method_bytes, start_investigation,
export_investigation_summary, compare_to_baseline, attach_to_pod, detach_from_pod), and
collect_batch (issue #665 Part C) — an explicit, acknowledged exception to the cap: a
new dedicated tool rather than a bolt-on parameter, because the cross-tool {tool, kind} fan-out
it needs (collect_sample kinds + collect_events kinds, concurrently, against one resolved
process) doesn't fit either existing tool's "one kind, one populated field" envelope contract. See
docs/design/ephemeral-process-capture-design.md Part C ("Rejected alternatives") for the full
comparison against the alsoCollect bolt-on and kind="batch" shapes that were considered first.
Don't add tools speculatively. New capabilities should either:
- Extend an existing tool with a parameter, or
- Be exposed as a Resource (
audience=["assistant"]) or Prompt, not a Tool, or - Follow the "split collector, unified drilldown" pattern: separate collectors per backend
(e.g.
inspect_heap(source="dump")vsinspect_heap(source="live")) register a singleHeapSnapshotArtifactin the sharedIDiagnosticHandleStore, and a singlequery_snapshot(handle, view, …)tool answers parameterized follow-up questions. This keeps the tool surface flat while letting the LLM ask narrowly-scoped questions without re-paying the collection cost.
The unified drilldown architecture originated in Phase 7 issues #8 mcp-drilldown
and #24 wave 1 heap drilldown.
Phase 16 — active roadmap
All open work has a GitHub issue. Read the active tracking issue first: #551 Phase 16 — Roadmap. It carries the current priority order and links to the research behind each gap. Don't inline that list here — it drifts.
How to contribute as an agent
When picking up an issue:
- Read the active tracking issue (#551) for current priorities and dependencies. Don't start blocked work.
- Read the linked research findings in the issue body before designing.
- Build + run tests before and after —
dotnet buildanddotnet testfrom the repo root. - Don't add tools without an issue — discuss first in the relevant
drilldownordiscoverabilityissue. - Keep PRs small and reference the issue (
Closes #N). - Don't commit secrets, dumps (
*.dmp), or.nettracefiles.
Agent workflow conventions
These are repo-wide meta-workflows that have proven to pay off here. They are declarative on purpose — the goal is to bias decisions, not to script every turn. Skip them when the task is genuinely trivial.
- Mandatory code review before flipping a PR out of draft. Use the
tasktool withagent_type: "code-review"against the staged / branch diff and address every real finding. Pick a reviewmodelthat differs from whichever model is driving the main implementation turn (e.g. review withgpt-5.6-solwhen implementing asclaude-sonnet-5, or vice versa) — don't hardcode a single review model regardless of which model wrote the code. Empirically this has caught a real bug on most non-trivial PRs in this repo — including several flake / race-condition regressions that the human + author-agent pair both missed. - Decompose-then-parallelise. Features here tend to land as several small,
independent PRs (one recent consolidation shipped as 13). When the work decomposes into ≥2
independent trails (different directories, different test surfaces, no
shared schema migration), prefer dispatching one background sub-agent per
trail over serialising them in the main loop (in Copilot CLI:
taskwithmode: "background"; other agent CLIs expose an equivalent). The main loop keeps coordination + code review; the sub-agents own implementation. - Pre-scope R&D items with a
researchorexploreagent first. For fuzzy / multi-week items (e.g. "NativeAOT heap walk", "new cloud provider recipe"), dispatch a sub-agent for survey + feasibility before drafting the plan. Saves the main context for actual design + execution. - Don't reach for a sub-agent when a single tool call would do. Simple lookups (one grep, one file read), pointed edits, and any interactive debugging stay in the main loop — sub-agent fidelity loss is not worth it.
- Worktree etiquette for parallel work. Create the branch on the remote
first (
git worktree add -b <branch> /tmp/<dir> origin/main) so the sub- agent operates on an isolated checkout. After merge,git worktree remove --force <path>beforegh pr merge --delete-branch(the latter cannot delete a local branch held by a worktree).
User- or task-scoped preferences ("for this PR don't run review", "I prefer option X") belong in the prompt, not here. Conventions in this section apply to every contributor and every agent on this repo.
Things deliberately not in scope
- Modifying target source or deployment — non-goal. Standard diagnostics work over the diagnostic socket; the explicitly requested method-parameter path may temporarily attach a profiler and ReJIT only its allowlisted methods.
- Persistent server-side investigation memory — investigation memory remains portable JSON the agent persists externally (see issue #10). Opt-in SQLite evidence packages are a separate, explicit persistence feature: ordinary reads are immutable, recovery creates a derived package, and the generic artifact reaper must never enter the managed
captures/namespace. Seedocs/design/durable-sqlite-storage-contract.md. - A web UI — this is an MCP server; the UI is whatever MCP client the human uses.
- Replacing dotnet-monitor — different goals.
dotnet-monitoris rule-based collection for ops; we are interactive diagnosis for an LLM. They complement each other.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

