Skip to content

Let AI agents drive DiskHound over a local MCP server - #5

Merged
huntharo merged 3 commits into
mainfrom
codex/diskhound-mcp-patterns-5e1b95
Oct 14, 2026
Merged

huntharo merged 3 commits into
mainfrom
codex/diskhound-mcp-patterns-5e1b95

Conversation

@huntharo

@huntharo huntharo commented Sep 25, 2026 •

Copy link
Copy Markdown
Owner

Upstream PR: tzarebczan#71 (draft)

Summary

DiskHound can now act as a local MCP server, so an AI agent such as Claude Code, Claude Desktop, or Codex can work alongside the user to find where space went. The agent reads scans, runs scans, and moves the DiskHound window to whatever it is looking at, so the user watches the investigation in the app instead of reading paths in a terminal.

  • Off by default. Turning it on starts a loopback-only server at http://127.0.0.1:51735/mcp. The old port, 51733, is PwrSuiteLab Control's.
  • Easy to find. An agent button is always in the header, the drive picker links to setup, and so do the app and tray menus.
  • Guided connection. Like PwrSuiteLab, the guide leads with Copy prompt for your agent, and each client (Claude Code, Claude Desktop, Codex, others) has a tab with its own prompt, so the agent sets itself up. Claude Desktop's chat can't run commands, so its tab has Add to Claude instead, which hands Claude an extension to install. A last step shows the connection live.
  • Approval. Every agent is approved in a sheet over the main window. The user picks one of four roles and can change or revoke it later in Settings.
  • Removing files. An agent can ask to move items to the Trash (Cleanup Operator) or delete them permanently (Cleanup Admin), and the user confirms every request. A session never sees tools its role doesn't grant. Calling one anyway is refused before it runs, logged to agent-security.log, and shown in the app.
  • Clients. Claude Code and Claude Desktop use a bundled Rust stdio helper; Claude Desktop runs it from an extension (an MCP Bundle). Codex speaks HTTP + OAuth directly.
  • Skills. Two cleanup procedures ship as MCP skills (SEP-2640), with prompt fallbacks and a diskhound_read_skill tool for clients that pass on only tools (Claude Desktop). They cover space that deleting files doesn't free: APFS clones and Time Machine local snapshots on macOS, shadow copies and .vhdx disks on Windows, and hardlinks and btrfs/ZFS snapshots on Linux.
  • What removal really frees. diskhound_measure_removal measures what removing a set of files and folders together frees, on disk now. It counts APFS clones and hardlinks once, including copies outside the set and outside any scan. The call blocks until the walk is done. If the client stops waiting first, DiskHound finishes the walk and answers the same call from memory for 5 minutes. Not offered on Windows.

User docs are in docs/mcp.md. The design review (numbered turns, as-built specimens, options, a prototype and the build list) is in the Claude Design project as "AI Agents (MCP) - Connect & Manage".

Finding it

The header's agent button is always there. With agents off, its popover explains the feature and offers Set up…. The drive picker adds "Using Claude or Codex? Connect an AI agent ›". The app menu has Connect an AI Agent… and the tray has AI Agents….

Header button, popover, and drive picker link

With agents on, a green dot means DiskHound is listening, and an amber badge counts sign-ins waiting for the user. For ten minutes after an agent acts, the button becomes a pill naming it: blue while it works, red when a call failed or was blocked. In windows 1,100 px wide or less, the pill shows only its dot; the name stays in its tooltip. The popover lists each session, its last action and role, waiting sign-ins with Review, and blocked requests today.

Popover with a connected session

Connecting

Set up… lands on the connect guide. With agents off, its last step has a Turn on button, since the toggle is scrolled out of view. The last step then waits live and shows the connection as soon as the agent signs in. Tabs get a green dot for clients that are connected. The guide folds away once something is connected.

The prompts follow PwrSuiteLab's wording: "Add diskhound to my Claude Code user configuration using the stdio executable "…", with no arguments. Preserve my other MCP servers, then help me connect and approve access in DiskHound." Codex's and other clients' prompts use the HTTP endpoint with OAuth. DiskHound never writes another app's configuration. The CLI command is behind a Show button for doing it by hand.

