21 Commits

Author SHA1 Message Date
Mika Kuns
7b65545600 chore(release): 1.4.0
Some checks failed
CI (Node) / build-test (push) Failing after 7s
Release / release (push) Successful in 7s
Release (Node) / release (push) Failing after 8s
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 13:14:22 +02:00
Mika Kuns
b10ac36ed0 feat(naming)!: auto-derive mailbox name from project + runtime rename
Mailbox names are now built as <project>-<session-short>, where <project>
is the sanitized git-repo basename (or cwd basename) — no more env-var
prefix step. Sessions can re-tag themselves at runtime via the new
mcp__mailbox__rename tool (POST /v1/rename), which transfers all
pending messages to the new name in a single transaction. Peers using
the old name re-discover via list_mailboxes.

BREAKING: \$CLAUDE_MAILBOX_NAME is no longer read. Existing setups that
relied on the env-var prefix should remove it from .claude/settings.json;
the prefix now comes from the working directory automatically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 13:14:15 +02:00
Mika Kuns
8832eab6c7 refactor(node): migrate from better-sqlite3 to node:sqlite, require Node 24+
Some checks failed
CI (Node) / build-test (push) Failing after 8s
Native binding caused install pain on every new Node major (no prebuilts +
node-gyp needs VS+Windows SDK to fall back). For this project's workload
(a few ops/day, no advanced SQLite features) better-sqlite3's perf edge is
irrelevant — node:sqlite's bundled, ABI-stable sync API is the better fit.

- db.ts: DatabaseSync, db.exec("PRAGMA …"), explicit BEGIN/COMMIT helper to
  replace db.transaction(); row casts go through unknown because node:sqlite
  returns Record<string, SQLOutputValue>.
