I use Claude Code every day. After about a year of trying plugins, skills and MCP servers, I noticed two things.
First, my sessions were expensive before I typed anything. The first reply of a fresh session cost about 55k tokens. All of it was context loaded at start-up: plugin and skill descriptions, MCP tool schemas, hook output, CLAUDE.md files. A lot of it was stuff I had forgotten I'd installed: duplicates, MCP servers that never connected, and tools I hadn't called in a month.
Second, my machine was filling up with leftovers. Run ps aux | grep mcp after a day of work and you may be surprised. When an agent exits, its stdio MCP servers get re-parented to launchd or init and keep running. This is a known issue (#1935, #33947); one report counts 96 orphaned processes after a single day. On top of that there were temp directories, interrupted plugin installs, old plugin versions, transcripts, and git worktrees that agents created for parallel work and never removed.
So I built Agent GC. This post is about how it decides what is garbage, because that turned out to be the interesting part.
Two problems, two treatments
The context problem and the leftovers problem look similar, but they need opposite answers.
- Context sources are the user's choices. A plugin that costs 8k tokens may be worth it to you. So Agent GC measures and explains, and gives you a reversible switch, but it never turns anything off by itself.
- Leftovers can be collected automatically, but only if the collector is provably conservative. A worktree with uncommitted changes is not garbage, however old it looks.
Measuring the start cost (instead of guessing)
You can't estimate the start cost reliably by adding up file sizes. Luckily you don't have to: the agent already records it. The first assistant message of every session in the transcripts contains the token usage the model received:
input_tokens + cache_creation_input_tokens + cache_read_input_tokens
Agent GC takes the median over the last 7 days of interactive sessions (headless runs started by other tools are excluded) and shows a weekly trend. Then it breaks the total down by source: each plugin, skill, MCP server (measured by actually calling initialize and tools/list), hook and CLAUDE.md import, heaviest first. It also flags them: duplicate, not connecting, unused for 30 days, loaded while disabled.
Every switch can be undone. Plugins and skills are turned off through the agent's own settings. MCP servers and hooks are moved to a stash, and the config file is edited atomically with a backup, preserving symlinks and key order.
The leftovers: borrowing from runtime garbage collectors
For leftovers I deliberately copied the structure of a tracing garbage collector, the kind that lives inside the JVM or Go. The analogy fits surprisingly well:
| Runtime GC | Agent GC |
|---|---|
| Roots | Running processes and their working directories, running agents' start times, paths referenced by config files, git repositories |
| Heap objects | Temp dirs, transcripts, plugin versions, worktrees, orphaned MCP helpers |
| Mark | One function that decides "is this dead" |
| Write barrier | Re-check every fact right before acting |
| Generations | Young garbage every 15 min, old garbage daily |
| Free | Quarantine. Nothing is deleted immediately |
That last row is the main departure. In a language runtime, a wrong free corrupts a few bytes of heap. Here, a wrong free deletes someone's work.
One decision point
Each kind of garbage is a heap. A heap only lists its objects and reports facts about them: when it was last touched, what it's anchored to (a path, a config key, a process identity), and whether it looks like garbage on its own. A heap never decides to remove anything.
The decision lives in exactly one function, mark. An object is dead only if every rule holds:
-
It looks like garbage on its own. "Unknown" counts as alive. If
gitfails or a config file can't be read, nothing is touched. - Nothing reachable points to it. A live process working inside the path, or a config file referencing it, keeps it alive.
-
It has been idle long enough. Each heap has its own threshold: 3 days for temp dirs, the agent's own
cleanupPeriodDaysfor transcripts. - No running agent could still be using it. More on this below.
- It has looked dead for long enough. Some heaps require an object to stay dead for a while before it counts.
Putting all of this in one place means a safety rule can't be forgotten in one of ten collectors.
The rule that does the most work: the agent epoch
Rule 4 is borrowed from snapshot-at-the-beginning marking. If any running agent started before an object went quiet, the object stays alive, because that agent may have started using it and just hasn't touched it lately.
This single rule covers three cases that would otherwise need special code:
- the temp directory of a session that's still running;
- a transcript that a running session may still append to;
- a plugin version that an agent loaded before you updated the plugin.
It already paid off during testing. On my machine, a real Claude Code session had been running for five days. Its five-day-old temp directory was correctly kept alive. To see it collected in the test, I had to age the directory to 60 days.
The barrier: agents don't stop while you collect
Between deciding and acting, a worktree can get a new commit, a temp directory can get a cloned repo, and a pid can be reused by a different process. So right before each action, the heap re-reads the object's facts, the process table is refreshed, and mark runs again. If anything changed, the object is skipped. Ending up alive is not an error.
Processes are identified by pid plus start time, never pid alone, which protects against pid reuse.
Orphans: identity, not names
Most existing MCP cleanup scripts match by name: anything with mcp in its command line, re-parented to init. That also catches your own detached servers.
Agent GC is deliberately narrower. A process counts as an orphaned helper only if:
- it was re-parented to
init/launchd/systemd, and - Agent GC saw it as a direct child of an agent, or its command line exactly matches an MCP server in your config.
Every signal goes through a single guard that refuses pid 0, pid 1, process groups, and Agent GC's own process tree.
Quarantine instead of delete
- Files and directories are renamed into a graveyard with a manifest. A rename on the same file system is instant and never leaves a half-moved tree. Temp files stay for a day, everything else for a week. Under disk pressure the graveyard shrinks, and it never takes more than 10% of free space.
-
Worktrees are locked with
git worktree lockbefore they move, so git's ownprunedoesn't destroy the record. A restored worktree comes back whole. -
Processes are paused with
SIGSTOP, not killed. For an hour you can resume one, and then it's marked spared and never taken again. Only after that hour, and only if it's still the same process and still stopped, does it getSIGTERMand eventuallySIGKILL.
The trade-off is that disk space is freed later. That seemed like the right price.
Live mode: event-driven, not cron
A 15-minute timer means orphaned MCP servers keep running for up to 15 minutes. Live mode reacts to agent exits instead. It uses kqueue NOTE_EXIT on macOS and pidfd on Linux. When an agent exits, the loop waits 2 seconds for its helpers to be re-parented, then runs a young collection. The orphans are suspended seconds after their agent is gone.
Between events the loop doesn't poll. It asks mark when each object stops being alive purely because of time (for example last_touch + min_idle), and sleeps until the earliest such deadline. File system events (FSEvents/inotify) trigger a recalculation. When idle, the daemon uses about 0% CPU and 25 MB of RAM.
What it deliberately doesn't do
- No agent memory. Deleting a memory can't be undone, and its value can't be judged by a rule.
- No automatic context changes. It measures and suggests; you decide.
-
No
node_modulesor build caches. Other tools do that well. - Nothing leaves your machine. No telemetry, no network calls.
Try it
It's open source (MIT), written in Rust, with a small tray app built on Tauri. It works with Claude Code and Codex CLI on macOS and Linux.
brew install --cask dimitreee/tap/agent-gc-app # menu bar app, macOS
brew install dimitreee/tap/agent-gc # CLI
npx agent-gc-cli # or via npm
- Repo: github.com/Dimitreee/agent_gc
- Full design write-up, with the safety argument, test setup and comparison to similar tools: how-it-works.md
I'd love to hear what your session start costs, and which leftovers it misses on your machine. Cursor and Gemini CLI support is next.


Top comments (0)