Claude Desktop is different: its chat can't run a command, and claude mcp add only reaches Claude Code (including Code sessions in the Claude app). Claude Desktop installs local servers from MCP Bundles, so Add to Claude zips DiskHound's own helper with a manifest into DiskHound.mcpb in temp and opens it. Claude shows its install dialog, and after Install it connects without a restart. The bundle uses the app's version, and passes --port when DiskHound isn't on the default. If Claude can't be opened, the tab says so and offers Show file. The extension serves the Claude app's chats and its Code sessions. Linux has no Claude Desktop, so the tab isn't shown there.

Claude Desktop reads an extension's tool list once, when it connects, and keeps it. It does re-fetch the list after tools/list_changed, but it never passes the new list on to chats. So for Claude Desktop the helper holds that first tools/list until the user decides, for up to 45 s (Claude gives up on a request after 60 s), and Claude gets the tools of the granted role. If Claude still ends up with an out-of-date list (the user answered late, or changed the role), diskhound_status tells the agent to have the user turn DiskHound off and on in Claude's Settings → Extensions, and the role-change toast says the same.

Each client now saves its own approval. The Keychain account is <origin>#<client>, with a lock file per client, so approving Claude Code never lets Claude Desktop in, and one client's pending approval doesn't block another's.

Connect guide with the setup prompts

Approving

The sheet is attached to the main window. It names the client (the helper maps clientInfo to Claude Desktop, Claude Code or Codex; Claude Desktop sends claude-ai, or local-agent-mode-<extension> from an extension) and the transport. Role cards show each role's permissions as chips, with destructive ones in red.

Approval sheet

Picking a role above the default says what it adds, in red for permanent delete, and scrolls that note into view above the buttons. If several requests arrive, they wait in line. A request whose client stopped waiting is marked, and only Deny is left. Loading the same authorize URL twice (Codex opens it in the browser and prints it too) reuses the request instead of queuing a second one.

Approval sheet with Cleanup Admin picked

Managing and revoking

Each session in Settings → AI Agents shows its client, transport, approval age, permission chips, last action and blocked count. From there the user can change the role, revoke the session, or forget revoked sessions. After a role change, the stdio helper sees the new permissions on its next call and sends tools/list_changed. An HTTP client picks up the change when it reconnects.

Sessions

Removing files, and what happens when an agent isn't allowed to

Role Tools that remove files
Disk Explorer, Cleanup Guide none
Cleanup Operator diskhound_move_to_trash
Cleanup Admin diskhound_move_to_trash, diskhound_delete_permanently

Both removal tools show a native confirmation that lists every item and its size. Cancel is the default button. Protected folders, drive roots, the home folder and its standard folders, and DiskHound itself are always refused, and the dialog says what it left out.

A tool the role doesn't grant is missing from the session's tools/list. A call to it anyway (a stale list, or a guess) is refused before any tool runs:

diskhound_delete_permanently isn't available to this DiskHound session (Cleanup Guide doesn't grant files.delete). Nothing was changed, and DiskHound logged the attempt. Ask the user to change this session's role in DiskHound → Settings → AI Agents if they want you to do this, then reload your tool list.

The user sees a red pill and a notification, and the attempt is listed under Blocked requests and Recent agent actions.

Blocked request in the header

Blocked requests and recent actions

Refusals are kept in agent-security.log (NDJSON, 0600), which Show file reveals. Identical refusals within a minute are counted instead of repeated. At most 60 lines an hour reach disk; after the first append, appends are at least 5 minutes apart; and the file rotates at 256 KB. An agent refused nonstop for a day therefore costs at most 288 appends and about 0.5 MB.