- package.json: drop better-sqlite3 + @types/better-sqlite3, bump
  engines.node to >=24, vitest 2 → 4 (2.x couldn't resolve `node:sqlite`).
- mailbox-doctor: add Step 1 that enforces Node ≥24 with a concrete fix
  message, renumbers downstream steps.

Node 1.2.0 → 1.3.0. 35 transitive packages removed from the lockfile.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:07:21 +02:00
Mika Kuns
8747d638fb feat(plugin): add SubagentStop hook to auto-check inbox after subagent runs
Delivers peer messages that arrive during a long-running subagent into the
parent context the moment the Task tool returns, instead of waiting until
the next user prompt. Reuses the existing `claude-mailbox check --hook` so
the mailbox identity stays consistent with UserPromptSubmit.

Plugin 1.2.0 → 1.3.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:06:55 +02:00
Mika Kuns
d456f29138 fix(plugin): sync plugin.json version with releases
All checks were successful
Release / release (push) Successful in 8s
Release (Node) / release (push) Successful in 12s
plugin.json was stuck at 0.1.0 across every release, so Claude Code's
per-version plugin cache never refreshed and clients kept running the
original .mcp.json (http://127.0.0.1:47822/mcp). Bump to 1.2.0 to match
the node package and add a release-workflow step that derives plugin.json
from the tag on every future release.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 14:51:34 +02:00
Mika Kuns
d37d2419d6 feat(cli): pre-install port check in install-autostart
All checks were successful
CI (Node) / build-test (push) Successful in 9s
Release / release (push) Successful in 8s
Release (Node) / release (push) Successful in 12s
Before registering the Scheduled Task / Run-key / launchd / systemd unit,
probe /health on the resolved port. If a non-claude-mailbox service
answers, refuse with a helpful hint (`--port <n>` or mailbox.json) so
users don't end up with autostart firing against an occupied port.
Pass --skip-port-check to bypass.

The doctor already had this logic in Step 2; now standalone
install-autostart invocations are protected too.
2026-05-19 14:09:21 +02:00
Mika Kuns
ee0b72f43b feat: change default port from 47822 to 37849 (v1.2.0)
All checks were successful
CI (Node) / build-test (push) Successful in 10s
CI (.NET) / build (push) Successful in 11s
47822 collided with ClaudeDo.Worker.exe on at least one user's machine.
37849 is high, registered to nobody, and avoids the prior conflict.
Both the Node port and the .NET port move together (still
wire-compatible). Defaults change only — if a user has a custom port
in mailbox.json, that stays.
2026-05-19 14:07:56 +02:00
Mika Kuns
d3abc762fd fix(ci): allow same-version npm version call (idempotent when source already bumped)
Some checks failed
Release / release (push) Failing after 6s
Release (Node) / release (push) Successful in 11s
2026-05-19 13:55:11 +02:00
Mika Kuns
d0eb2af183 chore(node): release v1.1.0
Some checks failed
CI (Node) / build-test (push) Successful in 9s
Release / release (push) Successful in 6s
Release (Node) / release (push) Failing after 4s
2026-05-19 13:53:34 +02:00
Mika Kuns
42237149a1 feat: stdio MCP wrapper + Windows Run-key autostart fallback (v1.0.1)
Some checks failed
CI (Node) / build-test (push) Successful in 9s
Release (Node) / release (push) Failing after 1s
Release / release (push) Successful in 7s
Two production-readiness fixes so colleagues can install cleanly:

1. Plugin's MCP server now spawns `claude-mailbox mcp-stdio`, a small
   stdio MCP wrapper that proxies tool calls to the daemon's REST API.
   Claude Code does not support env-var substitution in HTTP MCP `url`
   fields (issue #46889), so the wrapper is the only way to make the
   daemon URL configurable per machine via CLAUDE_MAILBOX_URL.

2. Windows `install-autostart` now falls back from `schtasks /Create`
   to an HKCU\Software\Microsoft\Windows\CurrentVersion\Run entry
   when Group Policy blocks the Scheduled Task path. Both modes are
   per-user, no admin, persist across logoffs. The chosen mode is
   recorded in ~/.claude-mailbox/autostart-mode so status/start/stop/
   uninstall-autostart pick the right cleanup path.

Also bumps the npm version to 1.0.1 to align with the published 1.0.0
plus this patch.
2026-05-19 13:43:55 +02:00
Mika Kuns
ac626f678b fix(cli,plugin): CLAUDE_MAILBOX_URL env override + port-conflict-aware doctor
All checks were successful
CI (Node) / build-test (push) Successful in 9s
The plugin's UserPromptSubmit and SessionStart hooks call `claude-mailbox`
with no --url flag, so they previously always hit the hardcoded
http://127.0.0.1:47822/mcp default. If port 47822 was held by another
local service (e.g. ClaudeDo), the daemon couldn't bind there and every
hook was talking to the wrong process.

CLI default for --url now resolves to $CLAUDE_MAILBOX_URL when set,
falling back to http://127.0.0.1:47822. Doctor gained a Step 2 that
probes /health on 47822, identifies foreign occupants, picks a free
port, writes both ~/.claude-mailbox/mailbox.json and the
CLAUDE_MAILBOX_URL entry in .claude/settings.json env so the hooks
follow along automatically.

Also adds a fallback hint when Windows schtasks /Create fails with
Access is denied (Group Policy restricts non-admin task creation): run
install-autostart from an elevated shell, or accept an ephemeral serve
for the current session.
2026-05-19 13:30:51 +02:00
Mika Kuns
73a49e405f docs(readme): use .git suffix on marketplace clone URL 2026-05-19 13:18:52 +02:00
Mika Kuns
43e8d0d4ca fix(ci): add pretest hook so vitest sees built dist/cli.js
All checks were successful
CI (Node) / build-test (push) Successful in 8s
Release / release (push) Successful in 8s
Release (Node) / release (push) Successful in 13s
2026-05-19 13:12:59 +02:00
Mika Kuns
50f2b5a7cb docs(readme): restructure for getting-started flow
Some checks failed
CI (Node) / build-test (push) Failing after 5s
Release (Node) / release (push) Failing after 5s
Release / release (push) Successful in 7s
2026-05-19 12:56:27 +02:00
Mika Kuns
19d7a591df chore(node): release v0.1.0 2026-05-19 12:01:41 +02:00
Mika Kuns
48b6ba6452 feat(plugin): SessionStart hook discovers and announces active peers
session-announce now calls /v1/list with the session's X-Mailbox header,
which both registers the session with the daemon and returns all known
mailboxes in one round-trip. The output appends an "Active peers" block
listing mailboxes seen within the last hour (configurable via
--peer-window-minutes), capped at 10 entries by default. Self is
filtered out; the list is sorted most-recent-first.

So when the user says "I started a second session, coordinate with it",
Claude already has the peer's mailbox name in context — no manual
list_mailboxes call needed.

The peer-formatting logic is extracted into formatActivePeerList for
unit testing; CLI tests now pin --url to an unreachable port to keep
assertions stable on machines that have a real daemon running.
2026-05-19 11:59:31 +02:00
Mika Kuns
9fd321043f feat(mcp): identity-via-arg + plugin ships .mcp.json
MCP tools (send/check_inbox/peek_inbox/list_mailboxes) now accept the
caller's mailbox name as an explicit argument (from/name), falling back
to the X-Mailbox header for legacy single-session HTTP setups. This
unblocks multi-session coordination through a shared .mcp.json — each
Claude session passes its own session-derived name on every call,
instead of relying on a single transport header that all sessions
would share.

The plugin now ships .mcp.json (no header), and the SessionStart
announcement spells out the exact args to pass to each mcp__mailbox__*
tool so Claude wires it up automatically.
2026-05-19 11:50:58 +02:00
Mika Kuns
462d6561e1 feat(plugin): per-session mailbox identity + mailbox-update command
The hook now derives a unique mailbox name from the session_id supplied
on hook stdin, so two parallel Claude Code sessions in the same project
get distinct mailboxes (e.g. `claude-a8b3c1d2`, `claude-d4e5f6a7`)
instead of colliding on a shared env value. An optional
CLAUDE_MAILBOX_NAME base prefix flavors the names as `<base>-<sid>`.

Adds:
- `claude-mailbox session-announce` subcommand for the new SessionStart
  hook, which prints the current session's mailbox name to context
- `/claude-mailbox:mailbox-update` slash command for `npm update` +
  daemon restart
- stdin parsing helpers (parseHookStdin, deriveSessionName) with unit
  tests; the doctor no longer needs a mandatory name prompt
2026-05-19 11:39:14 +02:00
Mika Kuns
c231f8c18c feat(plugin): add /claude-mailbox:mailbox-doctor for one-command setup
The doctor command runs entirely inside Claude Code and walks through:
binary install via npm, daemon autostart, mailbox-name prompt with write
to per-project `.claude/settings.json` env, and a self → self smoke test.
Also adds `/claude-mailbox:mailbox-status` as a read-only health check.

Reduces the colleague onboarding to: add marketplace, install plugin,
run the doctor — no terminal context-switch required.
2026-05-19 10:55:05 +02:00
Mika Kuns
5c5843e62d feat(plugin): ship Claude Code plugin + marketplace manifest
Adds a /plugin marketplace at the repo root and a `claude-mailbox` plugin under
plugin/ that wires the UserPromptSubmit hook without needing the per-user
`install-hook` step. The hook command (`claude-mailbox check --hook`) now reads
the mailbox name from $CLAUDE_MAILBOX_NAME when --name is omitted and emits a
one-line setup hint when the daemon is unreachable, so a missing daemon is loud
instead of invisible.

The plugin only contains the Claude Code glue — the daemon binary is still a
separate prerequisite (`npm i -g @kuns/claude-mailbox` + install-autostart),
and the plugin/README plus main README spell out the three-step setup.
2026-05-19 10:49:36 +02:00
Mika Kuns
66967167bc feat(node): add Claude Code UserPromptSubmit hook for auto inbox-check
Adds `install-hook` / `uninstall-hook` subcommands that idempotently patch
~/.claude/settings.json (or .claude/settings.json with --project), plus a
`--hook` flag on `check` that emits human-readable output and stays silent
on empty inbox or unreachable daemon.
2026-05-19 10:09:30 +02:00
29 changed files with 3061 additions and 1482 deletions

View File

@@ -0,0 +1,14 @@
{
"name": "claude-mailbox",
"owner": {
"name": "Mika Kuns"
},
"description": "Plugins for the Claude-Mailbox project.",
"plugins": [
{
"name": "claude-mailbox",
"source": "./plugin",
"description": "Auto-checks the local Claude-Mailbox daemon before every prompt and injects pending messages."
}
]
}

View File

@@ -36,7 +36,17 @@ jobs:
- name: Set package version
env:
VERSION: ${{ steps.ver.outputs.version }}
run: npm version --no-git-tag-version "$VERSION"
run: npm version --no-git-tag-version --allow-same-version "$VERSION"
- name: Sync plugin.json version
working-directory: ${{ github.workspace }}
env:
VERSION: ${{ steps.ver.outputs.version }}
run: |
set -euo pipefail
jq --arg v "$VERSION" '.version = $v' plugin/.claude-plugin/plugin.json > plugin/.claude-plugin/plugin.json.tmp
mv plugin/.claude-plugin/plugin.json.tmp plugin/.claude-plugin/plugin.json
cat plugin/.claude-plugin/plugin.json
- name: Install
run: npm ci
@@ -44,9 +54,6 @@ jobs:
- name: Test
run: npm test
- name: Build
run: npm run build
- name: Pack
env:
VERSION: ${{ steps.ver.outputs.version }}

282
README.md
View File

@@ -1,41 +1,60 @@
# ClaudeMailbox
A standalone MCP mail server that lets parallel Claude sessions coordinate with each other. Any Claude session (plain terminal, ClaudeDo worktree, anything that consumes `.mcp.json`) can send messages to a peer session's inbox, check for pending messages, and discover other active mailboxes.
A standalone MCP mail server that lets parallel Claude sessions coordinate with each other. Messages are queued in a tiny SQLite database via a local HTTP daemon. Any Claude session — Claude Code, ClaudeDo worktree, plain MCP client — can send to a peer's inbox, check for pending messages, and discover other active mailboxes.
Not a substitute for `run_in_background: true` — that handles single-session responsiveness. This handles **session-to-session** coordination.
Not a substitute for `run_in_background: true` (which handles single-session responsiveness). This handles **session-to-session** coordination.
## Architecture
---
One long-running daemon binds HTTP on loopback, hosts the MCP server at `/mcp` and a small REST API at `/v1/*`, and persists state in a single SQLite file. Sessions declare themselves via an `X-Mailbox` header in their `.mcp.json`.
## Getting started
Pick one path. Most users want path A.
### A. Claude Code plugin (recommended — three prompts)
Inside Claude Code:
```
session-backend session-frontend external sender
(X-Mailbox: backend) (X-Mailbox: frontend) (CLI / UI / hook)
| | |
| HTTP | |
+--------------+-----------------+--------------------------+
v
claude-mailbox serve (ASP.NET Core + Kestrel)
/mcp MCP tools
/v1/* REST for non-MCP senders
/health
v
~/.claude-mailbox/mailbox.db (SQLite WAL)
/plugin marketplace add https://git.kuns.dev/releases/ClaudeMailbox.git
/plugin install claude-mailbox@claude-mailbox
/claude-mailbox:mailbox-doctor
```
## Install
The doctor command does the rest:
The recommended path is the npm package — it works on Windows, macOS, and Linux.
1. installs the daemon binary via `npm install -g @kuns/claude-mailbox` if missing (asks first)
2. registers the daemon for autostart and starts it
3. optionally lets you pick a base prefix (e.g. `backend`, `frontend`); without one, mailbox names are anonymous (`claude-a8b3c1d2`)
4. runs a self → self smoke test
After that, every Claude Code session automatically:
- gets a **unique mailbox identity** derived from its session UUID (so two parallel sessions never collide),
- announces that identity and the **list of currently active peers** at session start,
- pulls unread mailbox messages into context before every prompt.
You can then say things like:
> "I started a second session, coordinate with it on the refactor."
Claude already has the peer's mailbox name in context from the SessionStart announcement, so it calls `mcp__mailbox__send(from="<my-name>", to="<peer>", body="...")` directly.
See [`plugin/README.md`](./plugin/README.md) for the full walkthrough, including the `mailbox-status` and `mailbox-update` slash commands.
### B. Manual install (no Claude Code plugin)
If you're using a different MCP client, scripts, or you don't want the plugin:
```sh
# one-time per machine: point the @kuns scope at the public Gitea npm registry
npm config set @kuns:registry=https://git.kuns.dev/api/packages/releases/npm/
# install
# install + autostart
npm install -g @kuns/claude-mailbox
claude-mailbox install-autostart
```
Or use the bootstrap one-liner:
Or the bootstrap one-liner:
```powershell
# Windows
@@ -47,89 +66,94 @@ irm https://git.kuns.dev/releases/ClaudeMailbox/raw/branch/main/install.ps1 | ie
curl -fsSL https://git.kuns.dev/releases/ClaudeMailbox/raw/branch/main/install.sh | sh
```
macOS users can also install via Homebrew once the tap is published:
```sh
brew install kuns/tap/claude-mailbox
```
### Autostart
```sh
claude-mailbox install-autostart # per-user, no admin
claude-mailbox install-autostart --service # Windows only: register as a Windows Service (admin)
claude-mailbox status # Running | Stopped | NotInstalled
claude-mailbox uninstall-autostart [--purge]
```
| Platform | Default mechanism | `--service` mechanism |
|---|---|---|
| Windows | Scheduled Task at logon (no admin) | Windows Service (admin, via `node-windows`) |
| macOS | launchd LaunchAgent in `~/Library/LaunchAgents/` | n/a |
| Linux | systemd `--user` unit in `~/.config/systemd/user/` | n/a |
### Config precedence
```
CLI flag > mailbox.json > built-in defaults
```
`mailbox.json` is searched at `~/.claude-mailbox/mailbox.json` (per-user), and on Windows additionally at `%ProgramData%\ClaudeMailbox\mailbox.json` (machine-wide, written by `--service` install). Pass `--config <path>` to override.
Defaults: port `47822`, bind `127.0.0.1`, database at `~/.claude-mailbox/mailbox.db`.
### Smoke test
```sh
claude-mailbox install-autostart
claude-mailbox status
curl http://127.0.0.1:47822/health
claude-mailbox uninstall-autostart --purge
```
### Build the .NET binary (alternative)
The original .NET 8 implementation still lives in `src/ClaudeMailbox/`. Build a self-contained Windows exe with:
```powershell
dotnet publish src/ClaudeMailbox -c Release -r win-x64 --self-contained -p:PublishSingleFile=true
```
Put the resulting `claude-mailbox.exe` on your `PATH` and use the legacy `install-service` verbs (Windows-only, admin shell):
```
claude-mailbox install-service [--port 47822] [--bind 127.0.0.1] [--db-path <path>]
claude-mailbox uninstall-service [--purge]
```
The .NET and Node builds are wire-compatible (same port, same `X-Mailbox` header, same MCP tool names, same SQLite schema), so a `.mcp.json` configured against one works against the other.
## Use from a Claude session
Drop this into your project's `.mcp.json` (one per session, different `X-Mailbox` values):
Then drop this into your project's `.mcp.json`:
```json
{
"mcpServers": {
"mailbox": {
"type": "http",
"url": "http://127.0.0.1:47822/mcp",
"headers": {
"X-Mailbox": "backend"
}
"url": "http://127.0.0.1:37849/mcp"
}
}
}
```
Four MCP tools are exposed:
Optionally add a static identity (so your client doesn't need to pass `from` / `name` on every call):
| Tool | Purpose |
```json
"headers": { "X-Mailbox": "backend" }
```
### C. Build the .NET binary from source
The original .NET 8 implementation lives in `src/ClaudeMailbox/`. Wire-compatible with the npm build (same port, same `X-Mailbox` header, same MCP tool names, same SQLite schema).
```powershell
dotnet publish src/ClaudeMailbox -c Release -r win-x64 --self-contained -p:PublishSingleFile=true
```
Put the resulting `claude-mailbox.exe` on `PATH`. Windows-only `install-service` verbs (admin shell):
```
claude-mailbox install-service [--port 37849] [--bind 127.0.0.1] [--db-path <path>]
claude-mailbox uninstall-service [--purge]
```
---
## How identity works
Every Claude Code session gets a unique mailbox name automatically derived as `<project>-<8-hex-of-session-id>`:
| Setup | Resulting mailbox name |
|---|---|
| `mcp__mailbox__send(to, body)` | Send a message to another mailbox |
| `mcp__mailbox__check_inbox()` | Pull all pending messages for this mailbox (marks delivered) |
| `mcp__mailbox__peek_inbox()` | Non-consuming check — returns `{ pending, oldestAt }` |
| `mcp__mailbox__list_mailboxes()` | Discover known mailboxes and who has mail for you |
| Inside a git repo | `<repo-basename>-<8-hex>` (e.g. `claude-mailbox-a3f91b2c`) |
| Outside a git repo | `<cwd-basename>-<8-hex>` |
| No cwd available (rare) | `claude-<8-hex>` |
| Manual `.mcp.json` with `X-Mailbox: backend` header (no plugin) | `backend` (legacy mode) |
Project names are sanitized (lowercased, non-alphanumerics → dashes, capped at 40 chars). The plugin's `SessionStart` hook prints the session's identity and the list of peers active in the last hour into the conversation context, so Claude knows who it is and who's around without needing to call any tools first.
### Renaming at runtime
Claude can refine its own mailbox name during the session — useful when a session focuses on a specific area (e.g. only frontend work):
```
mcp__mailbox__rename(current_name="claude-mailbox-a3f91b2c", new_name="claude-mailbox-frontend-a3f91b2c")
```
Pending messages are transferred to the new name in a single transaction. The old name is removed — peers using it must re-discover via `list_mailboxes`. The endpoint returns `409` if the target name is already in use.
---
## Autostart
```sh
claude-mailbox install-autostart # per-user, no admin
claude-mailbox install-autostart --service # Windows only: Windows Service (admin)
claude-mailbox status # Running | Stopped | NotInstalled
claude-mailbox uninstall-autostart [--purge]
```
| Platform | Default mechanism | `--service` mechanism |
|---|---|---|
| Windows | Scheduled Task at logon (no admin); falls back to HKCU Run-key if Group Policy blocks schtasks | Windows Service (admin, via `node-windows`) |
| macOS | launchd LaunchAgent in `~/Library/LaunchAgents/` | n/a |
| Linux | systemd `--user` unit in `~/.config/systemd/user/` | n/a |
---
## MCP tools
| Tool | Required args | Purpose |
|---|---|---|
| `mcp__mailbox__send` | `to`, `body`, `from` | Send a message. `from` falls back to X-Mailbox header. |
| `mcp__mailbox__check_inbox` | `name` | Pull all pending messages and mark delivered. Falls back to header. |
| `mcp__mailbox__peek_inbox` | `name` | Non-consuming `{ pending, oldestAt }`. Falls back to header. |
| `mcp__mailbox__list_mailboxes` | `name` | Discover known mailboxes + `pendingForYou`. Falls back to header. |
The plugin's SessionStart announcement tells Claude exactly which name to pass for the current session, so the args are filled in automatically.
### Suggested CLAUDE.md snippet for poll discipline
@@ -139,41 +163,93 @@ after each subagent completes. If pending > 0, call mcp__mailbox__check_inbox
and treat the messages as input with priority over the current plan.
```
## CLI client mode
---
Any external process (scripts, UIs, hooks) can talk to a running daemon without needing MCP:
## CLI
Any external process — scripts, UIs, manual debugging — can talk to a running daemon directly:
```
claude-mailbox send --to <mailbox> --from <mailbox> --body <text> [--url http://127.0.0.1:47822]
claude-mailbox peek --name <mailbox> [--url ...]
claude-mailbox check --name <mailbox> [--url ...]
claude-mailbox list [--url ...]
claude-mailbox send --from <mailbox> --to <mailbox> --body <text>
claude-mailbox peek --name <mailbox>
claude-mailbox check --name <mailbox> [--hook]
claude-mailbox list
claude-mailbox status
claude-mailbox session-announce # hook helper, reads stdin JSON
claude-mailbox install-hook --name <mailbox> [--user|--project]
claude-mailbox uninstall-hook [--user|--project]
```
The CLI subcommands are thin HTTP clients against the `/v1/*` endpoints.
All subcommands accept `--url <url>` to target a non-default daemon address.
---
## REST surface
| Method | Path | Requires `X-Mailbox` | Purpose |
| Method | Path | `X-Mailbox` required | Purpose |
|---|---|---|---|
| `GET` | `/health` | no | `{ status, version, dbPath }` |
| `POST` | `/v1/send` | yes (sender) | `{ to, body }` |
| `POST` | `/v1/send` | yes (sender) | body: `{ to, body }` |
| `GET` | `/v1/peek?name=<mailbox>` | no | read-only status |
| `POST` | `/v1/check-inbox?name=<mailbox>` | yes (must match `name`) | consume inbox |
| `GET` | `/v1/list` | no | list all mailboxes |
| `GET` | `/v1/list` | optional (presence registers caller) | list all mailboxes |
---
## Config precedence
```
CLI flag > mailbox.json > built-in defaults
```
`mailbox.json` is searched at `~/.claude-mailbox/mailbox.json` (per-user), and on Windows additionally at `%ProgramData%\ClaudeMailbox\mailbox.json` (machine-wide, written by `--service` install). Override with `--config <path>`.
Defaults: port `37849`, bind `127.0.0.1`, database at `~/.claude-mailbox/mailbox.db`.
---
## Architecture
One long-running daemon binds HTTP on loopback, hosts the MCP server at `/mcp` and a small REST API at `/v1/*`, and persists state in a single SQLite file.
```
session-A session-B external sender
mailbox: claude-a8b3c1d2 mailbox: claude-d4e5f6a7 (CLI / UI / script)
| | |
| HTTP | |
+--------------+-----------------+--------------------------+
v
claude-mailbox serve (npm: Fastify; .NET: Kestrel)
/mcp MCP tools
/v1/* REST for non-MCP senders
/health
v
~/.claude-mailbox/mailbox.db (SQLite WAL)
```
---
## Development
```
```sh
# Node port (the recommended runtime)
cd node
npm install
npm run build
npm test
# .NET 8 port (wire-compatible alternative)
dotnet build
dotnet test tests/ClaudeMailbox.Tests/ClaudeMailbox.Tests.csproj
dotnet run --project src/ClaudeMailbox -- serve
```
Test suite covers end-to-end coordination, concurrent `check_inbox` race safety, and schema idempotency.
The test suites cover end-to-end coordination, concurrent `check_inbox` race safety, schema idempotency, hook stdin parsing, session-id derivation, and settings-file patching.
---
## Scope
- Loopback bind only (v1). Cross-machine coordination is a future extension — swap the middleware for token auth and change the bind address.
- No auth on loopback. Local filesystem permissions are the trust boundary.
- No message expiry or cleanup. Delivered messages stay as a timeline/audit log.
- No message expiry. Delivered messages remain as an audit log.

View File

@@ -17,4 +17,36 @@ Then:
claude-mailbox install-autostart # registers per-OS autostart, no admin needed by default
```
See the repository [README](../README.md) for the full architecture, MCP tool reference, and `.mcp.json` snippet.
See the [repository README](https://git.kuns.dev/releases/ClaudeMailbox/src/branch/main/README.md) for the full architecture, MCP tool reference, and `.mcp.json` snippet.
## Claude Code hook (auto-check inbox)
Register a `UserPromptSubmit` hook so Claude pulls pending mailbox messages before every prompt:
```sh
claude-mailbox install-hook --name alice # patches ~/.claude/settings.json
claude-mailbox install-hook --name alice --project # patches <cwd>/.claude/settings.json
claude-mailbox uninstall-hook # remove again
```
The hook is idempotent (running `install-hook` twice does nothing the second time) and only touches the `UserPromptSubmit` block — other hooks and settings are preserved.
Under the hood the hook runs `claude-mailbox check --name <mailbox> --hook`, which:
- prints unread messages in a Claude-friendly format,
- silently exits 0 if the inbox is empty or the daemon is unreachable (no context noise),
- marks the messages delivered so they aren't injected again next prompt.
Cost: one local HTTP round-trip plus Node coldstart per prompt (~100ms on Windows).
## Troubleshooting
`npm install` returns `401 Unauthorized`
: The Gitea registry usually serves the `releases` scope publicly, but if your instance requires auth you'll need a read token:
```sh
npm config set //git.kuns.dev/api/packages/releases/npm/:_authToken=<token>
```
`Cannot find module 'node:sqlite'` or similar
: claude-mailbox uses Node's built-in `node:sqlite`, stable since Node 24. On Node 22.523.x it works only with `--experimental-sqlite`. Upgrade to Node 24 LTS or newer: `nvm install 24 && nvm use 24` (or `winget install OpenJS.NodeJS.LTS` on Windows).

2005
node/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "@kuns/claude-mailbox",
"version": "0.0.0",
"version": "1.4.0",
"description": "Standalone MCP mail server that lets parallel Claude sessions coordinate with each other.",
"type": "module",
"bin": {
@@ -13,17 +13,17 @@
],
"scripts": {
"build": "tsc -p tsconfig.json",
"pretest": "npm run build",
"test": "vitest run",
"test:watch": "vitest",
"start": "node dist/cli.js serve",
"prepack": "npm run build"
},
"engines": {
"node": ">=20"
"node": ">=24"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"better-sqlite3": "^11.3.0",
"commander": "^12.1.0",
"fastify": "^5.0.0",
"zod": "^3.25.0"
@@ -32,10 +32,9 @@
"node-windows": "^1.0.0-beta.8"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.11",
"@types/node": "^22.7.4",
"typescript": "^5.6.2",
"vitest": "^2.1.1"
"vitest": "^4.1.6"
},
"keywords": [
"mcp",

View File

@@ -1,10 +1,40 @@
import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
import { run, cliEntry, type AutostartManager, type AutostartInstallOpts } from "./index.js";
import { userConfigPath } from "../config.js";
function markerPath(): string {
return join(dirname(userConfigPath()), MARKER_FILE);
}
function readActiveMode(): "task" | "run-key" | null {
const path = markerPath();
if (!existsSync(path)) return null;
const raw = readFileSync(path, "utf8").trim();
if (raw === "task" || raw === "run-key") return raw;
return null;
}
function writeActiveMode(mode: "task" | "run-key"): void {
const path = markerPath();
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, mode, "utf8");
}
function clearActiveMode(): void {
const path = markerPath();
if (existsSync(path)) rmSync(path, { force: true });
}
function isAccessDenied(stderr: string): boolean {
return /access is denied|0x80070005/i.test(stderr);
}
const TASK_NAME = "ClaudeMailbox";
const SERVICE_NAME = "ClaudeMailbox";
const RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
const RUN_VALUE = "ClaudeMailbox";
const MARKER_FILE = "autostart-mode";
function ensureConfigSeeded(opts: AutostartInstallOpts): string {
const path = userConfigPath();
@@ -24,10 +54,14 @@ function buildServeCommand(): { node: string; script: string; configPath: string
return { node, script, configPath: userConfigPath() };
}
function scheduledTaskInstall(opts: AutostartInstallOpts): void {
const configPath = ensureConfigSeeded(opts);
function buildServeCommandString(configPath: string): string {
const { node, script } = buildServeCommand();
const tr = `"${node}" "${script}" serve --config "${configPath}"`;
return `"${node}" "${script}" serve --config "${configPath}"`;
}
function tryScheduledTaskInstall(opts: AutostartInstallOpts): { ok: boolean; stderr: string } {
const configPath = ensureConfigSeeded(opts);
const tr = buildServeCommandString(configPath);
const r = run("schtasks.exe", [
"/Create",
"/SC",
@@ -40,28 +74,110 @@ function scheduledTaskInstall(opts: AutostartInstallOpts): void {
"LIMITED",
"/F",
]);
if (r.status !== 0) return { ok: false, stderr: r.stderr || r.stdout };
run("schtasks.exe", ["/Run", "/TN", TASK_NAME]);
return { ok: true, stderr: "" };
}
function runKeyInstall(opts: AutostartInstallOpts): void {
const configPath = ensureConfigSeeded(opts);
const cmd = buildServeCommandString(configPath);
const r = run("reg.exe", [
"add",
RUN_KEY,
"/v",
RUN_VALUE,
"/t",
"REG_SZ",
"/d",
cmd,
"/f",
]);
if (r.status !== 0) {
throw new Error(`schtasks /Create failed (exit ${r.status}): ${r.stderr || r.stdout}`);
throw new Error(`reg add (HKCU Run) failed (exit ${r.status}): ${r.stderr || r.stdout}`);
}
const start = run("schtasks.exe", ["/Run", "/TN", TASK_NAME]);
if (start.status !== 0) {
console.warn(`Task created but /Run returned ${start.status}: ${start.stderr.trim()}`);
spawnRunKeyDaemon(configPath);
}
function spawnRunKeyDaemon(configPath: string): void {
if (runKeyDaemonRunning()) return;
const { node, script } = buildServeCommand();
const ps = `Start-Process -WindowStyle Hidden -FilePath "${node}" -ArgumentList @('"${script}"','serve','--config','"${configPath}"')`;
run("powershell.exe", ["-NoProfile", "-Command", ps]);
}
function runKeyDaemonRunning(): boolean {
const ps = `Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -like '*claude-mailbox*serve*' } | Select-Object -First 1 -ExpandProperty ProcessId`;
const r = run("powershell.exe", ["-NoProfile", "-Command", ps]);
return r.status === 0 && r.stdout.trim().length > 0;
}
function killRunKeyDaemon(): void {
const ps = `Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -like '*claude-mailbox*serve*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }`;
run("powershell.exe", ["-NoProfile", "-Command", ps]);
}
function runKeyUninstall(): void {
const r = run("reg.exe", ["delete", RUN_KEY, "/v", RUN_VALUE, "/f"]);
if (r.status !== 0 && !/unable to find/i.test(r.stderr)) {
throw new Error(`reg delete failed (exit ${r.status}): ${r.stderr || r.stdout}`);
}
killRunKeyDaemon();
}
function scheduledTaskInstall(opts: AutostartInstallOpts): void {
const attempt = tryScheduledTaskInstall(opts);
if (attempt.ok) {
writeActiveMode("task");
return;
}
if (isAccessDenied(attempt.stderr)) {
console.warn(
"schtasks /Create denied by Windows policy — falling back to HKCU Run-key autostart (per-user, no admin).",
);
runKeyInstall(opts);
writeActiveMode("run-key");
return;
}
throw new Error(`schtasks /Create failed: ${attempt.stderr}`);
}
function scheduledTaskUninstall(purge: boolean): void {
const mode = readActiveMode();
if (mode === "run-key") {
runKeyUninstall();
clearActiveMode();
if (purge) purgeData();
return;
}
// Default to task uninstall, also clean up Run-key in case of mixed state
run("schtasks.exe", ["/End", "/TN", TASK_NAME]);
const r = run("schtasks.exe", ["/Delete", "/TN", TASK_NAME, "/F"]);
if (r.status !== 0 && !/cannot find/i.test(r.stderr)) {
throw new Error(`schtasks /Delete failed (exit ${r.status}): ${r.stderr || r.stdout}`);
if (r.status !== 0 && !/cannot find/i.test(r.stderr) && !/does not exist/i.test(r.stderr)) {
// Fall through — try Run-key cleanup anyway
}
// Best-effort Run-key cleanup
run("reg.exe", ["delete", RUN_KEY, "/v", RUN_VALUE, "/f"]);
killRunKeyDaemon();
clearActiveMode();
if (purge) purgeData();
}
function scheduledTaskStatus(): "Running" | "Stopped" | "NotInstalled" {
const mode = readActiveMode();
if (mode === "run-key") {
const r = run("reg.exe", ["query", RUN_KEY, "/v", RUN_VALUE]);
if (r.status !== 0) return "NotInstalled";
return runKeyDaemonRunning() ? "Running" : "Stopped";
}
const r = run("schtasks.exe", ["/Query", "/TN", TASK_NAME, "/FO", "LIST", "/V"]);
if (r.status !== 0) {
if (/cannot find/i.test(r.stderr) || /does not exist/i.test(r.stderr)) return "NotInstalled";
if (/cannot find/i.test(r.stderr) || /does not exist/i.test(r.stderr)) {
// Maybe a Run-key install happened without a marker (legacy / manual). Check reg.
const reg = run("reg.exe", ["query", RUN_KEY, "/v", RUN_VALUE]);
if (reg.status === 0) return runKeyDaemonRunning() ? "Running" : "Stopped";
return "NotInstalled";
}
return "Stopped";
}
if (/Status:\s*Running/i.test(r.stdout)) return "Running";
@@ -69,11 +185,22 @@ function scheduledTaskStatus(): "Running" | "Stopped" | "NotInstalled" {
}
function scheduledTaskRun(): void {
const mode = readActiveMode();
if (mode === "run-key") {
const cfgPath = userConfigPath();
spawnRunKeyDaemon(cfgPath);
return;
}
const r = run("schtasks.exe", ["/Run", "/TN", TASK_NAME]);
if (r.status !== 0) throw new Error(`schtasks /Run failed: ${r.stderr || r.stdout}`);
}
function scheduledTaskEnd(): void {
const mode = readActiveMode();
if (mode === "run-key") {
killRunKeyDaemon();
return;
}
run("schtasks.exe", ["/End", "/TN", TASK_NAME]);
}

View File

@@ -1,11 +1,28 @@
#!/usr/bin/env node
import { Command } from "commander";
import { readFileSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveConfig, baseUrl, DEFAULT_PORT } from "./config.js";
import { startServer } from "./server.js";
import { autostartManager } from "./autostart/index.js";
import { runStdioMcp } from "./mcp-stdio.js";
import {
applyInstall,
applyUninstall,
buildHookCommand,
deriveSessionName,
formatActivePeerList,
formatMessagesForHook,
parseHookStdin,
readSettings,
readStdinIfPiped,
settingsPathFor,
writeSettings,
type HookMessage,
type HookScope,
type PeerEntry,
} from "./hook.js";
function readVersion(): string {
try {
@@ -19,7 +36,9 @@ function readVersion(): string {
}
}
const DEFAULT_URL = `http://127.0.0.1:${DEFAULT_PORT}`;
const HARDCODED_DEFAULT_URL = `http://127.0.0.1:${DEFAULT_PORT}`;
const ENV_URL = (process.env["CLAUDE_MAILBOX_URL"] ?? "").trim();
const DEFAULT_URL = ENV_URL || HARDCODED_DEFAULT_URL;
async function callJson(
method: string,
@@ -114,24 +133,126 @@ program
}
});
function resolveHookMailboxName(explicit: string | undefined): string | null {
if (explicit && explicit.trim()) return explicit.trim();
const stdin = parseHookStdin(readStdinIfPiped());
const sid = stdin?.session_id?.trim();
if (!sid) return null;
const cwd = typeof stdin?.cwd === "string" ? stdin.cwd : process.cwd();
return deriveSessionName(sid, cwd);
}
program
.command("check")
.description("Pull pending messages and mark delivered.")
.requiredOption("--name <name>", "Mailbox name (also sent as X-Mailbox)")
.description(
"Pull pending messages and mark delivered. In --hook mode the name is auto-derived from the SessionStart/UserPromptSubmit stdin: <project>-<session-short>, where <project> is the git-repo or cwd basename from stdin.",
)
.option(
"--name <name>",
"Explicit mailbox name. Overrides hook stdin auto-derivation.",
)
.option("--url <url>", "Daemon base URL", DEFAULT_URL)
.action(async (opts: { name: string; url: string }) => {
.option(
"--hook",
"Hook mode: human-readable output, silent when no mailbox configured or daemon unreachable. Emits a one-line setup hint when name resolves but daemon is unreachable.",
)
.action(async (opts: { name?: string; url: string; hook?: boolean }) => {
const name = opts.hook
? resolveHookMailboxName(opts.name)
: (opts.name ?? "").trim() || null;
if (!name) {
if (opts.hook) return;
console.error("Missing --name.");
process.exit(1);
}
try {
const out = await callJson(
"POST",
`${opts.url}/v1/check-inbox?name=${encodeURIComponent(opts.name)}`,
{ headers: { "X-Mailbox": opts.name } },
`${opts.url}/v1/check-inbox?name=${encodeURIComponent(name)}`,
{ headers: { "X-Mailbox": name } },
);
if (opts.hook) {
const messages = (Array.isArray(out) ? out : []) as HookMessage[];
const text = formatMessagesForHook(name, messages);
if (text) process.stdout.write(text);
return;
}
console.log(JSON.stringify(out, null, 2));
} catch (err) {
if (opts.hook) {
const msg = err instanceof Error ? err.message : String(err);
if (/ECONNREFUSED|fetch failed|ENOTFOUND|connect/i.test(msg)) {
process.stdout.write(
`[Claude-Mailbox] Daemon not reachable at ${opts.url}. Run \`claude-mailbox install-autostart\` (one-time) or \`claude-mailbox start\`.\n`,
);
}
return;
}
reportClientError(err, opts.url);
}
});
program
.command("session-announce")
.description(
"SessionStart-hook helper: derives the session's mailbox name from stdin session_id, registers it with the daemon, and announces the identity + currently active peers to context.",
)
.option("--url <url>", "Daemon base URL", DEFAULT_URL)
.option(
"--peer-window-minutes <minutes>",
"Only show peers seen within this many minutes (default 60)",
(v) => parseInt(v, 10),
60,
)
.option(
"--max-peers <n>",
"Maximum number of peers to list (default 10)",
(v) => parseInt(v, 10),
10,
)
.action(async (opts: { url: string; peerWindowMinutes: number; maxPeers: number }) => {
const stdin = parseHookStdin(readStdinIfPiped());
const sid = stdin?.session_id?.trim();
if (!sid) return;
const cwd = typeof stdin?.cwd === "string" ? stdin.cwd : process.cwd();
const name = deriveSessionName(sid, cwd);
const lines = [
`Claude-Mailbox: your mailbox name this session is \`${name}\`.`,
`The name is auto-derived as <project>-<session-short>. You can rename it (e.g. to tag your working area) with mcp__mailbox__rename(current_name="${name}", new_name="<project>-<area>-<short>"); after that, use the new name everywhere.`,
`When using mcp__mailbox__* tools, ALWAYS pass your current name explicitly:`,
` - mcp__mailbox__send: from="${name}"`,
` - mcp__mailbox__check_inbox: name="${name}"`,
` - mcp__mailbox__peek_inbox: name="${name}"`,
` - mcp__mailbox__list_mailboxes: name="${name}"`,
`Peers reach you with: mcp__mailbox__send(from="<their-name>", to="${name}", body="...")`,
];
try {
const out = await callJson("GET", `${opts.url}/v1/list`, {
headers: { "X-Mailbox": name },
});
const all = (Array.isArray(out) ? out : []) as PeerEntry[];
lines.push(
"",
...formatActivePeerList(all, name, {
windowMinutes: opts.peerWindowMinutes,
maxPeers: opts.maxPeers,
}),
);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (/ECONNREFUSED|fetch failed|ENOTFOUND|connect/i.test(msg)) {
lines.push(
"",
`[Claude-Mailbox] Daemon not reachable at ${opts.url}. Run \`claude-mailbox install-autostart\` (one-time) or \`claude-mailbox start\`.`,
);
}
}
lines.push("");
process.stdout.write(lines.join("\n"));
});
program
.command("list")
.description("List known mailboxes.")
@@ -145,6 +266,74 @@ program
}
});
program
.command("mcp-stdio")
.description(
"Run a stdio MCP server that proxies tool calls to the local daemon's REST API. The daemon URL comes from $CLAUDE_MAILBOX_URL (default http://127.0.0.1:37849). Used by the Claude Code plugin's .mcp.json so the URL is configurable per machine without env-substitution in the URL field.",
)
.action(async () => {
try {
await runStdioMcp();
} catch (err) {
console.error(err instanceof Error ? err.message : String(err));
process.exit(1);
}
});
program
.command("install-hook")
.description(
"Install a Claude Code UserPromptSubmit hook that checks the mailbox on every prompt. Idempotent.",
)
.requiredOption("--name <name>", "Mailbox name to check")
.option("--user", "Patch ~/.claude/settings.json (default)")
.option("--project", "Patch <cwd>/.claude/settings.json")
.option("--url <url>", "Daemon base URL to embed in the hook command")
.action(async (opts: { name: string; user?: boolean; project?: boolean; url?: string }) => {
if (opts.user && opts.project) {
console.error("Pick either --user or --project, not both.");
process.exit(1);
}
const scope: HookScope = opts.project ? "project" : "user";
const path = settingsPathFor(scope);
const settings = readSettings(path);
const command = buildHookCommand(opts.name, opts.url);
const result = applyInstall(settings, command);
if (result.changed) {
writeSettings(path, settings);
console.log(`Hook installed in ${path}`);
console.log(`Command: ${command}`);
} else {
console.log(`Hook already present in ${path}; nothing to do.`);
}
});
program
.command("uninstall-hook")
.description("Remove the claude-mailbox UserPromptSubmit hook from Claude Code settings.")
.option("--user", "Patch ~/.claude/settings.json (default)")
.option("--project", "Patch <cwd>/.claude/settings.json")
.action(async (opts: { user?: boolean; project?: boolean }) => {
if (opts.user && opts.project) {
console.error("Pick either --user or --project, not both.");
process.exit(1);
}
const scope: HookScope = opts.project ? "project" : "user";
const path = settingsPathFor(scope);
if (!existsSync(path)) {
console.log(`No settings file at ${path}; nothing to remove.`);
return;
}
const settings = readSettings(path);
const result = applyUninstall(settings);
if (result.changed) {
writeSettings(path, settings);
console.log(`Hook removed from ${path}`);
} else {
console.log(`No claude-mailbox hook found in ${path}; nothing to remove.`);
}
});
program
.command("install-autostart")
.description(
@@ -154,11 +343,49 @@ program
.option("--port <port>", "Port to listen on", (v) => parseInt(v, 10))
.option("--bind <address>", "Bind address")
.option("--db-path <path>", "SQLite database path")
.action(async (opts: { service?: boolean; port?: number; bind?: string; dbPath?: string }) => {
const mgr = await autostartManager(opts.service ? "service" : "default");
await mgr.install({ port: opts.port, bind: opts.bind, dbPath: opts.dbPath });
console.log("Autostart installed.");
});
.option(
"--skip-port-check",
"Skip the pre-install probe for a foreign occupant on the daemon's port",
)
.action(
async (opts: {
service?: boolean;
port?: number;
bind?: string;
dbPath?: string;
skipPortCheck?: boolean;
}) => {
if (!opts.skipPortCheck) {
const cfg = resolveConfig({ port: opts.port, bind: opts.bind, dbPath: opts.dbPath });
const probeUrl = `http://${cfg.bind}:${cfg.port}/health`;
try {
const res = await fetch(probeUrl, { headers: { Accept: "application/json" } });
const text = await res.text();
let parsed: { status?: string; version?: string } | null = null;
try {
parsed = text.length ? (JSON.parse(text) as { status?: string; version?: string }) : null;
} catch {
parsed = null;
}
if (res.ok && parsed?.status === "ok" && parsed.version) {
console.log(
`Port ${cfg.port} already serves a claude-mailbox daemon (version ${parsed.version}). Autostart will manage that one.`,
);
} else {
console.error(
`Port ${cfg.port} is held by a non-claude-mailbox service (status ${res.status}). Pick a free port via \`--port <n>\` or write {"port": <n>} to ~/.claude-mailbox/mailbox.json. Use --skip-port-check to bypass.`,
);
process.exit(4);
}
} catch {
// Connection refused or similar — port is free, proceed.
}
}
const mgr = await autostartManager(opts.service ? "service" : "default");
await mgr.install({ port: opts.port, bind: opts.bind, dbPath: opts.dbPath });
console.log("Autostart installed.");
},
);
program
.command("uninstall-autostart")

View File

@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
export const DEFAULT_PORT = 47822;
export const DEFAULT_PORT = 37849;
export const DEFAULT_BIND = "127.0.0.1";
export interface FileConfig {

View File

@@ -1,4 +1,4 @@
import Database from "better-sqlite3";
import { DatabaseSync, type StatementSync } from "node:sqlite";
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
@@ -50,6 +50,15 @@ function nowIso(): string {
return new Date().toISOString();
}
export type RenameFailure = "invalid" | "source-missing" | "target-exists";
export class RenameError extends Error {
constructor(message: string, public readonly reason: RenameFailure) {
super(message);
this.name = "RenameError";
}
}
function parseDate(s: string | null | undefined): Date | null {
if (!s) return null;
const normalized = s.includes("T") ? s : s.replace(" ", "T") + (s.endsWith("Z") ? "" : "Z");
@@ -57,28 +66,44 @@ function parseDate(s: string | null | undefined): Date | null {
return isNaN(d.getTime()) ? null : d;
}
function runInTransaction<T>(db: DatabaseSync, fn: () => T): T {
db.exec("BEGIN");
try {
const result = fn();
db.exec("COMMIT");
return result;
} catch (err) {
try {
db.exec("ROLLBACK");
} catch {
// ignore: original error already on its way up
}
throw err;
}
}
export class MailboxStore {
private readonly db: Database.Database;
private readonly db: DatabaseSync;
private readonly stmts: {
findMailbox: Database.Statement;
insertMailbox: Database.Statement;
touchMailbox: Database.Statement;
listMailboxes: Database.Statement;
insertMessage: Database.Statement;
countPending: Database.Statement;
oldestPending: Database.Statement;
selectPending: Database.Statement;
markDelivered: Database.Statement;
pendingByRecipient: Database.Statement;
findMailbox: StatementSync;
insertMailbox: StatementSync;
touchMailbox: StatementSync;
listMailboxes: StatementSync;
insertMessage: StatementSync;
countPending: StatementSync;
oldestPending: StatementSync;
selectPending: StatementSync;
markDelivered: StatementSync;
pendingByRecipient: StatementSync;
};
constructor(public readonly dbPath: string) {
mkdirSync(dirname(dbPath), { recursive: true });
this.db = new Database(dbPath);
this.db.pragma("journal_mode = WAL");
this.db.pragma("foreign_keys = ON");
for (const sql of DDL_STATEMENTS) this.db.prepare(sql).run();
this.db = new DatabaseSync(dbPath);
this.db.exec("PRAGMA journal_mode = WAL");
this.db.exec("PRAGMA foreign_keys = ON");
for (const sql of DDL_STATEMENTS) this.db.exec(sql);
this.stmts = {
findMailbox: this.db.prepare("SELECT * FROM mailboxes WHERE name = ?"),
@@ -114,7 +139,7 @@ export class MailboxStore {
upsertMailbox(name: string): void {
const now = nowIso();
const existing = this.stmts.findMailbox.get(name) as MailboxRow | undefined;
const existing = this.stmts.findMailbox.get(name) as unknown as MailboxRow | undefined;
if (existing) {
this.stmts.touchMailbox.run(now, name);
} else {
@@ -123,14 +148,13 @@ export class MailboxStore {
}
send(from: string, to: string, body: string): { id: number; queuedAt: Date } {
const tx = this.db.transaction(() => {
return runInTransaction(this.db, () => {
this.upsertMailbox(from);
this.upsertMailbox(to);
const createdAt = nowIso();
const result = this.stmts.insertMessage.run(to, from, body, createdAt);
return { id: Number(result.lastInsertRowid), queuedAt: new Date(createdAt) };
});
return tx();
}
peek(name: string): InboxStatus {
@@ -141,19 +165,47 @@ export class MailboxStore {
}
checkInbox(name: string): MessageRow[] {
const tx = this.db.transaction(() => {
const pending = this.stmts.selectPending.all(name) as MessageRow[];
return runInTransaction(this.db, () => {
const pending = this.stmts.selectPending.all(name) as unknown as MessageRow[];
if (pending.length > 0) {
const ids = pending.map((m) => m.id);
this.stmts.markDelivered.run(nowIso(), JSON.stringify(ids));
}
return pending;
});
return tx();
}
rename(from: string, to: string): { from: string; to: string; messagesTransferred: number } {
const oldName = from.trim();
const newName = to.trim();
if (!oldName) throw new RenameError("from is required", "invalid");
if (!newName) throw new RenameError("to is required", "invalid");
if (oldName === newName) {
this.upsertMailbox(oldName);
return { from: oldName, to: newName, messagesTransferred: 0 };
}
return runInTransaction(this.db, () => {
const source = this.stmts.findMailbox.get(oldName) as unknown as MailboxRow | undefined;
if (!source) throw new RenameError(`Mailbox '${oldName}' does not exist.`, "source-missing");
const target = this.stmts.findMailbox.get(newName) as unknown as MailboxRow | undefined;
if (target) throw new RenameError(`Mailbox '${newName}' already exists.`, "target-exists");
const now = nowIso();
this.stmts.insertMailbox.run(newName, source.created_at, now);
const movedTo = this.db
.prepare("UPDATE messages SET to_mailbox = ? WHERE to_mailbox = ?")
.run(newName, oldName);
this.db
.prepare("UPDATE messages SET from_mailbox = ? WHERE from_mailbox = ?")
.run(newName, oldName);
this.db.prepare("DELETE FROM mailboxes WHERE name = ?").run(oldName);
return { from: oldName, to: newName, messagesTransferred: Number(movedTo.changes ?? 0) };
});
}
listMailboxes(forName?: string): MailboxInfo[] {
const rows = this.stmts.listMailboxes.all() as MailboxRow[];
const rows = this.stmts.listMailboxes.all() as unknown as MailboxRow[];
const pendingMap = new Map<string, number>();
if (forName) {
const counts = this.stmts.pendingByRecipient.all() as { to_mailbox: string; n: number }[];

244
node/src/hook.ts Normal file
View File

@@ -0,0 +1,244 @@
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { basename, dirname, join } from "node:path";
export interface HookStdinPayload {
session_id?: string;
hook_event_name?: string;
[key: string]: unknown;
}
export function parseHookStdin(raw: string | null | undefined): HookStdinPayload | null {
if (!raw || !raw.trim()) return null;
try {
const parsed = JSON.parse(raw) as unknown;
if (parsed && typeof parsed === "object") return parsed as HookStdinPayload;
return null;
} catch {
return null;
}
}
export function readStdinIfPiped(): string | null {
if (process.stdin.isTTY) return null;
try {
return readFileSync(0, "utf8");
} catch {
return null;
}
}
export function shortSessionId(sessionId: string): string {
const hex = sessionId.replace(/[^0-9a-fA-F]/g, "").toLowerCase();
if (hex.length >= 8) return hex.slice(0, 8);
return sessionId.toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 8) || "00000000";
}
const MAX_PROJECT_NAME_LENGTH = 40;
export function sanitizeProjectName(raw: string | null | undefined): string {
if (!raw) return "";
const cleaned = raw
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
return cleaned.slice(0, MAX_PROJECT_NAME_LENGTH).replace(/-+$/g, "");
}
export function deriveProjectName(cwd?: string | null): string {
const dir = (cwd ?? "").trim();
if (dir) {
const gitTop = gitToplevel(dir);
if (gitTop) {
const sanitized = sanitizeProjectName(basename(gitTop));
if (sanitized) return sanitized;
}
const sanitized = sanitizeProjectName(basename(dir));
if (sanitized) return sanitized;
}
return "claude";
}
function gitToplevel(cwd: string): string | null {
try {
const r = spawnSync("git", ["rev-parse", "--show-toplevel"], {
cwd,
encoding: "utf8",
timeout: 1500,
});
if (r.status !== 0) return null;
const out = (r.stdout ?? "").trim();
return out || null;
} catch {
return null;
}
}
export function deriveSessionName(sessionId: string, cwd?: string | null): string {
const short = shortSessionId(sessionId);
const project = deriveProjectName(cwd);
return `${project}-${short}`;
}
export interface PeerEntry {
name: string;
lastSeenAt: string;
}
export function formatActivePeerList(
peers: PeerEntry[],
selfName: string,
options: { windowMinutes: number; maxPeers: number; now?: number },
): string[] {
const others = peers.filter((p) => p.name !== selfName);
const cutoff = (options.now ?? Date.now()) - options.windowMinutes * 60_000;
const active = others
.filter((p) => {
const t = new Date(p.lastSeenAt).getTime();
return Number.isFinite(t) && t >= cutoff;
})
.sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt))
.slice(0, options.maxPeers);
if (active.length === 0) {
return [
`No other mailboxes seen within the last ${options.windowMinutes} minutes (${others.length} total registered).`,
];
}
const lines = [
`Active peers (seen within last ${options.windowMinutes} min, ${active.length} of ${others.length} total):`,
];
for (const p of active) {
lines.push(` - ${p.name} (last seen ${p.lastSeenAt})`);
}
return lines;
}
export interface HookMessage {
id: number;
from: string;
body: string;
sentAt: string;
}
export function formatMessagesForHook(name: string, messages: HookMessage[]): string {
if (messages.length === 0) return "";
const header =
messages.length === 1
? `You have 1 new mailbox message for "${name}":`
: `You have ${messages.length} new mailbox messages for "${name}":`;
const lines: string[] = [header, ""];
for (const m of messages) {
lines.push(`[#${m.id}] from ${m.from} (${m.sentAt}):`);
for (const bodyLine of m.body.split(/\r?\n/)) {
lines.push(` ${bodyLine}`);
}
lines.push("");
}
return lines.join("\n").trimEnd() + "\n";
}
export type HookScope = "user" | "project";
export function settingsPathFor(scope: HookScope, cwd: string = process.cwd()): string {
if (scope === "user") return join(homedir(), ".claude", "settings.json");
return join(cwd, ".claude", "settings.json");
}
interface ClaudeHookCommand {
type: "command";
command: string;
timeout?: number;
}
interface ClaudeHookGroup {
matcher?: string;
hooks: ClaudeHookCommand[];
}
interface ClaudeSettings {
hooks?: Record<string, ClaudeHookGroup[]>;
[key: string]: unknown;
}
const HOOK_EVENT = "UserPromptSubmit";
export function buildHookCommand(name: string, url?: string): string {
const parts = ["claude-mailbox", "check", "--name", quoteIfNeeded(name), "--hook"];
if (url) parts.push("--url", quoteIfNeeded(url));
return parts.join(" ");
}
function quoteIfNeeded(value: string): string {
if (/^[A-Za-z0-9._:/@\-]+$/.test(value)) return value;
return `"${value.replace(/(["\\])/g, "\\$1")}"`;
}
function isOurHookCommand(command: string): boolean {
const c = command.trim();
return /(^|\W)claude-mailbox\s+check\s/.test(c) && /(^|\s)--hook(\s|$)/.test(c);
}
export function readSettings(path: string): ClaudeSettings {
if (!existsSync(path)) return {};
const raw = readFileSync(path, "utf8");
if (!raw.trim()) return {};
return JSON.parse(raw) as ClaudeSettings;
}
export function writeSettings(path: string, settings: ClaudeSettings): void {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(settings, null, 2) + "\n", "utf8");
}
export interface PatchResult {
changed: boolean;
reason: "added" | "already-present" | "removed" | "not-present";
}
export function applyInstall(settings: ClaudeSettings, command: string): PatchResult {
settings.hooks ??= {};
settings.hooks[HOOK_EVENT] ??= [];
const groups = settings.hooks[HOOK_EVENT];
for (const group of groups) {
for (const hook of group.hooks) {
if (hook.command.trim() === command.trim()) {
return { changed: false, reason: "already-present" };
}
}
}
let target = groups.find((g) => (g.matcher ?? "") === "");
if (!target) {
target = { matcher: "", hooks: [] };
groups.push(target);
}
target.hooks.push({ type: "command", command });
return { changed: true, reason: "added" };
}
export function applyUninstall(settings: ClaudeSettings): PatchResult {
const groups = settings.hooks?.[HOOK_EVENT];
if (!groups || groups.length === 0) return { changed: false, reason: "not-present" };
let removed = false;
for (const group of groups) {
const before = group.hooks.length;
group.hooks = group.hooks.filter((h) => !isOurHookCommand(h.command));
if (group.hooks.length !== before) removed = true;
}
settings.hooks![HOOK_EVENT] = groups.filter((g) => g.hooks.length > 0);
if (settings.hooks![HOOK_EVENT].length === 0) {
delete settings.hooks![HOOK_EVENT];
}
if (settings.hooks && Object.keys(settings.hooks).length === 0) {
delete settings.hooks;
}
return removed ? { changed: true, reason: "removed" } : { changed: false, reason: "not-present" };
}

195
node/src/mcp-stdio.ts Normal file
View File

@@ -0,0 +1,195 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { DEFAULT_PORT } from "./config.js";
const HARDCODED_DEFAULT_URL = `http://127.0.0.1:${DEFAULT_PORT}`;
function resolveDaemonUrl(): string {
const env = (process.env["CLAUDE_MAILBOX_URL"] ?? "").trim();
if (!env || env.includes("${")) return HARDCODED_DEFAULT_URL;
return env.replace(/\/$/, "");
}
function requireIdentity(value: string | undefined, argName: "from" | "name"): string {
const v = (value ?? "").trim();
if (!v) {
throw new Error(
`Pass \`${argName}\` (your mailbox name from the SessionStart announcement).`,
);
}
return v;
}
async function rest(
method: "GET" | "POST",
url: string,
init: { headers?: Record<string, string>; body?: unknown } = {},
): Promise<unknown> {
const headers: Record<string, string> = { Accept: "application/json", ...(init.headers ?? {}) };
let body: string | undefined;
if (init.body !== undefined) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(init.body);
}
const res = await fetch(url, { method, headers, body });
const text = await res.text();
if (!res.ok) {
throw new Error(`${method} ${url}${res.status}: ${text}`);
}
return text.length ? JSON.parse(text) : null;
}
export function buildStdioMcpServer(daemonUrl: string = resolveDaemonUrl()): McpServer {
const server = new McpServer({ name: "claude-mailbox", version: "1.0.0" });
server.registerTool(
"send",
{
title: "Send mail",
description:
"Send a message to another mailbox. Pass `from` with your own mailbox name (see the SessionStart announcement).",
inputSchema: {
to: z.string().describe("Name of the recipient mailbox."),
body: z.string().describe("Message body (plain text or markdown)."),
from: z
.string()
.describe(
"Your mailbox name. Take it from the SessionStart announcement.",
),
},
},
async ({ to, body, from }) => {
const sender = requireIdentity(from, "from");
const out = (await rest("POST", `${daemonUrl}/v1/send`, {
headers: { "X-Mailbox": sender },
body: { to, body },
})) as { id: number; queuedAt: string };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
server.registerTool(
"check_inbox",
{
title: "Check inbox",
description:
"Pull all undelivered messages for your mailbox and mark them delivered. Pass `name` with your own mailbox name.",
inputSchema: {
name: z
.string()
.describe(
"Your mailbox name. Take it from the SessionStart announcement.",
),
},
},
async ({ name }) => {
const me = requireIdentity(name, "name");
const messages = (await rest(
"POST",
`${daemonUrl}/v1/check-inbox?name=${encodeURIComponent(me)}`,
{ headers: { "X-Mailbox": me } },
)) as { id: number; from: string; body: string; sentAt: string }[];
const arr = Array.isArray(messages) ? messages : [];
return {
content: [{ type: "text", text: JSON.stringify(arr) }],
structuredContent: { messages: arr },
};
},
);
server.registerTool(
"peek_inbox",
{
title: "Peek inbox",
description:
"Non-consuming check of your mailbox. Returns pending count and oldest pending timestamp. Pass `name` with your own mailbox name.",
inputSchema: {
name: z
.string()
.describe(
"Your mailbox name. Take it from the SessionStart announcement.",
),
},
},
async ({ name }) => {
const me = requireIdentity(name, "name");
const out = (await rest("GET", `${daemonUrl}/v1/peek?name=${encodeURIComponent(me)}`)) as {
pending: number;
oldestAt: string | null;
};
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
server.registerTool(
"list_mailboxes",
{
title: "List mailboxes",
description:
"Discover known mailboxes and how many messages each has waiting for you. Pass `name` with your own mailbox name.",
inputSchema: {
name: z
.string()
.describe(
"Your mailbox name. Take it from the SessionStart announcement.",
),
},
},
async ({ name }) => {
const me = requireIdentity(name, "name");
const list = (await rest("GET", `${daemonUrl}/v1/list`, {
headers: { "X-Mailbox": me },
})) as { name: string; lastSeenAt: string; pendingForYou: number }[];
const arr = Array.isArray(list) ? list : [];
return {
content: [{ type: "text", text: JSON.stringify(arr) }],
structuredContent: { mailboxes: arr },
};
},
);
server.registerTool(
"rename",
{
title: "Rename your mailbox",
description:
"Rename your own mailbox (e.g. to add a working-area tag like `myproject-frontend-a3f9`). Pending messages are transferred to the new name. After this returns, USE THE NEW NAME for all subsequent send/check/peek/list calls. Peers using the old name will fail until they re-discover via list_mailboxes.",
inputSchema: {
current_name: z
.string()
.describe(
"Your current mailbox name (from the SessionStart announcement or last rename).",
),
new_name: z
.string()
.describe("The new mailbox name. Must be unique. Convention: <project>-<area>-<short>."),
},
},
async ({ current_name, new_name }) => {
const from = requireIdentity(current_name, "name");
const out = (await rest("POST", `${daemonUrl}/v1/rename`, {
headers: { "X-Mailbox": from },
body: { to: new_name },
})) as { from: string; to: string; messagesTransferred: number };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
return server;
}
export async function runStdioMcp(): Promise<void> {
const server = buildStdioMcpServer();
const transport = new StdioServerTransport();
await server.connect(transport);
}

View File

@@ -2,38 +2,54 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
import type { FastifyInstance } from "fastify";
import { MailboxStore, rowToMessage } from "./db.js";
import { MailboxStore, RenameError, rowToMessage } from "./db.js";
import { HEADER_NAME } from "./server.js";
function headerFallback(extra: unknown): string {
const headers =
(extra as { requestInfo?: { headers?: Record<string, string | string[] | undefined> } })
?.requestInfo?.headers ?? {};
const raw = headers[HEADER_NAME] ?? headers["X-Mailbox"];
return (Array.isArray(raw) ? raw[0] : raw ?? "").trim();
}
export function resolveIdentity(
argValue: string | undefined,
extra: unknown,
argName: "from" | "name",
): string {
const explicit = (argValue ?? "").trim();
if (explicit) return explicit;
const fallback = headerFallback(extra);
if (fallback) return fallback;
throw new Error(
`Pass \`${argName}\` (your mailbox name from the SessionStart announcement) or set the X-Mailbox header in .mcp.json.`,
);
}
function buildMcpServer(store: MailboxStore): McpServer {
const server = new McpServer({ name: "claude-mailbox", version: "1.0.0" });
const requireSender = (extra: unknown): string => {
const headers =
(extra as { requestInfo?: { headers?: Record<string, string | string[] | undefined> } })
?.requestInfo?.headers ?? {};
const raw = headers[HEADER_NAME] ?? headers["X-Mailbox"];
const value = (Array.isArray(raw) ? raw[0] : raw ?? "").trim();
if (!value) {
throw new Error(`Missing ${HEADER_NAME} header. Set it in your .mcp.json under headers.`);
}
return value;
};
server.registerTool(
"send",
{
title: "Send mail",
description:
"Send a message to another mailbox. The sender is the current session's X-Mailbox name.",
"Send a message to another mailbox. Pass `from` with your own mailbox name (see the SessionStart announcement); falls back to the X-Mailbox header for single-session HTTP setups.",
inputSchema: {
to: z.string().describe("Name of the recipient mailbox."),
body: z.string().describe("Message body (plain text or markdown)."),
from: z
.string()
.optional()
.describe(
"Your mailbox name (the sender). Take it from the SessionStart announcement. Required unless X-Mailbox is set in .mcp.json.",
),
},
},
async ({ to, body }, extra) => {
const from = requireSender(extra);
const r = store.send(from, to, body);
async ({ to, body, from }, extra) => {
const sender = resolveIdentity(from, extra, "from");
const r = store.send(sender, to, body);
const out = { id: r.id, queuedAt: r.queuedAt.toISOString() };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
@@ -47,12 +63,19 @@ function buildMcpServer(store: MailboxStore): McpServer {
{
title: "Check inbox",
description:
"Pull all undelivered messages for the current mailbox and mark them delivered. Returns an empty array when the inbox is empty.",
inputSchema: {},
"Pull all undelivered messages for your mailbox and mark them delivered. Pass `name` with your own mailbox name (from the SessionStart announcement); falls back to X-Mailbox header.",
inputSchema: {
name: z
.string()
.optional()
.describe(
"Your mailbox name. Take it from the SessionStart announcement. Required unless X-Mailbox is set in .mcp.json.",
),
},
},
async (_args, extra) => {
const name = requireSender(extra);
const messages = store.checkInbox(name).map((m) => {
async ({ name }, extra) => {
const me = resolveIdentity(name, extra, "name");
const messages = store.checkInbox(me).map((m) => {
const x = rowToMessage(m);
return { id: x.id, from: x.from, body: x.body, sentAt: x.sentAt.toISOString() };
});
@@ -68,12 +91,19 @@ function buildMcpServer(store: MailboxStore): McpServer {
{
title: "Peek inbox",
description:
"Non-consuming check of the current mailbox. Returns pending count and oldest pending timestamp.",
inputSchema: {},
"Non-consuming check of your mailbox. Returns pending count and oldest pending timestamp. Pass `name` with your own mailbox name; falls back to X-Mailbox header.",
inputSchema: {
name: z
.string()
.optional()
.describe(
"Your mailbox name. Take it from the SessionStart announcement. Required unless X-Mailbox is set in .mcp.json.",
),
},
},
async (_args, extra) => {
const name = requireSender(extra);
const status = store.peek(name);
async ({ name }, extra) => {
const me = resolveIdentity(name, extra, "name");
const status = store.peek(me);
const out = { pending: status.pending, oldestAt: status.oldestAt?.toISOString() ?? null };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
@@ -86,12 +116,20 @@ function buildMcpServer(store: MailboxStore): McpServer {
"list_mailboxes",
{
title: "List mailboxes",
description: "Discover known mailboxes and how many messages each has waiting for you.",
inputSchema: {},
description:
"Discover known mailboxes and how many messages each has waiting for you. Pass `name` with your own mailbox name to get accurate `pendingForYou` counts; falls back to X-Mailbox header.",
inputSchema: {
name: z
.string()
.optional()
.describe(
"Your mailbox name. Take it from the SessionStart announcement. Required unless X-Mailbox is set in .mcp.json.",
),
},
},
async (_args, extra) => {
const name = requireSender(extra);
const list = store.listMailboxes(name).map((m) => ({
async ({ name }, extra) => {
const me = resolveIdentity(name, extra, "name");
const list = store.listMailboxes(me).map((m) => ({
name: m.name,
lastSeenAt: m.lastSeenAt.toISOString(),
pendingForYou: m.pendingForYou,
@@ -103,6 +141,42 @@ function buildMcpServer(store: MailboxStore): McpServer {
},
);
server.registerTool(
"rename",
{
title: "Rename your mailbox",
description:
"Rename your own mailbox (e.g. to add a working-area tag like `myproject-frontend-a3f9`). Pending messages are transferred to the new name. After this returns, USE THE NEW NAME for all subsequent send/check/peek/list calls. Peers using the old name will fail until they re-discover via list_mailboxes.",
inputSchema: {
current_name: z
.string()
.optional()
.describe(
"Your current mailbox name (the one to rename away from). Required unless X-Mailbox is set in .mcp.json.",
),
new_name: z
.string()
.describe("The new mailbox name. Must be unique. Convention: <project>-<area>-<short>."),
},
},
async ({ current_name, new_name }, extra) => {
const from = resolveIdentity(current_name, extra, "name");
try {
const r = store.rename(from, new_name);
const out = { from: r.from, to: r.to, messagesTransferred: r.messagesTransferred };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
} catch (err) {
if (err instanceof RenameError) {
throw new Error(`${err.message} (${err.reason})`);
}
throw err;
}
},
);
return server;
}

View File

@@ -2,7 +2,7 @@ import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest }
import { readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { MailboxStore, rowToMessage } from "./db.js";
import { MailboxStore, RenameError, rowToMessage } from "./db.js";
import type { DaemonConfig } from "./config.js";
import { registerMcp } from "./mcp.js";
@@ -100,6 +100,25 @@ export async function buildServer(cfg: DaemonConfig, store: MailboxStore): Promi
}));
});
app.post<{ Body: { to?: string } }>("/v1/rename", async (req, reply) => {
const from = req.mailboxName!;
const to = (req.body?.to ?? "").trim();
if (!to) {
reply.code(400);
return { error: "to is required" };
}
try {
const r = store.rename(from, to);
return { from: r.from, to: r.to, messagesTransferred: r.messagesTransferred };
} catch (err) {
if (err instanceof RenameError) {
reply.code(err.reason === "target-exists" ? 409 : 400);
return { error: err.message, reason: err.reason };
}
throw err;
}
});
await registerMcp(app, store);
return app;

125
node/tests/cli-hook.test.ts Normal file
View File

@@ -0,0 +1,125 @@
import { describe, it, expect, beforeAll } from "vitest";
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
const cliPath = resolve(__dirname, "..", "dist", "cli.js");
function runCli(
args: string[],
opts: { env?: Record<string, string | undefined>; stdin?: string } = {},
): { status: number; stdout: string; stderr: string } {
const r = spawnSync(process.execPath, [cliPath, ...args], {
encoding: "utf8",
env: { ...process.env, ...(opts.env ?? {}) },
input: opts.stdin,
});
return {
status: r.status ?? -1,
stdout: typeof r.stdout === "string" ? r.stdout : "",
stderr: typeof r.stderr === "string" ? r.stderr : "",
};
}
const HOOK_STDIN = JSON.stringify({
session_id: "abc12345-de67-89f0-1234-567890abcdef",
hook_event_name: "UserPromptSubmit",
cwd: "/tmp",
prompt: "test",
});
describe("`check --hook` CLI behavior", () => {
beforeAll(() => {
if (!existsSync(cliPath)) {
throw new Error(`CLI not built. Run \`npm run build\` first. Missing: ${cliPath}`);
}
});
it("exits 0 silently when no stdin and no --name", () => {
const r = runCli(["check", "--hook"]);
expect(r.status).toBe(0);
expect(r.stdout).toBe("");
expect(r.stderr).toBe("");
});
it("derives session-id-based name from stdin and emits daemon hint when down", () => {
const r = runCli(["check", "--hook", "--url", "http://127.0.0.1:1"], {
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
});
it("explicit --name overrides session-id derivation", () => {
const r = runCli(
["check", "--hook", "--name", "explicit", "--url", "http://127.0.0.1:1"],
{ stdin: HOOK_STDIN },
);
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
});
it("uses CLAUDE_MAILBOX_URL env as default base URL when --url is not given", () => {
const r = runCli(["check", "--hook"], {
env: { CLAUDE_MAILBOX_URL: "http://127.0.0.1:1" },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable at http://127.0.0.1:1");
});
it("non-hook mode errors out when no name resolved", () => {
const r = runCli(["check"]);
expect(r.status).not.toBe(0);
expect(r.stderr).toContain("Missing --name");
});
});
describe("`session-announce` CLI behavior", () => {
const UNREACHABLE = "http://127.0.0.1:1";
beforeAll(() => {
if (!existsSync(cliPath)) {
throw new Error(`CLI not built. Run \`npm run build\` first. Missing: ${cliPath}`);
}
});
it("prints the derived mailbox name from a SessionStart payload (project-prefixed)", () => {
// cwd "/tmp" is not a git repo → basename "tmp" → project prefix "tmp".
const r = runCli(["session-announce", "--url", UNREACHABLE], {
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
// The exact prefix depends on the runtime cwd if git resolves; the deterministic
// assertion is the session-short suffix and the announcement structure.
expect(r.stdout).toMatch(/`[a-z0-9-]+-abc12345`/);
expect(r.stdout).toContain("mcp__mailbox__send");
expect(r.stdout).toMatch(/from="[a-z0-9-]+-abc12345"/);
});
it("includes a hint about the rename tool", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], { stdin: HOOK_STDIN });
expect(r.status).toBe(0);
expect(r.stdout).toContain("mcp__mailbox__rename");
});
it("emits daemon-not-reachable hint when daemon is down", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], { stdin: HOOK_STDIN });
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
});
it("stays silent when no session_id in stdin", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], {
stdin: JSON.stringify({ hook_event_name: "SessionStart" }),
});
expect(r.status).toBe(0);
expect(r.stdout).toBe("");
});
it("stays silent when no stdin at all", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE]);
expect(r.status).toBe(0);
expect(r.stdout).toBe("");
});
});

View File

@@ -2,7 +2,7 @@ import { describe, it, expect, afterEach, beforeEach } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { MailboxStore } from "../src/db.js";
import { MailboxStore, RenameError } from "../src/db.js";
let dir: string;
let dbPath: string;
@@ -75,6 +75,93 @@ describe("send / peek / check round-trip", () => {
});
});
describe("rename", () => {
it("renames a mailbox and transfers undelivered messages", () => {
const store = new MailboxStore(dbPath);
try {
store.send("alice", "bob-old", "hi");
store.send("alice", "bob-old", "again");
const r = store.rename("bob-old", "bob-new");
expect(r.from).toBe("bob-old");
expect(r.to).toBe("bob-new");
expect(r.messagesTransferred).toBe(2);
// Old name is gone.
const list = store.listMailboxes().map((m) => m.name);
expect(list).toContain("bob-new");
expect(list).not.toContain("bob-old");
// Messages still pending under the new name.
const peek = store.peek("bob-new");
expect(peek.pending).toBe(2);
// checkInbox under the new name yields the original bodies and the original from.
const pulled = store.checkInbox("bob-new");
expect(pulled.map((m) => m.body)).toEqual(["hi", "again"]);
} finally {
store.close();
}
});
it("also rewrites the from-side when the renamed mailbox was a sender", () => {
const store = new MailboxStore(dbPath);
try {
store.send("sender-old", "bob", "msg-1");
store.rename("sender-old", "sender-new");
const pulled = store.checkInbox("bob");
expect(pulled).toHaveLength(1);
expect(pulled[0]!.from_mailbox).toBe("sender-new");
} finally {
store.close();
}
});
it("treats rename-to-same-name as a no-op touch", () => {
const store = new MailboxStore(dbPath);
try {
store.upsertMailbox("alice");
const r = store.rename("alice", "alice");
expect(r.messagesTransferred).toBe(0);
expect(store.listMailboxes().map((m) => m.name)).toEqual(["alice"]);
} finally {
store.close();
}
});
it("rejects when target already exists", () => {
const store = new MailboxStore(dbPath);
try {
store.upsertMailbox("alice");
store.upsertMailbox("bob");
expect(() => store.rename("alice", "bob")).toThrow(RenameError);
try {
store.rename("alice", "bob");
} catch (e) {
expect((e as RenameError).reason).toBe("target-exists");
}
// Source still present after the failed attempt.
expect(store.listMailboxes().map((m) => m.name)).toEqual(["alice", "bob"]);
} finally {
store.close();
}
});
it("rejects when source is missing", () => {
const store = new MailboxStore(dbPath);
try {
try {
store.rename("nope", "fresh");
} catch (e) {
expect(e).toBeInstanceOf(RenameError);
expect((e as RenameError).reason).toBe("source-missing");
}
} finally {
store.close();
}
});
});
describe("listMailboxes", () => {
it("returns mailboxes alphabetically with pendingForYou for the caller", () => {
const store = new MailboxStore(dbPath);

415
node/tests/hook.test.ts Normal file
View File

@@ -0,0 +1,415 @@
import { describe, it, expect } from "vitest";
import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { execFileSync } from "node:child_process";
import {
applyInstall,
applyUninstall,
buildHookCommand,
deriveProjectName,
deriveSessionName,
formatActivePeerList,
formatMessagesForHook,
parseHookStdin,
readSettings,
sanitizeProjectName,
shortSessionId,
writeSettings,
type PeerEntry,
} from "../src/hook.js";
describe("formatMessagesForHook", () => {
it("returns empty string for empty inbox", () => {
expect(formatMessagesForHook("bob", [])).toBe("");
});
it("formats a single message", () => {
const out = formatMessagesForHook("bob", [
{ id: 1, from: "alice", body: "hi bob", sentAt: "2026-05-19T10:00:00.000Z" },
]);
expect(out).toContain("1 new mailbox message");
expect(out).toContain("[#1] from alice (2026-05-19T10:00:00.000Z):");
expect(out).toContain(" hi bob");
});
it("formats multiple messages with plural header", () => {
const out = formatMessagesForHook("bob", [
{ id: 1, from: "alice", body: "one", sentAt: "2026-05-19T10:00:00.000Z" },
{ id: 2, from: "carol", body: "two", sentAt: "2026-05-19T10:01:00.000Z" },
]);
expect(out).toContain("2 new mailbox messages");
expect(out).toContain("[#1] from alice");
expect(out).toContain("[#2] from carol");
});
it("preserves multi-line bodies with indentation", () => {
const out = formatMessagesForHook("bob", [
{ id: 1, from: "alice", body: "line1\nline2", sentAt: "2026-05-19T10:00:00.000Z" },
]);
expect(out).toContain(" line1");
expect(out).toContain(" line2");
});
});
describe("buildHookCommand", () => {
it("builds a basic command", () => {
expect(buildHookCommand("alice")).toBe("claude-mailbox check --name alice --hook");
});
it("appends --url when provided", () => {
expect(buildHookCommand("alice", "http://127.0.0.1:9000")).toBe(
"claude-mailbox check --name alice --hook --url http://127.0.0.1:9000",
);
});
it("quotes names with spaces", () => {
const cmd = buildHookCommand("my mailbox");
expect(cmd).toContain('--name "my mailbox"');
});
});
describe("applyInstall", () => {
it("creates hooks structure from empty settings", () => {
const s: Record<string, unknown> = {};
const r = applyInstall(s, "claude-mailbox check --name bob --hook");
expect(r).toEqual({ changed: true, reason: "added" });
expect(s).toMatchObject({
hooks: {
UserPromptSubmit: [
{
matcher: "",
hooks: [{ type: "command", command: "claude-mailbox check --name bob --hook" }],
},
],
},
});
});
it("is idempotent — does not duplicate the same command", () => {
const s: Record<string, unknown> = {};
applyInstall(s, "claude-mailbox check --name bob --hook");
const r = applyInstall(s, "claude-mailbox check --name bob --hook");
expect(r).toEqual({ changed: false, reason: "already-present" });
const groups = (s.hooks as { UserPromptSubmit: { hooks: unknown[] }[] }).UserPromptSubmit;
expect(groups[0]!.hooks).toHaveLength(1);
});
it("preserves existing unrelated hooks", () => {
const s: Record<string, unknown> = {
hooks: {
UserPromptSubmit: [
{
matcher: "",
hooks: [{ type: "command", command: "echo something-else" }],
},
],
PostToolUse: [{ matcher: "Bash", hooks: [{ type: "command", command: "logger" }] }],
},
};
applyInstall(s, "claude-mailbox check --name bob --hook");
const hooks = s.hooks as { UserPromptSubmit: { hooks: { command: string }[] }[] };
expect(hooks.UserPromptSubmit[0]!.hooks).toHaveLength(2);
expect(hooks.UserPromptSubmit[0]!.hooks[0]!.command).toBe("echo something-else");
expect(hooks.UserPromptSubmit[0]!.hooks[1]!.command).toBe(
"claude-mailbox check --name bob --hook",
);
expect((s.hooks as Record<string, unknown>).PostToolUse).toBeDefined();
});
it("adds a new empty-matcher group when only non-empty matchers exist", () => {
const s: Record<string, unknown> = {
hooks: {
UserPromptSubmit: [
{ matcher: "Bash", hooks: [{ type: "command", command: "echo bash-only" }] },
],
},
};
applyInstall(s, "claude-mailbox check --name bob --hook");
const groups = (s.hooks as { UserPromptSubmit: { matcher?: string }[] }).UserPromptSubmit;
expect(groups).toHaveLength(2);
expect(groups[1]!.matcher).toBe("");
});
});
describe("applyUninstall", () => {
it("removes the hook and cleans up empty structures", () => {
const s: Record<string, unknown> = {};
applyInstall(s, "claude-mailbox check --name bob --hook");
const r = applyUninstall(s);
expect(r).toEqual({ changed: true, reason: "removed" });
expect(s.hooks).toBeUndefined();
});
it("preserves unrelated hooks in the same group", () => {
const s: Record<string, unknown> = {
hooks: {
UserPromptSubmit: [
{
matcher: "",
hooks: [
{ type: "command", command: "echo something-else" },
{ type: "command", command: "claude-mailbox check --name bob --hook" },
],
},
],
},
};
applyUninstall(s);
const hooks = s.hooks as { UserPromptSubmit: { hooks: { command: string }[] }[] };
expect(hooks.UserPromptSubmit[0]!.hooks).toHaveLength(1);
expect(hooks.UserPromptSubmit[0]!.hooks[0]!.command).toBe("echo something-else");
});
it("returns not-present when there is nothing to remove", () => {
const s: Record<string, unknown> = {
hooks: { UserPromptSubmit: [{ matcher: "", hooks: [{ type: "command", command: "x" }] }] },
};
const r = applyUninstall(s);
expect(r).toEqual({ changed: false, reason: "not-present" });
});
it("removes hooks installed with --url arg", () => {
const s: Record<string, unknown> = {};
applyInstall(s, "claude-mailbox check --name bob --hook --url http://x");
applyUninstall(s);
expect(s.hooks).toBeUndefined();
});
});
describe("parseHookStdin", () => {
it("returns null for empty or whitespace input", () => {
expect(parseHookStdin(null)).toBeNull();
expect(parseHookStdin("")).toBeNull();
expect(parseHookStdin(" \n ")).toBeNull();
});
it("returns null for non-JSON input", () => {
expect(parseHookStdin("not json")).toBeNull();
expect(parseHookStdin("{")).toBeNull();
});
it("returns null for JSON primitives (only objects allowed)", () => {
expect(parseHookStdin("42")).toBeNull();
expect(parseHookStdin("\"foo\"")).toBeNull();
expect(parseHookStdin("null")).toBeNull();
});
it("parses a hook payload", () => {
const out = parseHookStdin(
JSON.stringify({
session_id: "abc12345-de67-89f0-1234-567890abcdef",
hook_event_name: "UserPromptSubmit",
prompt: "hi",
}),
);
expect(out?.session_id).toBe("abc12345-de67-89f0-1234-567890abcdef");
expect(out?.hook_event_name).toBe("UserPromptSubmit");
});
});
describe("shortSessionId", () => {
it("takes first 8 hex chars from a UUID", () => {
expect(shortSessionId("abc12345-de67-89f0-1234-567890abcdef")).toBe("abc12345");
});
it("normalizes case and ignores hyphens", () => {
expect(shortSessionId("ABC12345-DE67-89F0-1234-567890ABCDEF")).toBe("abc12345");
});
it("falls back to a sanitized prefix for non-hex ids", () => {
expect(shortSessionId("session-Test123")).toBe("sessiont");
});
});
describe("sanitizeProjectName", () => {
it("lowercases and replaces non-alnum with dashes", () => {
expect(sanitizeProjectName("My Project!")).toBe("my-project");
});
it("collapses runs of separators", () => {
expect(sanitizeProjectName("foo __ bar")).toBe("foo-bar");
});
it("trims leading/trailing dashes", () => {
expect(sanitizeProjectName("--foo--")).toBe("foo");
});
it("returns empty for purely non-alnum input", () => {
expect(sanitizeProjectName("---")).toBe("");
expect(sanitizeProjectName("")).toBe("");
expect(sanitizeProjectName(null)).toBe("");
expect(sanitizeProjectName(undefined)).toBe("");
});
it("caps long names", () => {
const out = sanitizeProjectName("a".repeat(120));
expect(out.length).toBeLessThanOrEqual(40);
});
});
describe("deriveProjectName", () => {
it("uses cwd basename when not in a git repo", () => {
// tmpdir is virtually never inside a git repo; basename is platform-dependent.
const got = deriveProjectName(tmpdir());
expect(got).toMatch(/^[a-z0-9-]+$/);
});
it("falls back to 'claude' when cwd is empty", () => {
expect(deriveProjectName("")).toBe("claude");
expect(deriveProjectName(null)).toBe("claude");
expect(deriveProjectName(undefined)).toBe("claude");
});
it("uses git toplevel basename when called from inside a repo", () => {
// The test harness itself runs inside the claude-mailbox checkout.
let inRepo = false;
try {
execFileSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: "pipe" });
inRepo = true;
} catch {
inRepo = false;
}
if (!inRepo) return; // CI without git in PATH — skip.
const got = deriveProjectName(process.cwd());
// Anywhere in the repo, we should resolve to the repo's basename — sanitized.
expect(got).toMatch(/^[a-z0-9-]+$/);
expect(got.length).toBeGreaterThan(0);
});
});
describe("deriveSessionName", () => {
it("composes <project>-<short>", () => {
const got = deriveSessionName("abc12345-de67-89f0-1234-567890abcdef", "");
expect(got).toBe("claude-abc12345");
});
it("derives different names for different sessions in the same project", () => {
const a = deriveSessionName("aaaa1111-de67-89f0-1234-567890abcdef", "");
const b = deriveSessionName("bbbb2222-de67-89f0-1234-567890abcdef", "");
expect(a).not.toBe(b);
});
});
describe("formatActivePeerList", () => {
const NOW = new Date("2026-05-19T12:00:00.000Z").getTime();
const peer = (name: string, isoOffsetMinutes: number): PeerEntry => ({
name,
lastSeenAt: new Date(NOW - isoOffsetMinutes * 60_000).toISOString(),
});
it("excludes self from the list", () => {
const out = formatActivePeerList(
[peer("self", 1), peer("alice", 1)],
"self",
{ windowMinutes: 60, maxPeers: 10, now: NOW },
);
const joined = out.join("\n");
expect(joined).not.toContain("self");
expect(joined).toContain("alice");
});
it("filters out peers older than the window", () => {
const out = formatActivePeerList(
[peer("recent", 5), peer("stale", 120)],
"self",
{ windowMinutes: 60, maxPeers: 10, now: NOW },
);
const joined = out.join("\n");
expect(joined).toContain("recent");
expect(joined).not.toContain("stale");
expect(out[0]).toContain("1 of 2 total");
});
it("returns a no-peers message when nothing is active", () => {
const out = formatActivePeerList(
[peer("ancient", 9999)],
"self",
{ windowMinutes: 60, maxPeers: 10, now: NOW },
);
expect(out).toHaveLength(1);
expect(out[0]).toMatch(/No other mailboxes seen within the last 60 minutes/);
expect(out[0]).toContain("1 total registered");
});
it("caps at maxPeers and sorts most-recent first", () => {
const out = formatActivePeerList(
[peer("p1", 30), peer("p2", 20), peer("p3", 10)],
"self",
{ windowMinutes: 60, maxPeers: 2, now: NOW },
);
const joined = out.join("\n");
expect(joined).toContain("p3");
expect(joined).toContain("p2");
expect(joined).not.toContain("p1");
expect(out[0]).toContain("2 of 3 total");
expect(joined.indexOf("p3")).toBeLessThan(joined.indexOf("p2"));
});
it("ignores peers with invalid lastSeenAt", () => {
const out = formatActivePeerList(
[{ name: "garbage", lastSeenAt: "not-a-date" }, peer("ok", 5)],
"self",
{ windowMinutes: 60, maxPeers: 10, now: NOW },
);
const joined = out.join("\n");
expect(joined).toContain("ok");
expect(joined).not.toContain("garbage");
});
});
describe("readSettings / writeSettings roundtrip", () => {
it("survives an install → write → read cycle", () => {
const dir = mkdtempSync(join(tmpdir(), "claude-mailbox-hook-"));
try {
const path = join(dir, "settings.json");
const s = readSettings(path);
expect(s).toEqual({});
applyInstall(s, "claude-mailbox check --name bob --hook");
writeSettings(path, s);
const reloaded = readSettings(path);
expect(reloaded.hooks?.UserPromptSubmit?.[0]?.hooks[0]?.command).toBe(
"claude-mailbox check --name bob --hook",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("creates parent .claude directory when missing", () => {
const dir = mkdtempSync(join(tmpdir(), "claude-mailbox-hook-"));
try {
const path = join(dir, "nested", ".claude", "settings.json");
writeSettings(path, { hooks: {} });
expect(readFileSync(path, "utf8")).toContain('"hooks"');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("preserves non-hook settings keys", () => {
const dir = mkdtempSync(join(tmpdir(), "claude-mailbox-hook-"));
try {
const path = join(dir, "settings.json");
mkdirSync(dir, { recursive: true });
writeFileSync(
path,
JSON.stringify({ model: "sonnet", permissions: { allow: ["Bash"] } }, null, 2),
);
const s = readSettings(path);
applyInstall(s, "claude-mailbox check --name bob --hook");
writeSettings(path, s);
const reloaded = readSettings(path) as {
model?: string;
permissions?: { allow?: string[] };
hooks?: unknown;
};
expect(reloaded.model).toBe("sonnet");
expect(reloaded.permissions?.allow).toEqual(["Bash"]);
expect(reloaded.hooks).toBeDefined();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

44
node/tests/mcp.test.ts Normal file
View File

@@ -0,0 +1,44 @@
import { describe, it, expect } from "vitest";
import { resolveIdentity } from "../src/mcp.js";
function fakeExtra(header?: string): unknown {
if (header === undefined) return {};
return { requestInfo: { headers: { "x-mailbox": header } } };
}
describe("resolveIdentity", () => {
it("prefers the explicit argument when present", () => {
expect(resolveIdentity("alice", fakeExtra("bob"), "from")).toBe("alice");
});
it("falls back to X-Mailbox header when arg missing", () => {
expect(resolveIdentity(undefined, fakeExtra("bob"), "from")).toBe("bob");
});
it("trims whitespace from explicit arg and header", () => {
expect(resolveIdentity(" alice ", fakeExtra(), "from")).toBe("alice");
expect(resolveIdentity(undefined, fakeExtra(" bob "), "name")).toBe("bob");
});
it("treats empty arg as missing and falls back", () => {
expect(resolveIdentity("", fakeExtra("bob"), "name")).toBe("bob");
expect(resolveIdentity(" ", fakeExtra("bob"), "name")).toBe("bob");
});
it("throws with a helpful message when neither is provided", () => {
expect(() => resolveIdentity(undefined, fakeExtra(), "from")).toThrow(
/Pass `from`.*SessionStart announcement/i,
);
});
it("throws referencing the correct arg name", () => {
expect(() => resolveIdentity(undefined, fakeExtra(), "name")).toThrow(
/Pass `name`/,
);
});
it("handles extra without requestInfo", () => {
expect(() => resolveIdentity(undefined, {}, "from")).toThrow(/Pass `from`/);
expect(() => resolveIdentity(undefined, null, "from")).toThrow(/Pass `from`/);
});
});

View File

@@ -94,6 +94,63 @@ describe("REST surface", () => {
expect(wrong.status).toBe(403);
});
it("POST /v1/rename transfers pending messages and exposes the new name", async () => {
// alice sends to bob-old.
await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" },
body: { to: "bob-old", body: "hi old bob" },
});
const rename = await call("POST", "/v1/rename", {
headers: { "X-Mailbox": "bob-old" },
body: { to: "bob-new" },
});
expect(rename.status).toBe(200);
expect(rename.body).toMatchObject({
from: "bob-old",
to: "bob-new",
messagesTransferred: 1,
});
// Peek under new name shows the pending msg; old name is empty.
const peekNew = await call("GET", "/v1/peek?name=bob-new");
expect(peekNew.body).toMatchObject({ pending: 1 });
const peekOld = await call("GET", "/v1/peek?name=bob-old");
expect(peekOld.body).toMatchObject({ pending: 0 });
// check-inbox under new name pulls the message.
const check = await call("POST", "/v1/check-inbox?name=bob-new", {
headers: { "X-Mailbox": "bob-new" },
});
const arr = check.body as Array<{ from: string; body: string }>;
expect(arr).toHaveLength(1);
expect(arr[0]!.body).toBe("hi old bob");
});
it("POST /v1/rename returns 409 when target name is taken", async () => {
await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" },
body: { to: "bob", body: "x" },
});
// 'taken' already exists thanks to upsert on X-Mailbox.
const r = await call("POST", "/v1/rename", {
headers: { "X-Mailbox": "bob" },
body: { to: "alice" },
});
expect(r.status).toBe(409);
expect(r.body).toMatchObject({ reason: "target-exists" });
});
it("POST /v1/rename requires X-Mailbox and body.to", async () => {
const missingHeader = await call("POST", "/v1/rename", { body: { to: "x" } });
expect(missingHeader.status).toBe(400);
const missingTo = await call("POST", "/v1/rename", {
headers: { "X-Mailbox": "alice" },
body: {},
});
expect(missingTo.status).toBe(400);
});
it("/v1/list and /v1/peek are anonymous", async () => {
await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" },

View File

@@ -0,0 +1,11 @@
{
"name": "claude-mailbox",
"version": "1.4.0",
"description": "Auto-checks the local Claude-Mailbox daemon before every prompt and after each subagent run, and injects pending messages into the conversation context.",
"author": {
"name": "Mika Kuns"
},
"homepage": "https://git.kuns.dev/releases/ClaudeMailbox",
"license": "MIT",
"keywords": ["mailbox", "ipc", "coordination", "mcp"]
}

9
plugin/.mcp.json Normal file
View File

@@ -0,0 +1,9 @@
{
"mcpServers": {
"mailbox": {
"type": "stdio",
"command": "claude-mailbox",
"args": ["mcp-stdio"]
}
}
}

92
plugin/README.md Normal file
View File

@@ -0,0 +1,92 @@
# claude-mailbox plugin
Lets Claude Code pull unread messages from a local `claude-mailbox` daemon before every prompt and inject them into the conversation context. Each Claude session gets a **unique mailbox identity** auto-derived from its session id, so two sessions in the same project never collide.
## Setup (three prompts, all inside Claude Code)
```
/plugin marketplace add https://git.kuns.dev/releases/ClaudeMailbox.git
/plugin install claude-mailbox@claude-mailbox
/claude-mailbox:mailbox-doctor
```
The doctor walks the rest:
1. installs the `claude-mailbox` binary via `npm install -g @kuns/claude-mailbox` if missing (asks first)
2. registers the daemon for autostart and starts it if needed
3. health-probes `http://127.0.0.1:37849/health`
4. runs a self → self smoke test
After that, every prompt auto-pulls unread messages.
## Mailbox identity (the important bit)
Each Claude Code session gets its own mailbox name, automatically derived as `<project>-<session-short>`:
| Where the session runs | Resulting mailbox name |
|---|---|
| Inside a git repo | `<repo-basename>-a8b3c1d2` (e.g. `claude-mailbox-a8b3c1d2`) |
| Outside a git repo | `<cwd-basename>-a8b3c1d2` |
| No cwd in stdin (rare) | `claude-a8b3c1d2` |
So if you open two Claude Code sessions in the same project, they'll share the project prefix but differ in the session-short — e.g. `claude-mailbox-a8b3c1d2` and `claude-mailbox-d4e5f6a7`. No env-var, no manual prefix step.
If a session focuses on a sub-area (frontend, backend, …), Claude can call `mcp__mailbox__rename(current_name="…", new_name="claude-mailbox-frontend-a8b3c1d2")` to tag itself; pending messages are transferred. Peers using the old name re-discover via `list_mailboxes`.
The `SessionStart` hook announces the current session's mailbox name in the conversation context on startup. Peers discover each other via `claude-mailbox list` or the `mcp__mailbox__list_mailboxes` MCP tool.
## What the hooks do
| Hook | Command | Effect |
|---|---|---|
| `SessionStart` | `claude-mailbox session-announce` | Registers the session with the daemon, then prints (a) this session's mailbox name, (b) the exact `from` / `name` args to pass to MCP tools, and (c) a list of other mailboxes active in the last hour — so Claude knows who's around without needing to call `list_mailboxes` first. |
| `UserPromptSubmit` | `claude-mailbox check --hook` | Pulls unread messages for the session's mailbox and injects them as context. Silent on empty inbox; emits a one-line setup hint when the daemon is unreachable. |
| `SubagentStop` | `claude-mailbox check --hook` | Same as `UserPromptSubmit`, but fires when a subagent finishes (Task tool). Lets the parent see peer messages that arrived during a long-running subagent run, instead of waiting until the next user prompt. |
Cost: one local HTTP round-trip per prompt and per subagent stop + Node coldstart (~100ms on Windows).
## MCP tools
The plugin ships a `.mcp.json` that spawns a **stdio MCP wrapper** (`claude-mailbox mcp-stdio`) so the daemon URL is configurable per machine via the `CLAUDE_MAILBOX_URL` env var (Claude Code doesn't yet support env substitution in HTTP MCP URLs — see issue #46889). The wrapper proxies tool calls to the daemon's REST API.
Each MCP tool takes the caller's mailbox name as an explicit argument (from the SessionStart announcement):
| Tool | Required args | Purpose |
|---|---|---|
| `mcp__mailbox__send` | `from`, `to`, `body` | Send a message to another mailbox. |
| `mcp__mailbox__check_inbox` | `name` | Pull all undelivered messages for your mailbox (marks delivered). |
| `mcp__mailbox__peek_inbox` | `name` | Non-consuming count of pending messages. |
| `mcp__mailbox__list_mailboxes` | `name` | Discover known mailboxes and `pendingForYou` counts. |
| `mcp__mailbox__rename` | `current_name`, `new_name` | Rename your own mailbox (e.g. add an area tag). Pending messages are transferred. Use the new name afterward. |
The SessionStart announcement spells out the exact args to pass, so Claude picks them up automatically.
## Slash commands
| Command | What it does |
|---|---|
| `/claude-mailbox:mailbox-doctor` | Diagnose + auto-fix the full setup. |
| `/claude-mailbox:mailbox-status` | Read-only health check. No changes. |
| `/claude-mailbox:mailbox-update` | Update the daemon to the latest npm version and restart it. |
## Coordinating two Claude Code sessions
1. Open two Claude Code sessions in the same (or different) project.
2. Each session's SessionStart hook registers itself with the daemon and prints both its own mailbox name and the **list of currently active peers** into context.
3. In session A you can simply say: *"I started a second session, coordinate with it."* Because the peer's mailbox name is already in context, Claude can call `mcp__mailbox__send(from="<my-name>", to="<peer-name>", body="...")` straight away — no manual `list_mailboxes` step needed.
4. Session B's `UserPromptSubmit` hook pulls the message on its next prompt and injects it as context.
You can also send from any shell:
```sh
claude-mailbox list
claude-mailbox send --from probe --to backend-a8b3c1d2 --body "hi"
```
## Uninstall
```
/plugin uninstall claude-mailbox@claude-mailbox
npm uninstall -g @kuns/claude-mailbox
claude-mailbox uninstall-autostart # if you registered it
```

View File

@@ -0,0 +1,123 @@
---
description: Diagnose and auto-fix the Claude-Mailbox setup (Node version, binary install, port-conflict detection, daemon autostart, smoke test, optional base-prefix).
allowed-tools: Bash, Read, Edit, Write
---
You are running the **Claude-Mailbox doctor**. Walk through these checks in order. After each step, print a one-line `✓` / `✗` with the action you took. End with a summary block.
Use `Bash` only for `claude-mailbox` subcommands, `npm`, `node`, `where`/`which`, and HTTP probes. Use `Read`/`Edit`/`Write` for `.claude/settings.json` and `mailbox.json`. Never run `sudo` automatically — if elevation is needed, stop and ask.
## Step 1 — Node.js version
Run: `node --version`
claude-mailbox uses Node's built-in `node:sqlite` and therefore requires **Node 24 or newer**. Parse the major version from the output.
- **Major ≥ 24** → ✓ record the version, continue.
- **Major == 22 or 23** → ✗ Stop. `node:sqlite` is experimental on these and requires `--experimental-sqlite`. Print:
> Found Node `<X.Y.Z>`. claude-mailbox needs Node 24 LTS or newer. Install via `nvm install 24 && nvm use 24` (or `nvs` / `winget install OpenJS.NodeJS.LTS` on Windows), then re-run the doctor.
- **Major < 22** → ✗ Stop with the same message; this Node is end-of-life.
- **Major ≥ 26** with `better-sqlite3` still installed globally from a previous version → just note: "Node `<X.Y.Z>` is fine for the current claude-mailbox (no native deps); ignore any old `better-sqlite3` build warnings from a prior install."
If `node --version` itself fails (`command not found`), stop and tell the user to install Node 24+ first.
## Step 2 — daemon binary on PATH
Run: `claude-mailbox --version`
- **Exit 0** → ✓ record the version. Continue.
- **Command not found** → binary missing. Install path:
| Platform | Command |
|---|---|
| Windows | `npm install -g @kuns/claude-mailbox` (no admin) |
| macOS / Linux | `npm install -g @kuns/claude-mailbox` (may fail with EACCES — never run sudo automatically; ask the user) |
Prerequisite: `npm config get @kuns:registry` must point at `https://git.kuns.dev/api/packages/releases/npm/`. If not:
```
npm config set @kuns:registry=https://git.kuns.dev/api/packages/releases/npm/
```
After install, re-run `claude-mailbox --version`. If it still fails, stop and report.
## Step 3 — port-conflict check (before autostart!)
Default port is 37849. Probe whether anything is already on it:
```
curl -sf http://127.0.0.1:37849/health
```
- **Returns a JSON body with `"status":"ok"` and a `version` field that matches `claude-mailbox --version`** → it's already our daemon, ✓ skip to Step 5.
- **Returns 200 with `"status":"ok"` but a different `version`** → it's an older claude-mailbox; treat as running, ✓.
- **Returns non-200, non-JSON, or any other foreign response** → **port conflict**. Some other process owns 37849.
- **Connection refused** → port is free, ✓ continue to Step 4.
If port conflict detected:
1. Tell the user which process holds the port (Windows: `Get-NetTCPConnection -LocalPort 37849 | Select-Object OwningProcess`, then `Get-Process -Id <pid>`; macOS/Linux: `lsof -i :37849`).
2. Pick a free port. Default suggestion: **47900**. Verify it's free: `curl -sf http://127.0.0.1:47900/health` should fail with connection refused.
3. Read `~/.claude-mailbox/mailbox.json` (create empty `{}` if missing) and merge `{"port": <chosen>}`. Write back.
4. Also write the override into `.claude/settings.json` env so the plugin's hooks find the right URL:
```json
"env": { "CLAUDE_MAILBOX_URL": "http://127.0.0.1:<chosen>" }
```
Merge into existing env, preserving other keys.
5. Mark `restart_needed = true`.
## Step 4 — daemon autostart and running state
Run: `claude-mailbox status`
- `Running` → ✓ continue.
- `Stopped` → `claude-mailbox start`, re-check.
- `NotInstalled` → `claude-mailbox install-autostart`, then `claude-mailbox start`, re-check.
**Behavior on `install-autostart`:** The CLI tries a Scheduled Task first (`schtasks /RL LIMITED`, no admin). If Windows Group Policy returns "Access is denied", it falls back transparently to an `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` registry entry plus a hidden `node serve` process — same per-user persistence, no admin needed. The chosen mechanism is recorded in `~/.claude-mailbox/autostart-mode` and respected by `status`/`start`/`stop`/`uninstall-autostart`.
If `install-autostart` still fails after both attempts (very rare — would mean both `schtasks` and `reg add` are blocked), stop and report what `status` and `start` printed.
## Step 5 — health probe
Hit `http://127.0.0.1:<port>/health` (use the configured port, not necessarily 37849). Expect a JSON body with `"status":"ok"` AND a `version` matching `claude-mailbox --version`. If unreachable or version mismatch, stop and report.
## Step 6 — mailbox identity
**No prompt.** Each Claude Code session gets a unique mailbox name auto-derived as `<project>-<short_session_id>`, where `<project>` is the git-repo basename of the session's `cwd` (or the cwd basename if not a git repo). Example: `claude-mailbox-a8b3c1d2`.
✓ "Mailbox name will be auto-derived as `<project>-<short_session_id>`."
Sessions can also rename themselves at runtime via the `mcp__mailbox__rename` MCP tool — e.g. to add an area tag like `claude-mailbox-frontend-a8b3c1d2`. No config involved.
## Step 7 — smoke test
Use two ephemeral names — we don't need the real session name here:
```
claude-mailbox send --from doctor-probe-a --to doctor-probe-b --body "ping from doctor"
claude-mailbox check --name doctor-probe-b
```
(If the port was changed in Step 3, pass `--url http://127.0.0.1:<port>` to both.)
The `check` output must be a JSON array with one message: `from: doctor-probe-a`, body matches. ✓ on success, ✗ otherwise.
## Step 8 — summary
```
Claude-Mailbox doctor
node: <version>
binary: <version>
daemon: Running (port: <port>, what you did if anything)
health: ok
port conflict: none | resolved (moved from 37849 to <port>)
base prefix: <name from settings, or "auto-derived (anonymous)">
smoke test: passed | failed
restart hint: yes if restart_needed, otherwise no
```
End with one of:
- All ✓ and no restart needed → "Setup is healthy. Your mailbox name this session will be revealed by the SessionStart hook on next session start."
- All ✓ and restart needed → "Restart Claude Code (or open a new session) so the SessionStart hook picks up the new env values."
- Anything ✗ → "Setup incomplete: <first failure>."

View File

@@ -0,0 +1,23 @@
---
description: Read-only Claude-Mailbox health check. No changes, no installs — just report.
allowed-tools: Bash, Read
---
Report the Claude-Mailbox setup status without making any changes. If something is wrong, **tell** the user but **do not** fix it — suggest `/claude-mailbox:mailbox-doctor` for that.
Print exactly this block, filling in each line:
```
Claude-Mailbox status
binary: <output of `claude-mailbox --version`, or "not installed">
daemon: <output of `claude-mailbox status`>
health: <"ok" if GET http://127.0.0.1:37849/health returns 200, else "unreachable">
mailbox name: auto-derived per session as <project>-<short-session-id> (see SessionStart announcement)
pending: n/a (the session's mailbox name isn't known until SessionStart runs in this session's context)
```
End with one line:
- All good → `Status: OK`
- Missing daemon → `Status: Setup incomplete. Run /claude-mailbox:mailbox-doctor to fix.`
- Daemon installed but stopped → `Status: Daemon is not running. Try \`claude-mailbox start\` or run /claude-mailbox:mailbox-doctor.`

View File

@@ -0,0 +1,56 @@
---
description: Update the Claude-Mailbox daemon to the latest published npm version and restart it.
allowed-tools: Bash
---
You are running the **Claude-Mailbox update** command. Update the `@kuns/claude-mailbox` npm package and restart the daemon. Never run `sudo` automatically — if elevation is needed, stop and ask.
## Step 1 — current version
Run: `claude-mailbox --version`
- Exit 0 → record the version string as `CURRENT`.
- Non-zero → tell the user the daemon binary is not installed yet. Suggest `/claude-mailbox:mailbox-doctor` to do a full setup and stop.
## Step 2 — latest published version
Run: `npm view @kuns/claude-mailbox version`
If the npm registry config is missing, the call may fail with a 404. Fall back to:
```
npm view --registry=https://git.kuns.dev/api/packages/releases/npm/ @kuns/claude-mailbox version
```
Record the result as `LATEST`.
## Step 3 — compare
- If `CURRENT === LATEST`: print "Already up to date (vX.Y.Z)." and stop. Do not run any further steps.
- Otherwise: tell the user `CURRENT``LATEST` and ask for confirmation before proceeding.
## Step 4 — perform the update
On user confirmation, run these in order. Stop on the first failure and report it:
1. `claude-mailbox stop`
2. `npm install -g @kuns/claude-mailbox@latest`
- On Linux/macOS this may fail with EACCES. **Do not run sudo automatically.** Ask the user how they want to proceed (e.g., `sudo npm install -g …`, or switch to a user-scoped Node setup with nvm/fnm).
3. `claude-mailbox start`
4. `claude-mailbox --version` to verify the upgrade landed.
5. `claude-mailbox status` to verify the daemon is `Running`.
## Step 5 — summary
Print exactly this block:
```
Claude-Mailbox update
previous version: <CURRENT>
new version: <whatever --version now reports>
daemon: Running | Stopped | NotInstalled
pending messages survived: <count of messages still in inbox via `claude-mailbox list`, if applicable>
```
If the new version matches `LATEST` and daemon is `Running`, end with: "Update complete."
Otherwise, end with the first thing that went wrong.

34
plugin/hooks/hooks.json Normal file
View File

@@ -0,0 +1,34 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "claude-mailbox session-announce"
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "claude-mailbox check --hook"
}
]
}
],
"SubagentStop": [
{
"hooks": [
{
"type": "command",
"command": "claude-mailbox check --hook"
}
]
}
]
}
}

View File

@@ -5,7 +5,7 @@ namespace ClaudeMailbox.Cli;
public static class ClientCommands
{
private const string DefaultUrl = "http://127.0.0.1:47822";
private const string DefaultUrl = "http://127.0.0.1:37849";
public static async Task<int> RunAsync(string[] args)
{

View File

@@ -61,7 +61,7 @@ public static class ServiceCommands
if (!File.Exists(configPath))
{
var portStr = ClientCommands.GetOption(args, "--port");
var port = int.TryParse(portStr, out var p) ? p : 47822;
var port = int.TryParse(portStr, out var p) ? p : 37849;
var bind = ClientCommands.GetOption(args, "--bind") ?? "127.0.0.1";
var dbPath = ClientCommands.GetOption(args, "--db-path") ?? defaultDbPath;

View File

@@ -2,7 +2,7 @@ namespace ClaudeMailbox.Config;
public sealed class DaemonConfig
{
public const int DefaultPort = 47822;
public const int DefaultPort = 37849;
public const string DefaultBindAddress = "127.0.0.1";
public int Port { get; init; } = DefaultPort;