How it works

  • Server. Runs in the Electron main process: stateless Streamable HTTP, with one McpServer per POST bound to that request's token. Each server registers only the tools, and the showInApp arguments, that the session's role allows.
    • Every call re-checks the policy file, so a revoke or role change applies to the next call.
    • The response header DiskHound-Capabilities lets the stdio helper notice a role change.
  • Stdio helper (diskhound-mcp).
    • It answers initialize at once and asks for approval in the background, so a client's connect timeout can't cut the user's decision short. Until then it shows one tool, diskhound_status, which says approval is pending.
    • It asks the user only when a tool is called, or once the client has stayed connected for 1.5 s. A health check (claude mcp list) lists tools and hangs up, so it never opens a sheet.
    • If the client hangs up while the sheet is showing, the helper withdraws the request (POST /authorize/cancel) and the sheet closes.
    • Approvals are saved in Keychain, Credential Manager, or Secret Service, and --ephemeral saves nothing.
  • OAuth 2.1. Dynamic client registration for public clients only, PKCE S256, and a resource indicator pinned to the MCP URL. The browser never approves anything; the redirect is released only after the native sheet decides.
  • Request checks. The Host header must be exactly 127.0.0.1:<port>, and the peer and Origin must be loopback. /mcp is POST only, bodies are capped at 256 KB, a token can have at most 16 requests pending, and errors are always JSON.
  • Sizes. Agent answers and confirm dialogs use the app's size-unit setting (decimal by default on macOS), so the numbers match the window.
  • Lazy load. The MCP SDK and Express live in their own bundle, dist-electron/mcp/agentRuntime.cjs. It loads only when agents are first turned on. If it fails to load, Settings shows the error with Try again; it no longer shows "Off".
  • Measuring removal. The native scanner's --mode=measure-removal walks the given paths with dua-core and reads metadata only. On APFS it takes each file's clone id from getattrlistbulk, and the clone reference count and private size once per clone group. A group's shared blocks are freed only when the set removes at least as many clones as APFS counts; a hardlinked file only when every name is in the set. A clone that was rewritten after copying reports its own blocks, and the rest is uncertainBytes. Main runs one walk at a time, keeps up to 8 results for 5 minutes, and drops them after a removal.
  • Renderer. The header button and Settings share one snapshot, which main keeps current by pushing changes. Opening the popover, switching tabs, or following links asks main for nothing. The read budgets lock that at 0 IPC and 0 reads.

Testing

  • Unit. bun run typecheck is clean, and 1,161 tests pass (4 skipped). New since the last push:
    • diskhound_measure_removal: de-duplicated paths, ranking by what each frees alone, totals and summary, the not-APFS, uncertain and missing notes, the limit, a refused drive root or relative path, and no tool on Windows; a scaling case;
    • the measurement runner: one walk per set whatever the order, reuse within the TTL, a walk that keeps going when the agent stops waiting and answers the retry, failures not kept, one walk at a time, results dropped after a removal, dispose; and the scanner process with a stand-in (arguments, the error line, abort);
    • diskhound_read_skill lists the skills, returns a file's text (the same text resources/read serves), lists a folder, and errors on an unknown URI;
    • diskhound_dev_artifacts reports each tree's freesAlone, shared bytes and sharedWith when APFS clones were measured, a listed.freesTogether range, and a path hint for unmeasured trees;
    • the Claude extension: the zip round-trips with its file modes and CRCs, the manifest, .exe on Windows, a non-default port, and a missing helper;
    • the security log: coalescing, the hourly cap, 5-minute throttling, rotation, and reloading the higher count;
    • the setup prompts for each client, the port argument, and the by-hand commands;
    • tool filtering for each role;
    • hidden-tool refusal over HTTP, and a refusal after a role was lowered mid-session;
    • cancel, and authorize de-duplication;
    • size units.
  • I/O budgets.
    • securityLog.ioBudget.test.ts: one refusal is 1 append; a 20-path burst is 1 append; an hour of a looping agent is 3 appends; loading the log is 1 read.
    • renderer.agents.ioBudget.test.ts, on the real main process and preload: browsing the popover, tabs and links is 0 IPC and 0 reads. A blocked HTTP delete is 1 security-log append plus the crash.log line, pushed to the UI with 0 IPC. A role change or revoke is one atomic policy write each. Add to Claude reads the helper, the icon and (unpackaged) package.json, then makes 1 mkdir and 1 write of the ~0.7 MB bundle, on a click made about once per setup.
  • Scanner (Rust). 104 tests pass, 11 of them for measure mode: ordinary files, a clone group freed only with every clone, a group inside one path, a rewritten clone, a hardlink freed only with every name, a hardlinked clone counted once, nested paths, a tally scaling test (N vs 8N paths and files), and real folders, hardlinks and cp -c clones on disk.
  • Helper (Rust). 18 tests pass, including: Claude Desktop's first tools/list waits for the decision, a stale list or a role change adds the reconnect note to diskhound_status, each client gets its own lock, initialize answers at once, listing doesn't start approval, hanging up withdraws the request, a role change triggers list_changed, and client names. Clippy is clean.
  • E2E. The full Playwright suite passed on macOS (45 tests). New coverage:
    • Measure removal, with no scan: two worktrees share a file with each other and one shares a file with a store outside the set (APFS clones on macOS, hardlinks on Linux). The set's total frees both of the first file's copies and the unshared file, and holds the store's file back. Each tree's freesAlone, the nested and missing paths, and a second call in another order answered from the first walk;
    • Add to Claude: the bundle unpacks the way Claude installs it, and its helper is the app's. It connects as Claude Desktop and lists tools before the user approves, as Claude does; the list comes back with the role's tools, diskhound_read_skill returns the cleanup skill, and the guide's last step ticks (skipped on Linux);
    • only Cleanup Admin can delete permanently: an Operator's call is refused and logged to the file, and Admin's delete goes through the confirm dialog;
    • a Guide doesn't list the Trash tool and gets a notification when it calls it anyway;
    • the popover leads to Settings;
    • the stdio sign-in as Claude Code, and a role raise that reloads the helper's tools;
    • a denied connection answers on the next call;
    • hanging up closes the sheet.
  • Hands-on, dev build, fresh profile. I drove the renderer over CDP; native dialogs couldn't be clicked there.
    • The first-run path: header button → popover → Set up… → Turn on → client tabs.
    • A scan of a small sandbox folder.
    • Codex, Claude Code (via the helper) and Claude Desktop (via the helper) sign-ins, with role changes.
  • Real clients.
    • Codex 0.153.4. codex mcp login diskhound asked for all five scopes. I approved it in the sheet as Cleanup Operator. codex exec then answered "what's using the most space" through diskhound_status and diskhound_list_folder, while the window followed it to the folder.
    • Asked to delete permanently, Codex said its session can only use the Trash. It had no delete tool, so nothing was sent and the file stayed.
    • Claude Code 2.1.278. It accepts the Settings command, and claude mcp list reports ✔ Connected without opening a sheet. Its headless prompt runs aren't available on this machine, so tool calls went through the helper with clientInfo claude-code.
    • Claude Desktop 2.16120.0. Opening a prototype bundle showed Claude's install dialog. After Install, Claude connected at once with no restart, DiskHound's sheet asked for approval, and Claude listed the tools again after approval. Claude named the connection local-agent-mode-DiskHound, which DiskHound showed raw and didn't match to the guide; that's fixed here.
    • That first install listed only diskhound_status: Claude listed tools before the approval and never took the new list into chats. After a reinstall, the helper found its saved approval, and Claude announced all 16 tools, which a new Code session used. That's why the helper now holds the first list.
    • With this build (cf3d57b): I revoked the old session, clicked Add to Claude and installed. Claude connected, the helper held its tool list, and the approval (as Claude Desktop, Cleanup Admin) landed in the same second Claude reported Connected to DiskHound (16 tools). A new chat asked what's using the most space and started a scan through DiskHound.
    • A Code session in the Claude app, asked for the stale worktrees whose removal together frees the most, couldn't get there through DiskHound. resources/read failed with "does not support resources": Claude passes an extension's tools on, not its resources. Dev Artifacts found 1 of about 530 worktrees, and no tool says what removing a set frees. The agent read the scan index and asked APFS for clone IDs itself. The pushes since add diskhound_read_skill, the freed-space fields and diskhound_measure_removal; worktree detection is a follow-up.
    • Measure mode on that question, release scanner, run directly: all 544 Codex and Claude worktrees on this Mac, 13.3M files, took 88 s (385 MB peak RSS). They take 578 GB by size; removing them all frees 175.7 GB. 7.1 GB stays in use through clones in the bun and pnpm caches, up to 0.9 GB more might come back from rewritten clones, and the rest is the same blocks counted more than once. 88 s is past Codex's default 60 s tool timeout, which is the case the kept result is for.
    • macOS asked for Keychain access again after the reinstall. The dev helper isn't signed, so each new build is a new app to the Keychain. A signed release helper keeps the same identity across updates, but I haven't confirmed that with a signed build.

Notes

  • SDK 1.30 rejects a tools/call or prompts/get that omits arguments. The spec makes it optional, and rmcp clients leave it out, so the HTTP layer defaults it to {}. A test pins the SDK behavior, so the shim can go after an upgrade.
  • DISKHOUND_AGENT_PORT moves the server off 51735. The E2E fixture gives each launch a free port with it.
  • Not in this PR (tracked separately):

@huntharo
huntharo force-pushed the codex/diskhound-mcp-patterns-5e1b95 branch 14 times, most recently from 5069e2b to b8c892a Compare October 1, 2026 16:17
@huntharo
huntharo force-pushed the codex/diskhound-mcp-patterns-5e1b95 branch 2 times, most recently from 2b9e6e4 to 880eb40 Compare October 13, 2026 03:21
@huntharo
huntharo force-pushed the codex/diskhound-mcp-patterns-5e1b95 branch from 880eb40 to 232797d Compare October 13, 2026 03:35
Settings → AI Agents turns on a loopback-only MCP server
(http://127.0.0.1:51733/mcp) so Claude Code, Codex, or any MCP client
can read scans, run scans, and steer the window while it helps the
user free up space. The window follows the agent, and a header pill
plus a Settings feed show what each agent did.

- OAuth 2.1 with dynamic client registration, PKCE, and a resource
  indicator. Approval happens only in a native DiskHound window,
  where the user names the session and picks a role (Disk Explorer,
  Cleanup Guide, Cleanup Operator). Tokens are stored hashed; every
  tool call re-reads the policy, so revokes and role changes apply
  on the next call.
- Host, peer, and Origin checks block DNS rebinding and cross-site
  requests. The SDK and Express load from their own bundle only when
  the feature is first turned on.
- 15 tools with MCP annotations and structured results. The only
  destructive one asks the user to move items to the Trash / Recycle
  Bin in a native dialog; paths are resolved on disk before the
  protected-folder check, and home, standard folders, drive roots,
  and DiskHound itself are refused.
- Scan comparisons carry the Changes tab's caveats when two scans
  counted sizes, hardlinks, or the macOS Data volume differently, so
  an agent doesn't read an accounting change as freed space.
- Two cleanup skills (free up space, investigate growth) served as
  SEP-2640 skill:// resources plus prompt fallbacks, with per-OS notes
  on space deleting doesn't free: APFS clones and Time Machine local
  snapshots, shadow copies and .vhdx disks, hardlinks and btrfs/ZFS
  snapshots.
- The Folders tab now marks trashed folders until the next scan.

Protected folders from Settings apply to agents too: they are checked
on the requested path, the resolved path, and again after the user
confirms, since Settings can change while the dialog is open. Folder
listings report the real folder count when the result is capped, and
duplicate groups report what removing each copy frees, clones and
hardlinks included.

Three E2E specs drive the built app the way Claude Code does: register,
/authorize, the real approval window, then MCP tool calls. They cover
the window following an agent, the Operator-only Trash with the user's
Cancel and Move, the home-folder refusal, Deny, restart, and Revoke.
DISKHOUND_AGENT_PORT moves the server off 51733, and the fixture gives
each launch a free port, so a run never collides with a DiskHound the
developer has open. The Trash confirmation and shell.trashItem are
stubbed in main, as the folder picker already is.

Session and token saves, the activity feed and tool calls have I/O
budgets, and the tool handlers have operation-count scaling tests.

Docs: docs/mcp.md.
diskhound-mcp is a small Rust helper shipped in resources/native. A
client that only launches stdio servers runs it with no arguments; it
bridges stdio to DiskHound's loopback HTTP endpoint, signs in with
OAuth on the client's behalf, and keeps the token in the OS credential
store, so later launches reuse the user's approval. DiskHound still
owns consent and the tools.

CI builds and tests it on all three OSes, and the release workflow
builds it per target (a universal binary on macOS) for
electron-builder to pick up. Its token and lock-file writes have an
I/O budget, and an E2E spec drives it against the built app.
Finding it: the header gets an agent button that is always there. Its
popover explains the feature when agents are off and lists sessions,
waiting sign-ins and blocked requests when they are on. After an
agent acts, the button becomes a pill naming it. The drive picker and
the app and tray menus link to Settings too.

Connecting: Settings → AI Agents leads with a prompt to paste into
any agent, which adds DiskHound to its own configuration. DiskHound
never writes another app's config. A tab per client (Claude Code,
Claude Desktop, Codex, others) has that client's prompt, the command
behind a Show button, a Turn on button when agents are off, and a
last step that shows the connection live. Claude Desktop's chat can't
run commands, so Add to Claude builds an MCP Bundle (.mcpb) from
DiskHound's own helper and opens it in Claude, which asks the user to
install it. Claude Desktop isn't offered on Linux.

Approving: the sheet sits over the main window and names the client
and transport. Role cards show each permission; a role above the
default says what it adds, in red for permanent delete, and scrolls
into view. Requests wait in line, a client that stopped waiting is
marked, and a reloaded authorize URL reuses its request.

Managing: sessions show the client, transport, permission chips, last
action and blocked count. Role changes apply on the next call; the
stdio helper announces the new tool list itself.

Removing files: Cleanup Operator can ask for the Trash, and the new
Cleanup Admin role can ask for a permanent delete. The user confirms
every request. A session sees only the tools its role grants. Calling
another is refused before it runs, logged to agent-security.log
(capped and throttled; see the I/O budgets) and shown in Settings.

The stdio helper answers initialize at once, names the client
(Claude Desktop, Claude Code, Codex), asks the user only on a tool
call or once the client stays connected, and withdraws its request if
the client hangs up, so health checks never open a sheet. Each client
saves its own approval, so approving one never lets another in.
Claude Desktop keeps the tool list it got when it connected, so the
helper holds that first list (up to 45 s) until the user decides, and
diskhound_status tells it how to reload a list that went stale. Agent text
and confirm dialogs use the app's size units. The server moves to
port 51735.

Answering: Claude Desktop passes an extension's tools on to its chats
and Code sessions, but not its resources, so diskhound_read_skill
serves the skills as a tool too. diskhound_dev_artifacts says what
removing each tree frees once APFS clones are counted, and gives a
range for removing the listed trees together.

Measuring: diskhound_measure_removal tells an agent what removing a
set of files and folders frees, measured on disk now, so it never has
to read the index or call getattrlist itself. The scanner's new
measure-removal mode walks the paths, reads metadata only, and counts
each APFS clone group and hardlinked file once. Their blocks come back
only when every clone or name is in the set, including copies outside
it and outside any scan. A rewritten clone's shared part is reported
as uncertain. The tool returns the set's total and what each path
frees alone. The call blocks until the walk is done. If the client
stops waiting first, the walk finishes anyway, and the same call made
within 5 minutes gets that result without another walk. Windows scans
already count each file once, so the tool isn't offered there.
@huntharo
huntharo force-pushed the codex/diskhound-mcp-patterns-5e1b95 branch from 232797d to de9cdaf Compare October 14, 2026 17:25
@huntharo
huntharo merged commit 2ac189b into main Oct 14, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant