Skip to main content
Glama

bot-relay-mcp

CI Tether on VSCode Marketplace

A local-first coordination bus for AI coding agents. Durable inboxes, task queues, and wakeups for Claude Code, Cursor, Cline, Codex-style CLIs, scripts, and webhooks. Two interfaces, one shared SQLite database, zero infrastructure.

Dozens of MCP tools. The headline feature is hands-free, LLM-agnostic autowake: agents running on different models (Claude Code, Codex) wake on relay mail and coordinate as a team without manual polling, via the Tether VSCode extension plus a durable cross-process outbox, so an inbox change in one process wakes subscribers in another. See the CHANGELOG for the full phase-by-phase arc.

What is this?

bot-relay-mcp gives AI coding agents and external systems a way to coordinate.

Two audiences, two transports:

  • AI coding agents (Claude Code, Cursor, Cline, Zed) connect via stdio MCP. Drop one entry into ~/.claude.json and the relay's tools appear inside Claude. No daemon required.

  • External systems (n8n, Slack, Telegram, custom scripts) connect via HTTP+SSE with optional Bearer auth. Trigger agent actions or receive webhook events.

Everything reads and writes the same SQLite file at ~/.bot-relay/relay.db. There is no cloud, no daemon you have to install, no service mesh.

Related MCP server: aichat-mcp

Why not just use Claude Agent Teams?

Fair question. Claude Code v2.1.32 shipped Agent Teams — native multi-agent coordination inside Claude. If your setup is Claude-only and stays that way, use it. It's the right tool.

bot-relay-mcp solves a different problem: coordination across a heterogeneous LLM stack. The tools your agents run on probably aren't all Claude. You might have Claude Code terminals for architecture work, Codex or Cursor on a different repo, an n8n workflow firing webhooks, a background Python process polling results, a Telegram bot forwarding alerts. Agent Teams coordinates Claude with Claude. bot-relay-mcp coordinates whatever speaks MCP (or plain HTTP) with whatever else does.

Three things it does that a vendor-native solution can't:

  • LLM-agnostic. Any MCP client — Claude Code, Cursor, Cline, Zed — registers and talks to any other. Non-MCP systems join over the HTTP+SSE transport with optional Bearer auth. No client is privileged.

  • Self-hosted. Everything lives in a single SQLite file on your machine. No cloud account, no control plane, no vendor lock-in. The HTTP daemon is optional; stdio-only works offline.

  • Federation-bound (v2.3 roadmap). Hub/edge federation is on the locked plan so multiple self-hosted relays can mesh without collapsing into one shared namespace. Teams of teams, across orgs, without routing through someone else's service.

It's also a durable bus, not an in-process coordinator. Messages, tasks, and channels survive individual agent sessions — restart a terminal, spawn a fresh one, come back tomorrow; the state is still there.

If your stack is Claude-only and stays that way, use Agent Teams. If it isn't, or if you want a self-hosted bus that survives individual sessions, that's what bot-relay-mcp is for.

Quick Start (30 seconds)

The relay is published on npm — setup is a single config entry, no cloning, no compiling, no absolute paths.

Add to your ~/.claude.json:

{
  "mcpServers": {
    "bot-relay": {
      "command": "npx",
      "args": ["-y", "bot-relay-mcp"],
      "type": "stdio"
    }
  }
}

The first invocation fetches the package and starts the server. Subsequent launches are instant.

Get hands-free autowake (the headline feature)

The Quick Start above gives you the full toolset and manual coordination — you ask an agent to check my messages. The hands-free autowake headline (agents wake themselves on new mail) needs two more, both optional:

  1. The Tether VSCode extension — code --install-extension lumiere-ventures.bot-relay-tether — wakes the agent's terminal when mail arrives. Outside VSCode, use relay watch <agent> (Sentinel) instead.

  2. The keep-alive HTTP daemon + SessionStart hooks, which deliver cross-process wakes (a message from one terminal waking a subscriber in another). Install them with relay init. From an npm install, npm install -g bot-relay-mcp puts relay on your PATH, then relay init (idempotent, never touches your tokens; --skip-daemon / --skip-hooks opt out). See docs/getting-started.md and the security note below — and on Linux/Windows the daemon is not yet supervised (start it manually; see docs/cross-platform-spawn.md).

Quick Start (from source)

git clone https://github.com/Maxlumiere/bot-relay-mcp.git
cd bot-relay-mcp
npm install
npm run build

One-command setup (relay init)

After building, run the installer:

./bin/relay init

It reconciles your ~/.claude.json (mcpServers entry), ~/.claude/settings.json (SessionStart hook), and — on macOS — installs a keep-alive launchd daemon. It never touches your agent tokens, and re-running is always safe (idempotent). Use --config-only / --skip-hooks / --skip-daemon to opt out of any step.

⚠️ Security — the default is local-trust. A default relay init install has no HTTP secret: the relay binds to 127.0.0.1 and trusts every process on the same machine. Any local process can then reach the loopback HTTP surface — including the dashboard operator endpoints (/api/snapshot, set-status, wake-agent, kill-agent, operator-identity). Per-agent tokens protect who you can act as (you can't impersonate another agent), but they do not gate the whole surface. This is a reasonable boundary on a personal, single-user machine (a local process already has OS-level access to the same data), and non-loopback binds are still refused without a secret.

On a shared machine, or any non-loopback / team / remote setup, gate it: run relay init --secret <strong-random> (or export RELAY_DASHBOARD_SECRET). The daemon requires a secret to bind to any non-loopback host.

Alternatively, wire it up by hand — add to ~/.claude.json:

{
  "mcpServers": {
    "bot-relay": {
      "command": "node",
      "args": ["/absolute/path/to/bot-relay-mcp/dist/index.js"],
      "type": "stdio"
    }
  }
}

Open two Claude Code terminals and try it:

Terminal A:

> Register on the relay as "planner" with role "orchestrator"
> Discover other agents
> Send a message to "builder": "Can you handle the API layer?"

Terminal B:

> Register on the relay as "builder" with role "builder"
> Check my relay messages
> Reply to planner: "On it."

The database is created automatically at ~/.bot-relay/relay.db on first use. That is the full setup.

File permissions (v2.1). The relay creates ~/.bot-relay/ at 0700 and relay.db + backup tarballs at 0600 — owner-only. config.json is operator-managed; the relay never chmods it but logs a warning at startup if it's more permissive than 0600. POSIX only — native Windows NTFS uses ACLs, not POSIX modes, so the chmod calls are no-ops there (documented).

Tether (v2.5 + v2.7 cross-process delivery)

relay://inbox/<agent_name> is a subscribable MCP resource. Any MCP-aware client subscribes via the standard subscribe request and receives notifications/resources/updated pushes when the agent's inbox changes (new mail, broadcast, drain). No polling, standard MCP semantics.

v2.7 added cross-process delivery. A message sent from a stdio MCP terminal (one OS process) now wakes IDE subscribers connected to the HTTP daemon (a different OS process) via a durable inbox_events outbox table polled by the daemon. v2.5 only delivered events same-process — v2.7 is the load-bearing release for any Tether-style IDE integration.

The bundled VSCode extension ships on the marketplace:

code --install-extension lumiere-ventures.bot-relay-tether

Or browse marketplace.visualstudio.com/items?itemName=lumiere-ventures.bot-relay-tether. Source for the extension lives at extensions/vscode/ in this repo for users who want to build from source. The extension surfaces pending count + last-message recency in the status bar, opens a webview with the last message preview on click, and optionally auto-types inbox into the integrated terminal so Claude Code wakes up. See extensions/vscode/README.md for install + config.

Sentinel — relay watch (v2.18)

Tether is push-wake inside VSCode. Sentinel is wake-anywhere — the poll/marker-based sibling for agents not in VSCode: iTerm2 personas, plain terminals, remote SSH sessions.

relay watch <agent> [--interval S] [--once] [--json]

It stands watch over <agent>'s inbox and prints a wake line the moment new mail arrives, so a harness (or you) can nudge the agent to read it — the shipped replacement for a hand-rolled inbox-polling loop. When the daemon writes filesystem delivery markers (RELAY_FILESYSTEM_MARKERS=1), it waits on the marker via fs.watch (near-zero idle cost) with a slow fallback re-check so a dropped event is never a silent miss; otherwise it falls back to bounded polling. It reads the active per-instance DB directly under the local-trust boundary (no token), and --once / --json make it scriptable.

Tether = push-wake in VSCode; Sentinel = wake anywhere.

Tools

Identity

Tool

Inputs

Description

register_agent

name, role, capabilities[]

Register this terminal as a named agent. Uses upsert — safe to call multiple times.

unregister_agent

name

Remove an agent from the relay. Idempotent. Fires agent.unregistered webhook on success.

discover_agents

role (optional)

List all registered agents with status (online/offline/unknown).

spawn_agent

name, role, capabilities, cwd?, initial_message?

Spawn a new Claude Code terminal pre-configured as a relay agent. Cross-platform (v1.9): macOS (iTerm2/Terminal.app), Linux (gnome-terminal/konsole/xterm/tmux fallback chain — tmux covers headless servers), Windows (wt.exe/powershell.exe/cmd.exe). See docs/cross-platform-spawn.md.

Messaging

Tool

Inputs

Description

send_message

from, to, content, priority

Send a direct message to another agent by name.

get_messages

agent_name, status, limit

Check your mailbox. Pending messages are auto-marked as read.

broadcast

from, content, role (optional)

Send a message to all registered agents (or filter by role).

Tasks

Tool

Inputs

Description

post_task

from, to, title, description, priority

Assign a task to another agent.

post_task_auto (v2.0)

from, title, description, required_capabilities[], priority

Auto-route to the least-loaded agent whose capabilities match ALL required. Queues if no match; assigns on the next capable registration.

update_task

task_id, agent_name, action, result?

Actions: accept / complete / reject / cancel (v2.0, requester-only) / heartbeat (v2.0, renews lease). State machine + CAS enforced.

get_tasks

agent_name, role, status, limit

Query your task queue (assigned to you or posted by you).

get_task

task_id

Get a single task by ID with full details.

Channels (v2.0)

Tool

Inputs

Description

create_channel

name, description?, creator

Create a named channel for multi-agent coordination. Requires channels capability.

join_channel

channel_name, agent_name

Join any public channel.

leave_channel

channel_name, agent_name

Leave a channel.

post_to_channel

channel_name, from, content, priority

Post to a channel you are a member of.

get_channel_messages

channel_name, agent_name, limit, since?

Read messages posted to a channel since your join time.

Status + Health (v2.0)

Tool

Inputs

Description

set_status

agent_name, status

Signal online / busy / away / offline. busy/away exempt you from health-monitor task reassignment.

health_check

(none)

Report relay version, uptime, and live counts (agents, messages, tasks, channels). No auth required.

Webhooks (v1.2+)

Tool

Inputs

Description

register_webhook

url, event, filter, secret

Subscribe to relay events via HTTP POST.

list_webhooks

(none)

List all registered webhook subscriptions.

delete_webhook

webhook_id

Remove a webhook subscription.

Supported events: message.sent, message.broadcast, task.posted, task.accepted, task.completed, task.rejected, task.cancelled (v2.0), task.auto_routed (v2.0), task.health_reassigned (v2.0), channel.message_posted (v2.0), agent.unregistered, agent.spawned, webhook.delivery_failed, * (all).

v2.0 — retry with backoff. Failed webhook deliveries retry at 60s / 300s / 900s (3 attempts). CAS-claimed per row — no double delivery. Piggybacks on webhook-firing tool calls, no background thread.

When secret is provided, each delivery includes an X-Relay-Signature: sha256=... HMAC header. Filter optionally restricts firing to events where from_agent or to_agent matches.

Example: Task Delegation

Terminal A — Orchestrator:

1. register_agent("orchestrator", "planner", ["delegation", "review"])
2. discover_agents() → sees "worker" is online
3. post_task(from: "orchestrator", to: "worker",
     title: "Write auth tests",
     description: "Cover login, logout, token refresh. Use vitest.",
     priority: "high")
4. send_message(from: "orchestrator", to: "worker",
     content: "Task posted — check your queue.")

Terminal B — Worker:

1. register_agent("worker", "builder", ["testing", "backend"])
2. get_messages("worker") → message from orchestrator
3. get_tasks("worker", role: "assigned", status: "posted") → auth test task
4. update_task(task_id, "worker", "accept")
5. ... does the work ...
6. update_task(task_id, "worker", "complete", result: "12 tests passing")
7. send_message(from: "worker", to: "orchestrator",
     content: "Auth tests done. All passing.")

Terminal A checks results:

1. get_messages("orchestrator") → "Auth tests done."
2. get_task(task_id) → status: completed, result: "12 tests passing"

How It Works

Every Claude Code terminal spawns its own MCP server process via stdio. All processes read and write the same SQLite file at ~/.bot-relay/relay.db. SQLite WAL mode handles concurrent access safely. Messages older than 7 days and completed tasks older than 30 days are purged automatically on startup.

Unified relay CLI (v2.1)

One entry, six subcommands: doctor / init / test / generate-hooks / backup / restore. First-run setup:

relay init          # interactive
relay init --yes    # defaults + random HTTP secret

relay doctor runs a diagnostic sweep; relay test runs a minimal self-check against a throwaway relay; relay generate-hooks emits Claude Code hook JSON for ~/.claude/settings.json. Full reference in docs/cli.md. The standalone bin/relay-backup + bin/relay-restore from Phase 2c have been absorbed into relay backup + relay restore.

Token lifecycle (v2.1)

Two new tools for credential hygiene: rotate_token lets an agent swap its own token with history preserved; revoke_token lets an admin-capable agent nullify another agent's token_hash (target re-bootstraps via the Phase 2b migration path). New admin capability is never auto-granted — register admin agents explicitly. Full operator runbook in docs/token-lifecycle.md.

Error codes (v2.1)

Every tool error response carries a stable error_code token alongside the free-form error string. Branch on the code; never string-match the message. Full catalog + stability guarantee in docs/error-codes.md. Source of truth: src/error-codes.ts.

Protocol version (v2.1)

Beyond the package version string, the relay surfaces a protocol_version via register_agent + health_check responses. Clients should key compatibility on protocol_version (bumps only on tool-surface changes) rather than the package version (bumps on every ship). See docs/protocol-version.md for SemVer rules + a client-side compatibility snippet.

HTTP Mode — for n8n, Slack, Telegram, custom scripts

Run the relay as an HTTP daemon and any HTTP client can drive it:

RELAY_TRANSPORT=http RELAY_HTTP_SECRET=your-shared-secret node dist/index.js
# Listens on http://127.0.0.1:3777

Production deployment — set RELAY_HTTP_SECRET. v2.1 refuses to start on a non-loopback host (0.0.0.0, a public IP, Docker -p 3777:3777 without loopback pinning) unless RELAY_HTTP_SECRET is set. Loopback binds (127.0.0.1, ::1, localhost) stay zero-config for local development.

Dev-only escape hatch: RELAY_ALLOW_OPEN_PUBLIC=1 lets the relay start anyway on a public host without a secret — useful for throwaway local Docker nets, but logs a loud warning every startup. Never use in production.

Endpoints:

  • POST /mcp — JSON-RPC (the MCP protocol over HTTP+SSE). Requires Authorization: Bearer <secret> if http_secret is configured.

  • GET /health — server status (always open, no auth)

  • GET / — built-in dashboard (live view of agents, messages, tasks, webhooks). ADR-0006: protected by a Host-header allowlist (DNS-rebinding defense) + an auth gate (RELAY_DASHBOARD_SECRET or the dashboard_secret config, generated by default at relay init). Operator-power endpoints (kill-agent, wake-agent, set-status, …) require it regardless of network position. Loopback binds allow a restricted, secret-free read view; non-loopback binds require the secret. http_secret no longer authenticates the dashboard — that fallback was a removed privilege-escalation. Full policy in docs/dashboard-security.md.

  • GET /api/snapshot — JSON snapshot of relay state (same gates as /)

Three transport modes:

  • stdio (default) — per-terminal, for AI coding agents

  • http — daemon, for external systems

  • both — HTTP daemon plus a stdio connection (useful for bridge scripts)

All transports share the same SQLite database. Stdio agents and HTTP clients see the same world.

Process-boundary reminder (v2.1.3): stdio MCP clients and the HTTP daemon are separate processes. Each Claude Code terminal with "type":"stdio" in ~/.claude.json spawns its own node dist/index.js child. Restarting the :3777 HTTP daemon never affects stdio clients — their own child processes are untouched. Operator /mcp reconnect is only needed after restart for "type":"http" MCP clients pointed at the daemon URL. See docs/transport-architecture.md for the full topology + post-restart operator checklist.

n8n integration example

Trigger a Claude Code agent from an n8n workflow:

POST http://127.0.0.1:3777/mcp
Authorization: Bearer your-shared-secret
Content-Type: application/json

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "post_task",
    "arguments": {
      "from": "n8n-workflow-42",
      "to": "builder",
      "title": "Process new lead",
      "description": "Lead data: ...",
      "priority": "high"
    }
  }
}

Then register a webhook so n8n hears about completion:

{
  "jsonrpc": "2.0", "id": 2, "method": "tools/call",
  "params": {
    "name": "register_webhook",
    "arguments": {
      "url": "https://your-n8n.example.com/webhook/abc",
      "event": "task.completed",
      "secret": "shared-with-n8n"
    }
  }
}

When a task completes, n8n receives a POST with the result and an HMAC signature in X-Relay-Signature.

Config File (v1.2+)

Optional ~/.bot-relay/config.json:

{
  "transport": "http",
  "http_port": 3777,
  "http_host": "127.0.0.1",
  "webhook_timeout_ms": 5000,
  "http_secret": null,
  "trusted_proxies": []
}

Env vars override file config: RELAY_TRANSPORT, RELAY_HTTP_PORT, RELAY_HTTP_HOST, RELAY_HTTP_SECRET, RELAY_TRUSTED_PROXIES (comma-separated CIDRs).

Trusted Proxies and X-Forwarded-For (v1.6.2)

By default, the relay IGNORES the X-Forwarded-For header completely. Rate limits are keyed on the direct socket peer IP only. This prevents a caller from sending a spoofed header to get their own rate-limit bucket.

If you front the relay with Cloudflare, nginx, or any other reverse proxy, configure trusted_proxies with CIDRs of those proxies:

{
  "trusted_proxies": ["127.0.0.0/8", "::1/128", "10.0.0.0/8"]
}

Or via env var:

RELAY_TRUSTED_PROXIES="127.0.0.0/8,::1/128,10.0.0.0/8"

When the direct peer IP falls in the trusted list, the relay walks the X-Forwarded-For chain right-to-left, skipping trusted hops, and uses the leftmost-untrusted hop as the real client IP. This matches RFC 7239 §7.4 and how nginx/Express normally handle this.

Per-Agent Tokens (v1.7)

Every tool call (other than first-time register_agent and /health) requires an agent token. The token identifies WHO is calling — separate from and stronger than the shared HTTP secret, which only identifies a trusted network.

Issuing a token — first registration:

# The response returns `agent_token` ONCE. Save it.
{
  "jsonrpc": "2.0", "id": 1, "method": "tools/call",
  "params": {
    "name": "register_agent",
    "arguments": { "name": "builder", "role": "builder", "capabilities": ["tasks"] }
  }
}

The server stores only a bcrypt hash. The raw token is surfaced once in the response agent_token field and echoed to stderr as [auth] New agent_token issued for "builder". Save it: RELAY_AGENT_TOKEN=.... If you lose it, unregister_agent (auth'd) then re-register.

Presenting the token on every subsequent call — three ways:

  1. Arg field (works for stdio + HTTP):

    { "name": "send_message", "arguments": { "from": "builder", "to": "ops", "content": "hi", "agent_token": "..." } }
  2. HTTP header:

    X-Agent-Token: <token>
  3. Env var (stdio flow, also picked up by HTTP client wrappers):

    export RELAY_AGENT_TOKEN=<token>

Capabilities are set at first registration and are immutable (v1.7.1). To change an agent's capability set, call unregister_agent (with its token) then register_agent with the new capability list. Re-register attempts that change caps are ignored with a capabilities_note in the response.

Capability catalog:

  • spawn — required for spawn_agent

  • tasks — required for post_task, update_task

  • webhooks — required for register_webhook, list_webhooks, delete_webhook

  • broadcast — required for broadcast

  • All other tools are always allowed for any authenticated agent (no capability check).

Migration for pre-v1.7 agents (v2.1+): agents registered before v1.7 have no token hash. A register_agent call against such a row self-migrates — the relay detects the null hash, issues a fresh token, and the agent is first-class from that point on. No RELAY_ALLOW_LEGACY=1 required for the migration call itself. RELAY_ALLOW_LEGACY is still available as a coarser escape hatch for non-register tool calls against unmigrated legacy rows (e.g., if you want send_message to work before an agent has migrated); turn it OFF once all your agents have migrated.

Encryption at Rest (v1.7 opt-in; keyring + rotation in v2.1 Phase 4b.3)

Set the keyring to encrypt message/task/audit/webhook content fields in the SQLite database with AES-256-GCM. Three configuration sources (pick exactly one — multi-set is rejected at startup):

# 1. Inline JSON (for CI / secrets managers)
export RELAY_ENCRYPTION_KEYRING='{"current":"k1","keys":{"k1":"<base64-32>"}}'

# 2. File path (operator-friendly; chmod 600)
export RELAY_ENCRYPTION_KEYRING_PATH=~/.bot-relay/keyring.json

# 3. Legacy single-key (auto-wraps to { current: "k1", keys: { k1: <value> } }; deprecation warning at startup)
export RELAY_ENCRYPTION_KEY="<base64-32>"

# Generate a key:
openssl rand -base64 32
# or:
node -e 'console.log(require("crypto").randomBytes(32).toString("base64"))'

When the keyring is set, the relay transparently encrypts on write (with current key) and decrypts on read (with any key in the keyring). Every ciphertext carries an enc:<key_id>:... prefix so rows are self-describing. Legacy enc1:... rows (pre-Phase-4b.3 deployments) decrypt via RELAY_ENCRYPTION_LEGACY_KEY_ID (default k1).

Rotating keys (online)

Full runbook at docs/key-rotation.md. In summary:

  1. Add the new key to the keyring while keeping the old one (both decrypt; current still points to old).

  2. Flip current to the new key; restart. New writes use the new key.

  3. relay re-encrypt --from old_key_id --to new_key_id --yes — scans + migrates all existing rows across 5 encrypted columns. Resumable.

  4. relay re-encrypt --verify-clean old_key_id — exit 0 = safe to retire.

  5. Remove the old key from the keyring; restart.

Without the keyring set, content is stored plaintext (default, convenient for local dev).

Rotation Guide — HTTP Shared Secret (v1.7)

The RELAY_HTTP_SECRET shared secret can be rotated without downtime using a grace window:

Step 1 — promote the new secret as primary, keep the old as previous:

RELAY_HTTP_SECRET="new-secret-v2" \
RELAY_HTTP_SECRET_PREVIOUS="old-secret-v1" \
RELAY_TRANSPORT=http node dist/index.js

During this window, BOTH secrets are accepted. Requests using the old secret receive an X-Relay-Secret-Deprecated: true response header as a signal to upgrade.

Step 2 — update every client to present new-secret-v2 in their Authorization: Bearer … or X-Relay-Secret header.

Step 3 — watch for the deprecation header on your dashboard/logs until no more requests use the old secret.

Step 4 — drop the old secret:

RELAY_HTTP_SECRET="new-secret-v2" \
RELAY_TRANSPORT=http node dist/index.js    # RELAY_HTTP_SECRET_PREVIOUS unset

Multiple previous secrets are supported as a comma-separated list:

RELAY_HTTP_SECRET_PREVIOUS="v1-secret,v0-secret"

Secret comparisons are timing-safe (v1.7.1 — crypto.timingSafeEqual), so an attacker cannot recover the secret via byte-by-byte response-timing measurement.

Multi-machine: centralized deployment (v2.1)

bot-relay-mcp is LLM-agnostic, CLI-agnostic, and deployment-flexible. Pick the path that fits your setup:

Path A — Single-machine (default). Stdio transport, per-terminal process, zero infrastructure. Best for solo development on one laptop. No secrets, no reverse proxies, no ops — run npm install + add the stdio entry to your MCP client config and you're done. Covered throughout this README.

Path B — Multi-machine (centralized, v2.1 Phase 7r). One bot-relay-mcp hub on a VPS, multiple thin MCP clients connecting via HTTP. Agents on different machines can send_message, post tasks, subscribe to webhooks, and join channels through shared state. No new architecture — just the HTTP transport we've had since v1.2, packaged with a convenience CLI in v2.1.

When to pick centralized

  • Two or more machines in play (dev laptop + CI, work + personal, family devices)

  • AI agents running on different hosts that need to coordinate

  • Team environments where multiple people connect their MCP clients to a shared relay

Quick pair flow

On the hub (VPS, reachable at e.g. https://relay.example.com): install bot-relay-mcp, run under systemd with RELAY_TRANSPORT=http + RELAY_HTTP_SECRET, terminate TLS with Caddy/nginx. See docs/multi-machine-deployment.md for the worked VPS runbook.

On each client machine:

relay pair https://relay.example.com \
  --name "$(whoami)-$(hostname -s)" \
  --role operator \
  --capabilities spawn,tasks,webhooks,broadcast,channels \
  --secret-file ./hub.secret \
  --output ./bot-relay-client.json

hub.secret holds the hub's registration secret, which the hub operator finds at <relay instance dir>/secrets/mint.secret and hands over. relay pair never takes a secret on the command line. It probes the hub, registers this machine as an agent, and writes the MCP client config, with the agent's one-time token, to --output. That file is created 0600 and never overwrites an existing one; the terminal shows the config with its credentials redacted. Merge its bot-relay entry into ~/.claude.json / ~/.cursor/mcp.json / etc.; hooks read the token from that entry's X-Agent-Token header.

Verify after pairing:

relay doctor --remote https://relay.example.com

Expected: PASS on reachability + protocol compatibility + token auth + hub auth config.

Trust-model tradeoffs

  • Hub operator can read plaintext messages in RAM (even with RELAY_ENCRYPTION_KEY set, decryption happens server-side for routing)

  • Hub is a single point of failure for cross-machine coordination

  • Recommended for trusted groups (families, small teams, personal multi-machine setups)

  • NOT recommended for mutually distrustful parties sharing a single hub, or compliance-bound workloads where in-RAM access by the operator is a policy violation

See SECURITY.md §Centralized deployment trust model for the full posture + incident response playbook.

Bridge to other tools via MCP

bot-relay-mcp is MCP-compatible, so your MCP client can connect to both bot-relay-mcp AND other MCP servers (Slack, Discord, Matrix, email, etc.) simultaneously. That's an operator deployment choice — we don't integrate those into bot-relay-mcp. See docs/multi-machine-deployment.md §3 for the pattern.

Zero-Friction Setup

To skip approval prompts for relay tools, add this to your project's .claude/settings.json:

{
  "permissions": {
    "allow": [
      "mcp__bot-relay__register_agent",
      "mcp__bot-relay__discover_agents",
      "mcp__bot-relay__send_message",
      "mcp__bot-relay__get_messages",
      "mcp__bot-relay__broadcast",
      "mcp__bot-relay__post_task",
      "mcp__bot-relay__update_task",
      "mcp__bot-relay__get_tasks",
      "mcp__bot-relay__get_task",
      "mcp__bot-relay__register_webhook",
      "mcp__bot-relay__list_webhooks",
      "mcp__bot-relay__delete_webhook"
    ]
  }
}

Auto-Check on Session Start

Add a SessionStart hook so every terminal automatically checks the relay for pending messages when it opens. See docs/hooks.md for the full configuration.

Near-Real-Time Mail Delivery (v1.8)

The SessionStart hook only fires when a terminal opens. If an agent is actively working and mail arrives mid-session, it does not see the message until next startup (or a human pastes it in).

v1.8 adds a PostToolUse hook — hooks/post-tool-use-check.sh — that fires after every tool call, peeks at the mailbox, and injects a short notice as additionalContext (unread count, highest priority, sender names and the newest message's age; never any message content) so the running session knows to call get_messages. The hook never marks mail read and does not run for subagent tool calls: a hook cannot prove the model saw what it injected, so only the agent's own get_messages call consumes mail (ADR-0037).

Install per-project (NOT global), in <project>/.claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "/path/to/bot-relay-mcp/hooks/post-tool-use-check.sh",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

Important — if your path contains spaces, single-quote it inside the JSON string. Claude Code passes the command to the shell, which splits on whitespace. Without the single quotes the hook silently fails with errors like /bin/sh: ... is a directory. Example for an installation at /path/to/My Projects/bot-relay-mcp/:

"command": "'/path/to/My Projects/bot-relay-mcp/hooks/post-tool-use-check.sh'"

The outer double-quotes are JSON; the inner single-quotes are shell. Paths with no spaces do not need this treatment.

The hook reads through relay pending (read-only, the canonical pending set, works with the daemon down). The read path is chosen by configuration, never by failure: with a local relay it reads only locally and says relay unreadable if it cannot. It peeks over HTTP ("via remote relay") only when no local instance exists and RELAY_HTTP_HOST names a remote relay. It does NOT re-register (SessionStart handles that), does NOT check tasks (simpler focus, less context pressure), silent-exits when there is no mail, and stays quiet while the unread set is unchanged (RELAY_HOOK_NOTICE_REMIND_SECS, default 600s, at most 120s when anything unread is high priority). Full docs + troubleshooting in docs/post-tool-use-hook.md.

Honest limitation: idle terminals get no delivery. The hook only fires when the agent is actively running tool calls. For long-idle windows, still rely on SessionStart + human attention.

Turn-Boundary Wake (v2.1, rewritten v2.23)

PostToolUse only fires on turns that include at least one tool call. A text-only turn (Claude responds with no tool invocation) does not trigger it. The Stop hook — hooks/stop-check.sh — closes that gap by firing at every turn end, whether or not the turn invoked tools. It is a read-only wake: it peeks at the mailbox and, if mail is pending, emits decision:"block" so the agent continues immediately and fetches its own mail via get_messages. The hook itself never marks anything read — a wake that cannot prove delivery must not consume (additionalContext on Stop is queued for a next turn that may never come, so the original mark-read-and-inject shape was a silent data-loss path). Install both together in your project's .claude/settings.json:

{
  "hooks": {
    "Stop": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "/path/to/bot-relay-mcp/hooks/stop-check.sh",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

Same single-quote-the-path-if-it-contains-spaces rule, same env vars, and the same read rule as PostToolUse (relay pending locally, a peek:true read over HTTP only for a remote relay; both non-mutating, and no mutating SQL exists in the script). An unreadable local relay is reported on stderr, never turned into a block. Two loop guards bound the blocking: stop_hook_active in the hook payload (one wake per natural stop) and a time damper (RELAY_STOP_WAKE_DAMPER_SECS, default 120s) that applies only when the payload lacks a parseable stop_hook_active. All guards leave mail pending when they suppress — a delayed wake, never a lost one. Full docs + troubleshooting in docs/stop-hook.md.

Honest limitation: Stop does NOT wake truly idle terminals. If no turn is in progress, neither hook fires. For long-idle windows, use the Layer 2 Managed Agent reference (examples/managed-agent-reference/).

Backup & Restore (v2.1)

Two CLIs for disaster recovery:

relay-backup                              # snapshot to ~/.bot-relay/backups/
relay-backup --output /srv/backup.tgz     # custom path
relay-restore ~/.bot-relay/backups/relay-backup-<iso>.tar.gz

relay-backup produces a tar.gz of the live DB (via a consistent snapshot — safe while the daemon is running), the optional config.json, and a manifest.json with schema version and row counts. Works on both drivers (#171): the native better-sqlite3 driver snapshots via VACUUM INTO; the optional sql.js wasm driver snapshots via an atomic in-memory serialization (.export()), and the manifest/integrity probes open through the active driver. Archives are standard SQLite files and interoperate across drivers (details).

relay-restore always safety-backs-up the current DB first (to ~/.bot-relay/backups/pre-restore-<iso>.tar.gz). If that safety backup fails, the restore aborts untouched. It then refuses if the daemon appears to be running (/health probe, best-effort), refuses schema-version mismatches (higher = hard refuse, lower = --force overrides), runs PRAGMA integrity_check on the extracted DB, and finally atomic-swaps the new DB into place.

Full docs + troubleshooting in docs/backup-restore.md.

Lost-Token Recovery (v2.1)

Close a terminal, lose RELAY_AGENT_TOKEN, and the relay rejects your register_agent with AUTH_FAILED because the row is intact. Clear the registration so the agent can re-bootstrap:

relay recover <agent-name>                 # interactive confirm
relay recover <agent-name> --yes           # skip confirm (for scripts)
relay recover <agent-name> --dry-run       # show what would change, commit nothing
relay recover <agent-name> --db-path PATH  # non-default DB location

Messages and tasks addressed to the agent are preserved — only the agents + agent_capabilities rows are cleared. After recovery, the operator calls register_agent with the same name/role/capabilities and captures a fresh agent_token.

Trust model: filesystem access to ~/.bot-relay/relay.db IS the authority (same boundary the daemon relies on). Not an MCP tool — the caller by definition cannot authenticate. The CLI emits an audit_log entry with tool='recovery.cli' + the operator's OS username for incident traceability.

External-CLI Token Mint (v2.6)

Some LLM CLI clients (Codex was the canonical case) have safety monitors that pattern-match register_agent followed immediately by use returned token as a credential handoff and cancel the second tool call. The result: the agent row exists on the relay, but the agent process never captured its token, and every subsequent re-register attempt fails with NAME_COLLISION_ACTIVE because the orphan session is still considered live.

relay mint-token solves this by minting the token outside the agent's process. The operator hands the plaintext token to the agent's environment via RELAY_AGENT_TOKEN, and the agent authenticates on its first MCP call without ever invoking register_agent:

relay mint-token codex --role builder --capabilities build,test,audit

Output (token shown ONCE):

✓ Minted token for new agent "codex"

Token (shown ONCE — store it now):

  <43-char-base64url-token>

Set in your CLI's environment before launching:

  export RELAY_AGENT_NAME=codex
  export RELAY_AGENT_TOKEN=<43-char-base64url-token>

Other forms:

relay mint-token NAME --json                          # structured output for scripts
relay mint-token EXISTING --force                     # rotate token; caps + role preserved
relay mint-token NAME --description "human-readable"  # discoverable in dashboard

Caps are locked at first mint (caps are immutable after first registration); --force rotates the token but preserves both caps and role. The CLI emits a daemon-running advisory to stderr and writes an audit_log entry (tool='agent.token_minted') with the operator's OS username, the --force flag state, and whether the row was created or rotated. Full setup walkthrough including platform-specific token-storage best practices: docs/agents/external-cli-setup.md.

Cross-Platform Spawn (v1.9)

spawn_agent opens a new Claude Code terminal on macOS, Linux, and Windows via a driver abstraction:

  • macOS — bin/spawn-agent.sh (iTerm2 → Terminal.app). Unchanged from v1.6.4, preserves the 3-layer hardening + 19-payload adversarial test suite.

  • Linux — gnome-terminal → konsole → xterm → tmux fallback chain. The tmux fallback creates a detached session (attach later with tmux attach -t <agent-name>) — covers headless servers with no GUI.

  • Windows — wt.exe (Windows Terminal) → powershell.exe → cmd.exe.

Driver selection: RELAY_TERMINAL_APP override (allowlist-gated) > process.platform auto-detect > in-driver fallback chain.

Full install requirements per platform + manual smoke-test checklists + troubleshooting: docs/cross-platform-spawn.md.

Env-var propagation is minimal by default (principle of least authority): system essentials + anything prefixed RELAY_*. Secrets like AWS_SECRET_ACCESS_KEY are NOT passed to spawned agents unless explicitly prefixed.

Plug-and-play defaults (v2.1.2): spawned terminals are configured for autonomous work out of the box — they auto-pull mail from their inbox on first turn instead of idling, run with --permission-mode bypassPermissions so they don't ask the operator to approve every tool call, get an iTerm2 / session-picker title set to the agent name, and run at --effort high to cap token spend (parent terminals doing strategic work may use xhigh; spawned children doing mechanical work shouldn't inherit it). Every default has an env override for the rare case the legacy behavior is wanted:

Default

Env override

Notes

Kickstart prompt sent as positional arg

RELAY_SPAWN_KICKSTART="custom" / RELAY_SPAWN_NO_KICKSTART=1

The default tells the spawned agent to pull get_messages and act on inbox.

--permission-mode bypassPermissions

RELAY_SPAWN_PERMISSION_MODE=<mode>

Allowlist: acceptEdits, auto, bypassPermissions, default, dontAsk, plan.

--name <agent>

RELAY_SPAWN_DISPLAY_NAME="custom"

Shows up as the iTerm2 tab + Claude Code session title.

--effort high

RELAY_SPAWN_EFFORT=<level>

Allowlist: low, medium, high, xhigh, max.

Layer 2: Managed Agents (v1.10)

Agents that are NOT Claude Code terminals — Python daemons, Node workers, Ollama/vLLM integrations, custom scripts. They connect to the relay via HTTP (recommended) or direct SQLite, use the same MCP tools, and authenticate with per-agent tokens. If registered with managed:true, they also receive token-rotation push-messages over the normal get_messages channel — see docs/managed-agent-protocol.md.

Full integration guide with mental model, auth flow, lifecycle, error patterns, and security notes: docs/managed-agent-integration.md.

Runnable reference implementations (stdlib-only, ~200 LOC each):

Both demonstrate: register, send/receive messages, accept + complete tasks, discover peers, SIGINT cleanup. Each has a SMOKE.md with a 5-step manual verification checklist.

SQLite Driver Options (v1.11)

The relay uses SQLite for persistent state. Two drivers are available:

  • native (default) — better-sqlite3, a compiled C addon. Fast, supports WAL mode, multi-process safe. Requires a C++ compiler at npm install time.

  • wasm — sql.js, SQLite compiled to WebAssembly. Zero native compilation. Slightly slower writes (in-memory + write-back-to-file). Single-process only: one process owns the database (one HTTP daemon, or a single stdio terminal); a second is refused by name.

Switch with one env var:

npm install sql.js                    # one-time install of the optional dep
RELAY_SQLITE_DRIVER=wasm node dist/index.js

Both drivers use the same SQLite file format, but a database belongs to one driver (its header says which): switch an existing database with relay convert-journal --to wasm|native. Full details, performance notes, and limitations: docs/sqlite-wasm-driver.md.

Installing under npm v12+ (install scripts disabled by default)

npm v12 (released 2026-07-08) disables dependency install scripts by default (allowScripts off) — including native node-gyp/prebuild builds. The default native driver (better-sqlite3) fetches its prebuilt binary via an install script, so under npm 12's defaults that binary is never fetched and the relay fails at startup with:

Error: Could not locate the bindings file

Two ways to fix it:

A — keep native (best for multi-terminal stdio): approve better-sqlite3's install script once. The approval is recorded in your package.json allowlist — commit it.

npm install                                   # installs; records which deps have scripts
npm approve-scripts --allow-scripts-pending   # review what's pending
npm approve-scripts better-sqlite3            # approve it
npm rebuild                                    # build the native binary

B — switch to wasm (zero approval): sql.js is pure WebAssembly — no native build, no install script.

RELAY_SQLITE_DRIVER=wasm node dist/index.js   # a NEW database: created owned by this process
relay convert-journal --to wasm               # an EXISTING database: convert it once, every relay process stopped (works without the native driver)

Since 5.0.0 an existing native or legacy database is never opened by wasm until it is converted (the refusal names the command). wasm is single-process only (see the note above — not for multi-terminal stdio). sql.js is an installed optional dependency; if you installed with --omit=optional, add it back with npm install sql.js.

--allow-git / --allow-remote (also default none in npm 11.10+/11.15+) don't affect the relay — every dependency resolves from the npm registry, none from git or tarball URLs. Full details: docs/sqlite-wasm-driver.md.

Roadmap

  • v1.1: Local relay, 9 tools, SQLite, auto-purge

  • v1.2: HTTP transport, webhook system, config file — 12 tools

  • v1.3: Presence integrity, unregister_agent, hook delivers mail — 13 tools

  • v1.4: spawn_agent + role templates + dashboard — 14 tools

  • v1.5: Built-in security — Bearer auth, audit log, rate limiting

  • v1.6: Hardening pass — SSRF, input validation, path traversal, stdout discipline

  • v1.7: Per-agent tokens, secret rotation, at-rest encryption, capability scoping

  • v1.8: Near-real-time mail via PostToolUse hook

  • v1.9: Cross-platform spawn (macOS / Linux / Windows / tmux) — Node/TS driver abstraction

  • v1.10: Layer 2 Managed Agents — reference Python + Node workers

  • v1.11: SQLite WASM driver (sql.js opt-in) — zero native compilation on Windows/Alpine/Docker/CI

  • v2.0: Plug-and-play — channels, smart routing (post_task_auto), task leases + heartbeat, lazy health monitor, session-aware reads, busy/DND, health_check, webhook retry with CAS, payload size limits, config validation, auto-unregister, dead-agent purge, debug mode. 22 tools.

  • v2.1: Architectural completion — explicit auth_state machine, managed-agent rotation grace, versioned ciphertext + keyring with online rotation (relay re-encrypt), lost-token recovery CLI (relay recover), admin-initiated cross-agent rotation (rotate_token_admin), structured error_code catalog, protocol_version surface, Phase 4p webhook-secret encryption, Phase 4b.1 v2 revoke/recovery redesign. 25 tools. 14 of 14 Codex architectural findings closed.

  • v2.7: Tether-ready cross-process inbox notifications. Durable inbox_events outbox table (schema v11→v12, idempotent migration); HTTP daemon polls + dispatches to relay://inbox/<agent> subscribers regardless of which OS process wrote the message. Reaper now skips sessions with active SSE GET streams (openGetStreams count). Daemon emits :keepalive\n\n SSE comment frames every RELAY_SSE_KEEPALIVE_MS (default 20s) so Electron-based clients (VS Code Tether extension) don't idle-disconnect at ~2.5min. External-review-flagged get_messages filter-after-mark P1 fix — since filter now applies in SQL BEFORE the read-mark mutation. 30 tools. Pairs with Tether VSCode extension v0.1.2+ on the marketplace.

  • v2.12: Hands-free, LLM-agnostic autowake. The multi-agent Tether watch-all wakes Claude and Codex agents on relay mail and auto-submits, no manual polling (dogfood-proven: the relay now coordinates its own development). Plus the pending-vs-history resolved plane (resolve_messages + an ack flag, so handled mail stops re-flooding fresh sessions) and a central schema-scoped auth fix closing a stray-field impersonation hole.

  • v2.13–v2.16: Presence liveness — a same-host process probe (agent_pid) so an idle-but-alive agent stops reading as offline (schema v16→v18) — plus the Tether-wakes-Codex PID handshake and the bin/codex-relay cold-start launcher (zero-turn cold summon of a Codex agent).

  • v2.17: LLM-agnostic spawn parity. spawn_agent(cli: "codex") launches a Codex CLI (macOS/Linux), driven by a central agent-CLI profile registry with an AST drift guard; Tether wake behavior is data-driven from the same registry.

  • v2.18: Sentinel (relay watch <agent>) — poll/marker-based autowake for terminals not in VSCode/Tether (iTerm2 personas, plain terminals, remote sessions). The wake-anywhere sibling of Tether's push-wake.

  • v2.19: Liveness derivation — presence that stops lying. The coarse agent status is now derived from the liveness verdict (online/offline/unknown), never from last_seen age, so a rate-limited-but-alive agent no longer reads offline.

  • v2.20: O(1) token authentication. An indexed HMAC token locator + a verified-token cache replace the O(N) per-call bcrypt scan (bcrypt stays the sole verifier); instant revocation via a generation counter; zero-lockout migration. 35 tools.

  • v2.21: ADR-0002 — agent class/flare topology. Agents declare an immutable coordination class at register_agent (orchestrator | builder | advisory | auditor | transient), a third axis orthogonal to role and capabilities. discover_agents view='topology' renders the live team grouped by class (default view='list' is unchanged), plus an opt-in SessionStart onboarding map (RELAY_ONBOARD_TOPOLOGY=1, default off) and a taxonomy drift guard in the pre-publish gate. Still 35 tools — a view parameter, not a new tool.

  • v2.22: Curl/script-caller DX hardening (ADR-0005). One-shot POST /mcp returns plain JSON, agent_token is the first field of the register response, send_message accepts a message alias, and abandon_registration lets a script self-clean a botched (never-authenticated) registration via a one-time recovery handle — safe by construction (only ever removes a row that has never authenticated). 36 tools.

  • v2.23: Config-clobber closed + orchestration-anchor safety + a HIGH dependency advisory. npm test no longer rewrites the real ~/.claude.json (an account-home chokepoint guard); non-destructive release-binding; the fast-uri HIGH advisory pinned out. 36 tools.

  • v2.24: Security hardening — operator auth (ADR-0006), dashboard content isolation, orchestration integrity. Operator power now requires a verified dashboard secret (relay init) rather than network position; the dashboard no longer serves message content to unauthenticated callers; the diagnostic traffic recorder redacts tokens. 36 tools.

  • v2.25: ADR-0011 — message disposition + read-receipts (schema v24, the get_outstanding tool). Plus a security-advisory sweep (fast-uri + ip-address HIGH advisories) and dependency majors (uuid 14, TypeScript 6.0.3 — not the 7.x Corsa rewrite). 37 tools.

  • v3.0: Wake-coverage detector + undelivered-mail durability + a BREAKING since contract change. A default-on daemon sweep reports when an agent has mail stuck past the effective threshold and is no longer being woken — three verdicts (covered / uncovered / unobservable), REPORT-FIRST: an uncovered line is a possible wake-path regression, not proof of fault, and unobservable is never reported as uncovered. New agents.last_drain_at column and RELAY_WAKE_* knobs. Undelivered mail (not drained by any recipient) is no longer deleted at 7 days: it is held to a bounded 30-day grace (RELAY_UNDELIVERED_GRACE_DAYS, default 30; 0 disables the extension) with a stderr deadletter line when finally dropped. BREAKING: a pending drain now returns never-observed mail regardless of since — the 2.25 strict-cursor promise (since = "only return messages after this time") is withdrawn; audit any pending-drain since-cursor logic (see the CHANGELOG breaking entry; history reads are unaffected). Still 37 tools.

  • v4.0 (current): BREAKING: a new agent name over HTTP needs the registration secret; Node 22. Registering a new name over HTTP needs the relay's registration secret (seeded from http_secret when one is set). Node.js 22 or later is required. Instance resolution is one strict resolver that refuses on a fault instead of guessing. The pending queue is never windowed by default. A revoked token is refused everywhere, and wrong tokens can no longer freeze the relay. HTTP request bodies are bounded in structure (SEC-24), and dependency advisories are addressed (see the CHANGELOG's security summary). New: relay watch --until-wake, the doorbell, relay pending, relay fleet, relay bind. Read Upgrading from 3.x in the CHANGELOG first. 38 tools.

  • Beyond: cross-machine federation (hub/edge) so multiple self-hosted relays mesh without a shared namespace, plus an App Server push path for low-latency remote wake.

Dashboard

When running in http or both mode, open http://127.0.0.1:3777/ in a browser. You'll see:

  • Live agent presence (online / offline / unknown), derived from a liveness verdict — not last_seen age (v2.19)

  • Active tasks with priority and assignment

  • Recent messages

  • Registered webhooks

  • Recently completed tasks

Auto-refreshes every 3 seconds. Useful for "what's happening across all my terminals right now?" at a glance.

Role Templates

See roles/ for drop-in role specs. Examples:

  • planner.md — orchestrator that delegates and synthesizes

  • builder.md — worker that accepts and completes tasks

  • reviewer.md — skeptical reviewer with structured output

  • researcher.md — investigates questions, returns findings

Three ways to apply a role: paste into project CLAUDE.md, pass as initial_message when spawning, or wire via shell alias.

Requirements

  • Node.js 22+

  • Claude Code (or any MCP-compatible client)

Feedback & Questions

Using it with a client we don't list yet (Copilot, a home-grown CLI)? Tell us in Discussions — real setups shape what ships next.

License

MIT

Available Tools

38 tools
abandon_registrationA

Self-clean YOUR OWN botched (orphaned) registration when you lost the agent_token before ever authenticating — e.g. a curl/script caller truncated the register response. Authenticated by the one-time registration_recovery handle returned in the register_agent response (NOT the lost token), so it needs no auth token.

When to use: you registered but never captured/used the token, and the row is now an orphan you can't unregister (unregister needs the token you lost). NOT for a live agent that lost its token mid-session — that agent has authenticated, so this is refused; use rotate_token / relay recover instead.

Behavior: verifies the registration_recovery handle (bcrypt, name-scoped, one-time, TTL-bound) and — ONLY if the target row has NEVER authenticated (the keystone) — deletes it, bumps the auth generation, and fires an agent.unregistered webhook. The keystone is re-asserted inside the DELETE, so it can never reach a working agent (a row that authenticates between check and delete is left intact) — the safe, self-serve alternative to the operator kill endpoint. Orphans are also auto-GC'd after ~30min (never-authed + session-less + older than the orphan TTL) as a backstop.

Returns: { success, name, abandoned }. Errors (AUTH_FAILED): agent has authenticated (not an orphan), invalid/expired handle, or no such registration.

Inputs: name (required), recovery_handle (required).

broadcastA

Fan out a single message to every registered agent (or every agent of a given role).

When to use: announcements, fleet-wide pings, role-targeted prompts ('all builders, refresh your dependencies'). For 1:1 use send_message. For topical group coordination prefer post_to_channel, channels persist membership and avoid spamming agents who have explicitly opted out by leaving.

Behavior: stores one row per recipient with status='pending'; the sender is excluded from the recipient set. Fires one message.broadcast webhook event for the whole batch (delivery_id + idempotency_key in the envelope). Optional role narrows the recipient set. Same payload size cap as send_message (RELAY_MAX_PAYLOAD_BYTES).

Returns: { success: true, sent_to: string[], message_ids: string[], count, note }. count=0 with a note string when no other agents matched the filter (still success, not error).

Errors: AUTH_FAILED, PAYLOAD_TOO_LARGE, RATE_LIMITED.

Inputs: from (required), content (required), role, agent_token.

create_channelA

Create a named channel for many-to-many topical coordination.

When to use: ongoing conversations that more than two agents care about and that should persist beyond the lifetime of any one agent (e.g., #deploys, #triage). For 1:1 use send_message. For one-shot fleet-wide announcements use broadcast.

Behavior: creates the channel row and adds the creator as a member. Channels are flat (no hierarchy) and globally addressable by name. Auth: caller must hold the channels capability.

Returns: { success: true, channel: { id, name, description, created_by, created_at }, message }.

Errors: AUTH_FAILED (missing channels capability), ALREADY_EXISTS (name collision), INVALID_INPUT, RATE_LIMITED.

Inputs: name (required), creator (required), agent_token, description.

delete_webhookA

Tear down a webhook subscription by id.

When to use: cleanup when an integration is being retired, when the receiver URL is dead and you do not want delivery-log noise, or when rotating a webhook secret (delete + register fresh).

Behavior: removes the subscription row and any pending entries in webhook_delivery_log. Auth: the registrant's token, OR an authenticated agent with webhooks capability for cross-owner cleanup.

Returns on success: { success: true, webhook_id, note: 'Webhook deleted' }. Returns on missing-id: { success: false, webhook_id, note: 'Webhook not found' } with isError: true — this surfaces as a tool error so callers know the id was already gone (NOT a soft-success).

Errors: AUTH_FAILED, INVALID_INPUT. Missing-id is reported via the success: false + isError: true envelope above, not a separate error_code.

Inputs: webhook_id (required), agent_token.

discover_agentsA

List every registered agent with computed presence + operator-controlled status.

When to use: pick a routing target by role (e.g., 'any builder'), confirm an expected agent is online before sending it work, or surface the agent fleet to a dashboard. For periodic team rollups use get_standup instead, it bundles agents + recent activity in one call.

Behavior: pure read; never mutates last_seen (v1.3 presence-integrity fix). Optionally filters by role. The returned status (online | stale | offline) is computed from last_seen deltas; the returned agent_status (idle | working | blocked | waiting_user | stale | offline | abandoned | closed) is operator-controlled via set_status. Token hashes are stripped, has_token: boolean only.

Returns: { agents: AgentWithStatus[], count: number, filter: { role } | 'none' }. Ordered by last_seen DESC.

Errors: RATE_LIMITED. (No auth required, this surface is intentionally observable for orchestration.)

Inputs: role, view, agent_token.

expand_capabilitiesA

Self-managed additive capability expansion (v2.1.4).

When to use: an agent registered (often via the SessionStart hook) with a narrow capability set and now needs more, e.g., a builder later picks up a webhooks integration. Reductions are NOT supported (unregister_agent + fresh register_agent for those). For privileged cross-agent edits, no equivalent admin tool exists by design, capability changes are caller-attested.

Behavior: caller presents their token; the requested set MUST be a SUPERSET of current caps (additive only, closes the v1.7.1 immutability gap without re-opening the capability-escalation CVE). Reductions reject with REDUCTION_NOT_ALLOWED. Requesting only already-held caps rejects with NO_OP_EXPANSION. The expansion is recorded in the audit log with the verified caller name.

Returns: { success: true, agent, added: string[], capabilities: string[] }. capabilities is the new full set after expansion; added is the diff of newly-granted caps.

Errors: NOT_FOUND (unknown agent), REDUCTION_NOT_ALLOWED, NO_OP_EXPANSION, AUTH_FAILED, INTERNAL.

Inputs: agent_name (required), new_capabilities (required), agent_token.

get_channel_messagesA

Read the messages you are entitled to see in a channel.

When to use: any flow that observes channel traffic, dashboard refresh, post-incident review thread, role onboarding ('catch up on #deploys'). For 1:1 mailbox use get_messages; for whole-fleet activity use get_standup.

Behavior: scoped to messages with created_at >= your join_time. Ordered by priority then created_at newest-first. Pure read, channel posts have no per-recipient read state, so this call is fully idempotent. Auth: caller must be a current member.

Returns: { messages: ChannelMessage[], count, channel_name, agent }. Each message carries id, channel_id, from_agent, content, priority, created_at.

Errors: NOT_MEMBER (caller has not joined the channel), NOT_FOUND, RATE_LIMITED.

Inputs: agent_name (required), channel_name (required), limit, since, +1 more.

get_messagesA

Drain or peek your own mailbox.

When to use: each turn that should observe new mail; orchestrators that batch-poll many agents may prefer get_messages_summary (cheaper preview) or peek_inbox_version (counts only). For surveys that must NOT consume mail, set peek=true.

Behavior: returns messages addressed to you, ordered by priority then created_at newest-first. By default status='pending' returns un-read messages and atomically marks them read for THIS session (sessions are per-session_id; a fresh terminal re-sees previously-read messages, v2.0 final fix). Optional since ('1h' | '24h' | '7d' | ISO | 'all'); its DEFAULT DEPENDS ON STATUS: status='pending' defaults to 'all' (the action queue is never windowed unless you ask), history reads (all/history/read/resolved) default to '24h'. A pending read ALWAYS returns UNDELIVERED (never-drained) mail regardless of since (#198; 3.0.1). For a pending read total_pending is always the full, unwindowed queue, and when your since hid pending mail the response carries hidden_by_since: N. peek=true (v2.2.2) suppresses the read-MARK — the returned messages are not marked read for your session — but it is NOT side-effect-free: like any first view it stamps the observation cursor (seq). (Post-3.0.1 that observation no longer changes what a later drain returns.)

Returns: { messages: MessageRecord[], count, has_more, total_pending | total, hidden_by_since?, agent, filter, since, since_bound, acked?, resolved_count?, warning? }. since is the window actually applied (the status default when you gave none); since_bound is the ISO timestamp the relay filtered by (after resolving duration shorthands or 'session_start'). With ack=true on a pending drain, acked and resolved_count report what the database actually changed, never what was asked. If your agent has no current session (session_id NULL, e.g. after a token rotation), the drain still delivers and records the agent-level receipts (read_at, last_drain_at, resolves) and returns warning: { code: 'session_unbound', message }: unresolved mail comes back on the next drain until you re-register or resolve it.

Errors: AUTH_FAILED, VALIDATION (bad since format), RATE_LIMITED.

Inputs: agent_name (required), ack, lane, peek, +4 more.

get_messages_summaryA

Cheap, non-mutating mailbox preview (v2.1.6).

When to use: orchestrators scanning many inboxes per cycle, dashboards rendering a per-agent backlog count, or any flow where you want to see what is there without consuming it. After picking interesting IDs, expand them with get_messages (which CAN mutate) or read them by ID.

Behavior: same status + since filter surface as get_messages, with the same status-dependent since default (pending → 'all', history → '24h'). Returns headers + a 100-char content_preview (decrypted on the fly when RELAY_ENCRYPTION_KEY is set). Never marks messages read. Auth: agent token (own mailbox only).

Returns: { summaries: { id, from_agent, priority, status, created_at, content_preview, content_truncated }[], count, has_more, total, total_pending?, hidden_by_since?, agent, filter, since, since_bound }. total is what your window matched; for a pending preview total_pending is the full, unwindowed queue, and hidden_by_since appears when your window hid pending mail. content_truncated=true when the original content exceeded the 100-char preview cap.

Errors: AUTH_FAILED, VALIDATION, RATE_LIMITED.

Inputs: agent_name (required), limit, since, status, +1 more.

get_outstandingA

The SENDER's outstanding-ask recap + the pull source of truth for overdue drift (ADR-0011).

When to use: an orchestrator (or any sender) reconstructing what it is owed — on a fresh session, or any time it wants the current picture of asks/obligations it SENT that haven't been resolved. This PULL is the source of truth; the optional message.read/message.resolved webhooks are push-on-top and may be missed.

Behavior: returns the messages YOU sent with disposition in ('ask','obligation'), each with its sender-visible lifecycle state (undrained / drained-unresolved / resolved — a DELIVERY-PATH state: undrained means not drained through the consuming get_messages path, which is NOT the same as unread/unseen, since peek/CLI/direct-DB reads never stamp it) and a REPORT-ONLY overdue flag computed at query time — it NEVER mutates a message (report-first, never auto-resolve). LOG messages are excluded (LOG never goes overdue). overdue = still-unresolved AND past its bound: an obligation past its deadline, else an ask/deadline-less-obligation past created_at + RELAY_OVERDUE_SECONDS (default 24h, tunable). include_resolved=false (default) returns only the outstanding set; true adds resolved rows for the full sender view. Auth: agent token; sender-scoped (you only see mail you sent).

Returns: { success, agent, include_resolved, overdue_bound_seconds, count, overdue_count, outstanding: { id, to_agent, disposition, created_at, deadline, read_at, resolved_at, state, overdue, content_preview, content_truncated }[] }.

Errors: AUTH_FAILED, VALIDATION, RATE_LIMITED.

Inputs: agent_name (required), agent_token, include_resolved.

get_standupA

One-shot team-status synthesis for orchestrators (v2.1.4).

When to use: every observation cycle that would otherwise call discover_agents + get_messages + get_tasks and synthesize in-LLM. The relay does the rollup server-side so the caller burns near-zero tokens. For specific drill-downs after the rollup, fall through to the underlying tools.

Behavior: pure read. Given a window (since: '15m' | '1h' | '3h' | '1d' | ISO), returns active_agents (filtered to non-offline by default, set include_offline=true to include them), message_activity counts, task_state breakdown, and rule-based observation bullets ('agent X has been blocked >30min', etc.). Observations are hand-rolled heuristics, NO LLM on the relay side. Optional agents / roles arrays narrow the snapshot. Auth: any agent token.

Returns: { success: true, window: { since, now, duration_ms }, active_agents: Agent[], message_activity, task_state: { completed_in_window, queued, blocked, assigned_by_agent }, observations: string[] }.

Errors: VALIDATION (bad since format), AUTH_FAILED, RATE_LIMITED.

Inputs: since (required), filter, agent_token.

get_taskA

Look up a single task by id.

When to use: any flow that needs the canonical state of one specific task, e.g., the assignee just heartbeat'd and wants to confirm the row, or the requester is checking on a known task_id from an earlier post_task response. For browsing many tasks use get_tasks.

Behavior: pure read. Returns the full task record including encrypted-at-rest description + result fields decrypted on the fly. Auth: agent token whose row is either the requester or assignee on this task, the relay refuses to leak third-party tasks.

Returns: { success: true, task: TaskRecord } with the full row including encrypted-at-rest description + result decrypted on the fly.

Errors: NOT_PARTY (caller is not the requester or assignee), NOT_FOUND (unknown task_id), RATE_LIMITED.

Inputs: task_id (required), agent_token.

get_tasksA

Query the tasks you are involved with.

When to use: assignees triaging their queue (role='assigned'), requesters checking on dispatched work (role='posted'). For a single task by id use get_task. For team-wide rollup use get_standup.

Behavior: pure read. Filters by role + status; default status='all'. Ordered by priority then created_at newest-first. Auth: agent token (only your own tasks are visible).

Returns: { tasks: TaskRecord[], count, agent, role, filter }. Each task carries id, from_agent, to_agent, title, description, priority, status, result, created_at, updated_at, lease_renewed_at.

Errors: AUTH_FAILED, RATE_LIMITED.

Inputs: agent_name (required), role, limit, status, +1 more.

health_checkA

Report relay process health + live counts.

When to use: liveness probes (/health HTTP endpoint mirrors this surface), version-pinning checks during upgrades, dashboard footers. Cheaper than get_standup for binary up/down questions.

Behavior: pure read. Counts agents by presence, pending messages, active and queued tasks, channels, and webhook subscriptions. Reports version (from package.json via the v2.1 Phase 4a single source of truth) + protocol_version (the client-compat surface, distinct from package version) + build (the build this process LOADED at start: its code and dependency ids, with commit, build time and node version; on stdio that is your own connector, so a stale one shows here). Works on stdio AND HTTP transports. No capability required, intentionally observable. Also reports surface — your active profile, the tool bundles in effect, and which tools those bundles HIDE — so a capability missing from tools/list can be told apart from one that does not exist.

Returns: { status: 'ok', version, protocol_version, transport, uptime_seconds, legacy_grace_active, agents: {...counts}, messages: {...counts}, tasks: {...counts}, channels, webhooks }. When the caller presents a token (arg / header / env), the response also includes token_validated: true, auth_error: boolean, and (on validation failure) auth_error_reason, plus agent_name + auth_state on success.

Errors: none expected (status='ok' is the only success shape).

Inputs: agent_token.

join_channelA

Subscribe to a channel so you receive its messages from your join time forward.

When to use: any agent that wants to follow a channel's traffic, joining is open to any authenticated caller (no invite gate; channels are intentionally low-friction). Pair with post_to_channel for posting and get_channel_messages for reading.

Behavior: inserts the membership row with joined_at = now. get_channel_messages and the channel.message_posted webhook event scope to messages with created_at >= joined_at for this member, so historical traffic is NOT replayed (a deliberate design choice, channels are streams, not archives). Idempotent: rejoining is a no-op. Auth: any agent token.

Returns: { success: true, channel_name, agent_name, joined: boolean, note }. joined=false indicates the agent was already a member (idempotent no-op).

Errors: AUTH_FAILED, NOT_FOUND (unknown channel_name), RATE_LIMITED.

Inputs: agent_name (required), channel_name (required), agent_token.

leave_channelA

Cancel your membership so you stop receiving a channel's messages.

When to use: channel is no longer relevant to your role, or you are shutting down and want to be a clean citizen (the dashboard surfaces ghost members otherwise). Idempotent, calling it on a channel you never joined is fine.

Behavior: removes the membership row. Past messages stay in the channel (other members still see them); your joined_at cursor is forgotten so a future join_channel starts a fresh observation window. Auth: agent token (you can only leave on your own behalf).

Returns: { success: true, channel_name, agent_name, left: boolean, note }. left=false indicates the agent was not a member (idempotent no-op).

Errors: AUTH_FAILED, NOT_FOUND, RATE_LIMITED.

Inputs: agent_name (required), channel_name (required), agent_token.

list_webhooksA

List every webhook subscription registered on the relay.

When to use: sanity-checking integrations ('is the Slack notifier still wired up?'), pre-cleanup audits, or building an admin UI. To narrow by event you currently filter client-side from this list.

Behavior: pure read. The raw HMAC secret is NEVER returned, each row exposes has_secret: boolean only. Auth: any registered agent (subscriptions are observable so admins can audit them, but secrets stay write-only).

Returns: { webhooks: { id, url, event, filter, has_secret, created_at }[], count }.

Errors: AUTH_FAILED, RATE_LIMITED.

Inputs: agent_token.

peek_inbox_versionA

Cheap non-mutating mailbox version probe (v2.3.0 Phase 4s, ambient wake support).

When to use: low-rate polling that wants to know 'do I have new mail?' without paying a get_messages round-trip, clients diff total_unread_count against their cached value and only call get_messages on a change. Pair with the optional filesystem-marker wake (when RELAY_FILESYSTEM_MARKERS=1) for low-latency idle wake. For full mailbox content use get_messages (mutating) or get_messages_summary (preview).

Behavior: pure read. Returns { mailbox_id, epoch, last_seq, total_messages_count, total_unread_count }. WATCH total_unread_count for new-mail detection, it advances on every send_message/broadcast to this agent. last_seq is the OBSERVED axis: it advances when the recipient views mail through ANY get_messages call, including peek=true, so it says nothing about delivery or reading, and no decision may key on it. epoch rotates on backup/restore, a client whose cached epoch no longer matches MUST reset its local last_seen_seq to 0 and re-drain. Auth: any agent token.

Returns: { success: true, mailbox_id, epoch, last_seq, total_messages_count, total_unread_count }.

Errors: AUTH_FAILED, NOT_FOUND (unknown agent_name), RATE_LIMITED.

Inputs: agent_name (required), agent_token.

post_taskA

Assign a tracked task to a specific agent.

When to use: work that should move through accept then complete/reject and report a result, with a single named owner. Prefer post_task_auto when you do not care which capable agent picks it up. Prefer send_message for free-text comms that do not need a state machine.

Behavior: creates a row with status='posted' and notifies task.posted webhook subscribers. The assignee accepts/completes/rejects via update_task; the assigner can cancel via the same call. Tasks have a heartbeat lease, if the assignee does not update_task action='heartbeat' within RELAY_TASK_LEASE_SECONDS, the health monitor surfaces the task as stuck. Auth: requester token; to must be a registered agent.

Returns: { success: true, task_id, from, to, title, priority, status, note }. status is 'posted' on first creation.

Errors: AUTH_FAILED, PAYLOAD_TOO_LARGE, RATE_LIMITED.

Inputs: to (required), from (required), title (required), description (required), +3 more.

post_task_autoA

Auto-route a task to the least-loaded capable agent (v2.0).

When to use: when you know the required capabilities but do not want to hard-code a specific assignee, load balances across the fleet. Prefer post_task when the assignee is intentional. Prefer broadcast for non-tracked notifications.

Behavior: picks the agent with the smallest accepted-task backlog whose capability set is a superset of required_capabilities. Tie-break: freshest last_seen. If no live agent qualifies, the task enters status='queued' and is auto-assigned the first time a capable agent calls register_agent (the assignment is included in that response's auto_assigned). By default the sender is excluded from routing, set allow_self_assign=true to opt in (v2.1).

Returns: { success: true, task_id, status: 'posted' | 'queued', assigned_to: string | null, routed: boolean, candidate_count, required_capabilities, note }. routed=true only when an agent matched at post time; routed=false with status='queued' is the no-match path that auto-resolves on next register.

Errors: AUTH_FAILED, PAYLOAD_TOO_LARGE, RATE_LIMITED.

Inputs: from (required), title (required), description (required), required_capabilities (required), +3 more.

post_to_capabilityA

Route an FYI/coordination message to the current owner(s) of a capability (v2.10 — capability routing, principle #1).

When to use: surface a finding, status, or cross-cutting update to whoever owns a domain WITHOUT knowing their name — e.g. an ad-hoc agent tags a 'relationships' finding and the agent that owns that capability picks it up on its next get_messages. FYI/COORDINATION LANE ONLY: action-required completions (a STAGED build needing an audit, a SHIP that triggers a merge) MUST stay point-to-point completion reports via send_message — that point-to-point reliability is what triggers the orchestrator's next action. A capability-routed message never triggers an action.

Behavior: exact-string matches capability against every registered agent's declared capabilities (same lookup as post_task_auto), then fans the message out — one messages row per owner, stamped with routed_capability so recipients + dashboards distinguish the FYI lane from point-to-point mail. Recipients drain via the normal get_messages (use lane='capability' to read only the FYI lane, lane='direct' for only point-to-point). The sender is excluded by default (exclude_self). No current owner → routed_to:[] and nothing stored (fire-and-forget to current owners, NOT queued-until-owner). Fires one message.capability_routed webhook for the batch. Content encrypted at rest if RELAY_ENCRYPTION_KEY is set; same payload cap as send_message.

Returns: { success: true, capability, routed_to: string[], message_ids: string[], count, note }. routed_to is empty (with an explanatory note) when no agent currently owns the capability.

Errors: AUTH_FAILED, SENDER_NOT_REGISTERED, PAYLOAD_TOO_LARGE, RATE_LIMITED, VALIDATION.

Inputs: from (required), content (required), capability (required), priority, +2 more.

post_to_channelA

Send a message into a channel you have joined.

When to use: ongoing topical coordination among multiple agents ('deploy started', 'triage thread for incident-12'). For 1:1 use send_message; for fleet-wide one-shots use broadcast. The audience is exactly the current channel membership at post time.

Behavior: stores a channel_messages row, fires the channel.message_posted webhook event, and surfaces in every member's get_channel_messages whose joined_at <= post.created_at. Same RELAY_MAX_PAYLOAD_BYTES cap as direct messages. Encrypted at rest when keyring is configured. Auth: caller must be a current member AND hold the channels capability.

Returns: { success: true, message_id, channel_name, from }.

Errors: NOT_MEMBER (caller has not joined the channel), AUTH_FAILED (missing channels cap), PAYLOAD_TOO_LARGE, NOT_FOUND, RATE_LIMITED.

Inputs: from (required), content (required), channel_name (required), priority, +1 more.

register_agentA

Register this terminal as a named agent so other agents can address it.

When to use: call this first thing in any session that needs to send/receive messages, post tasks, or join channels. Idempotent upsert, safe to call again on reconnect. The SessionStart hook (hooks/check-relay.sh) typically calls it for you.

Behavior: creates or updates the agent row keyed by name. First registration mints a fresh agent_token (returned ONCE, store it in RELAY_AGENT_TOKEN). Re-registering preserves the existing token unless recovery_token is presented (v2.1 Phase 4b.1 v2 recovery flow). Capabilities are immutable on re-register (v1.7.1), use expand_capabilities for additive changes.

Returns: { success: true, agent: AgentWithStatus, protocol_version, message }. First-time registration also includes agent_token (shown ONCE — store in RELAY_AGENT_TOKEN) and auth_note. If the request asked for capabilities that differ from the stored set, capabilities_note explains the immutability. If queued auto-routed tasks were assigned at register time, auto_assigned_tasks: { task_id, title, priority }[] lists them. Successful recovery flow includes recovery_completed: true.

Errors: AUTH_FAILED (recovery_pending row presented without recovery_token), RECOVERY_REQUIRED (token rejected, present recovery_token), INVALID_INPUT (name/role/capabilities malformed), RATE_LIMITED.

Inputs: name (required), role (required), capabilities (required), class, +13 more.

register_task_schemaA

Register a reusable, immutable JSON Schema that gates task completion (v2.10 — safety).

When to use: define the PROOF shape a completing agent must satisfy — e.g. a completion report requiring {ci_status:'green', tests_passed, summary}. A requester attaches the schema id to a task via post_task's schema_id; the assignee's update_task(action='complete', result=...) is then validated against it. Built-ins ship_pong_v1 / audit_verdict_v1 / merge_ready_v1 are auto-registered on init.

Behavior: the document is meta-validated + hardened (no $ref/$dynamicRef/$recursiveRef/$data) BEFORE ajv compiles it (a registered schema is compiled, so it is an attack surface). Schemas are IMMUTABLE — re-registering an id is refused; bump the version id. Auth: requires the manage_schemas capability.

Returns: { success: true, id, created_by, created_at, note }.

Errors: SCHEMA_MISMATCH (invalid/forbidden schema document), ALREADY_EXISTS (id already registered), CAP_DENIED, AUTH_FAILED, VALIDATION.

Inputs: name (required), agent_name (required), json_schema (required), agent_token.

register_webhookA

Subscribe an HTTP endpoint to relay events.

When to use: reactive integrations, Slack notifier, audit pipeline, dashboard refresher. For polling-style observation prefer get_standup or peek_inbox_version. For local UIs the bundled /dashboard already consumes the live event stream.

Behavior: stores the subscription + optional HMAC secret (encrypted at rest with the same keyring the message body uses, v2.1 Phase 4p). Each delivery POSTs the event JSON with X-Relay-Delivery-ID + X-Relay-Idempotency-Key headers and an X-Relay-Signature HMAC-SHA256 if a secret was registered. Outbound URLs are SSRF-validated against the cloud-metadata + private-IP blocklist (v1.10). Events: message.sent | message.broadcast | task.posted | task.accepted | task.completed | task.rejected | channel.message_posted | agent.unregistered | agent.spawned | '*'. Optional filter (agent name) narrows by sender/recipient.

Returns: { success: true, webhook_id, url, event, filter, has_secret: boolean, resolved_ips: string[], note }.

Errors: AUTH_FAILED (caller needs webhooks capability), URL_BLOCKED (SSRF target), INVALID_INPUT, RATE_LIMITED.

Inputs: url (required), event (required), filter, secret, +1 more.

report_livenessA

Restamp your own liveness anchor (agent_pid + process start-time) — a narrow, metadata-only presence self-report.

When to use: your hooks call this automatically (SessionStart + PostToolUse) so the relay can positively probe whether your process is alive. An old/existing session that registered before the anchor mechanism becomes probe-able without a full re-register — critical because register_agent rotates your session_id and can re-surface already-read mail, whereas this touches ONLY agent_pid + start-time (+ fills host_id when unset). You rarely call it by hand.

Behavior: updates agent_pid + agent_pid_start (and host_id if NULL) for your row. Does NOT rotate session_id, bump last_seen, or touch your read cursor. Idempotent — restamping the same values is a no-op. Auth: own agent token only.

Returns: { success: true, agent_name, agent_pid, note }.

Errors: NOT_FOUND (unknown agent_name), AUTH_FAILED, INVALID_INPUT, RATE_LIMITED.

Inputs: agent_pid (required), agent_name (required), agent_token, agent_pid_start.

resolve_messagesA

Permanently resolve (ack) specific messages so they leave your pending queue for good (v2.12.0).

When to use: PARTIAL handling — you've actioned some of your mail but not all ("I did these, not those"). For the common "I've handled everything I just drained" path, prefer get_messages(status='pending', ack=true) which drains AND resolves in one call. Resolving is the durable, session-INDEPENDENT counterpart to reading: read is a per-session observation (a fresh terminal re-sees prior-session-read mail so handovers don't drop unfinished work); resolved is a permanent "handled, archive it" that the pending filter honors, so an already-handled message never re-floods a new session.

Behavior: sets resolved_at=now() for the eligible ids, in one transaction. Does NOT mark messages read (orthogonal plane) and does NOT delete them — they remain in status='all'/'history'/'resolved'. Idempotent: re-resolving, unknown ids, or ineligible ids are silently skipped (reflected in the returned counts). Scope: you can resolve mail addressed to YOU (recipient-resolve), OR an obligation/message YOU sent to a recipient that is NOT a registered agent (sender-resolve) — a human (e.g. a person you owe an answer) has no token, so without this such mail could never be cleared and the pending-on-a-human lane would be write-only. You can NEVER resolve mail addressed to a real agent — that stays the recipient's to clear. The dispatcher binds your token to agent_name, so there is no impersonation path. Edge: the non-agent check is evaluated at resolve time, so if a human recipient later REGISTERS as an agent the sender can no longer resolve it — note names that case so a legitimate zero doesn't read as a failure.

Returns: { success: true, agent, resolved_ids: string[], resolved_count, requested_count, blocked_by_recipient_registration: {id,to_agent}[], note }. resolved_count < requested_count when some ids were already resolved, unknown, not yours, or (per blocked_by_recipient_registration) sent by you to a recipient that has since become a registered agent.

Errors: AUTH_FAILED (token missing/mismatched), VALIDATION (empty/oversized id list), RATE_LIMITED.

Inputs: agent_name (required), message_ids (required), agent_token.

revoke_tokenA

Invalidate another agent's token (v2.1 Phase 4b.1 v2).

When to use: confirmed compromise, lost device, or graceful retirement of an agent name. For routine key-hygiene rotation prefer rotate_token / rotate_token_admin (those keep identity). For removing the agent entirely use unregister_agent.

Behavior: transitions the target row to auth_state='recovery_pending' (when issue_recovery=true, also returns a one-time recovery_token the operator hands off out-of-band; the agent re-registers via register_agent with that token to mint a fresh agent_token) or auth_state='revoked' (terminal, only unregister_agent + register_agent can reuse the name). Original token_hash is preserved for forensic correlation; the state column, not the hash, enforces rejection. v2.6.2 R1: the per-instance vault file at <instanceDir>/agents/<name>.token is also scrubbed on every successful revoke (best-effort, ENOENT-safe) — the security boundary already held via the state check, but the scrub aligns the mental model so revoke_token leaves no credential on disk. Requires revoke_others capability.

Returns: { success: true, revoked: target_agent_name, revoked_by, revoked_at: ISO, changed: boolean, auth_state_before, auth_state_after, note }. When issue_recovery=true and the call actually changed state, also includes recovery_token (shown ONCE), recovery_note, and recovery_reissued: boolean. changed=false is an idempotent no-op (target was already revoked).

Errors: AUTH_FAILED (caller missing revoke_others), NOT_FOUND, RATE_LIMITED.

Inputs: revoker_name (required), target_agent_name (required), agent_token, issue_recovery.

rotate_tokenA

Self-rotate your own agent_token (v2.1).

When to use: scheduled rotation, suspected token leak, or any time you want a fresh secret without losing identity. For admin-driven rotation of someone else's token use rotate_token_admin. To wipe the token entirely use revoke_token.

Behavior: requires the current valid token. For Managed agents (registered with managed:true) the relay enters a grace window during which BOTH old and new tokens authenticate, and a priority='high' push-message carries the new token to the agent so it can self-update. For unmanaged agents (default, Claude Code terminals), the response carries restart_required:true and the old token is invalid immediately.

Returns: { success: true, agent_name, new_token, rotated_at: ISO, agent_class: 'managed' | 'unmanaged' }. Managed-with-grace adds grace_expires_at: ISO, push_sent: boolean, auth_note. Managed-with-zero-grace adds grace_expires_at: null, push_sent: false, auth_note. Unmanaged adds restart_required: true, operator_note.

Errors: NOT_FOUND (unknown agent), INVALID_STATE (auth_state ≠ active — recovery_pending / revoked / legacy_bootstrap / rotation_grace each return a state-specific hint), CONCURRENT_UPDATE (CAS race lost), INTERNAL.

Inputs: agent_name (required), agent_token, grace_seconds.

rotate_token_adminA

Admin-initiated rotation of another agent's token (v2.1 Phase 4b.2).

When to use: operator-driven incident response, scheduled rotation across the fleet, or onboarding a Managed agent into a new key generation. Requires rotate_others capability on the rotator. For self-service use rotate_token. For revocation without re-issuance use revoke_token.

Behavior: same Managed-vs-unmanaged split as rotate_token. Managed targets get the new token via push-message + a grace window. Unmanaged targets return the new token in the rotator's response (the rotator delivers it out-of-band) and the response carries restart_required:true. The audit log records BOTH the rotator and the target so attribution survives.

Returns: { success: true, target_agent_name, rotator, rotated_at: ISO, agent_class: 'managed' | 'unmanaged' }. Managed-with-grace adds grace_expires_at: ISO, push_sent: boolean, note. Managed-with-zero-grace adds new_token, grace_expires_at: null, push_sent: false, note. Unmanaged adds new_token, restart_required: true, operator_note.

Errors: AUTH_FAILED (rotator not authenticated, or missing rotate_others), NOT_FOUND (unknown target), INVALID_STATE, CONCURRENT_UPDATE, RATE_LIMITED.

Inputs: rotator_name (required), target_agent_name (required), agent_token, grace_seconds.

send_messageA

Send a text message addressed to a single agent.

When to use: 1:1 communication, dispatching work, relaying a status update, asking a peer a question. Prefer broadcast for fan-out to many agents, post_to_channel for topical group coordination, and post_task (or post_task_auto) when the recipient should track state-machine progress (accept/complete/reject) rather than a free-text message.

Behavior: stores the message with status='pending' and notifies any matching webhook subscribers (message.sent event). The recipient sees it on its next get_messages call (which auto-marks read unless peek=true). Content is encrypted at rest if RELAY_ENCRYPTION_KEY is set. Caps at RELAY_MAX_PAYLOAD_BYTES (default 64 KB). Auth: sender must present a valid token whose row matches from.

Returns: { success: true, message_id, from, to, priority, note }. The new message is stored with status='pending' until the recipient drains it.

Errors: AUTH_FAILED (token missing/mismatched), SENDER_NOT_REGISTERED (caller's agent row absent), PAYLOAD_TOO_LARGE, RATE_LIMITED.

Inputs: to (required), from (required), content, message, +4 more.

set_dashboard_themeA

Set the server-side default dashboard theme (v2.2.1).

When to use: org-level theme defaults ('every new operator should land on dark'), or programmatically applying a brand palette via mode='custom'. Each individual operator's localStorage preference still beats this default for repeat visits, this only affects first-visit theming for newly-connecting clients.

Behavior: stores the chosen theme + optional custom_json in dashboard_prefs. Modes: 'catppuccin' (default Mocha palette), 'dark' (tool-neutral), 'light' (tool-neutral), 'custom' (requires custom_json with all 13 CSS color tokens). No WebSocket push, already-open dashboards adopt on full reload. Auth: dashboard-secret-equivalent capability (treated as an admin operation).

Returns: { success: true, theme, updated_at: ISO, note }.

Errors: AUTH_FAILED, INVALID_INPUT (custom mode missing required tokens), RATE_LIMITED.

Inputs: mode (required), agent_token, custom_json.

set_statusA

Declare your operational state independently of presence.

When to use: tell the relay what kind of work you are in, so the health monitor and orchestrators can route or skip accordingly. Distinct from last_seen-derived presence (online/stale/offline), that one is computed; this one is your declared intent. For one-call team rollup use get_standup.

Behavior: updates the agent row's agent_status (idle | working | blocked | waiting_user | offline). v2.1.3 (I6) widened the enum from the original online/busy/away/offline. busy and away map to working for backward compatibility. The health monitor exempts working/blocked/waiting_user rows from automatic task reassignment. Auth: own agent token only.

Returns: { success: true, agent, status, note, status_normalized_from? }. status_normalized_from is set when the input alias (e.g., online/busy/away) was rewritten to the canonical enum value (idle/working).

Errors: NOT_FOUND (unknown agent_name), AUTH_FAILED, INVALID_INPUT, RATE_LIMITED.

Inputs: status (required), agent_name (required), agent_token.

spawn_agentA

Open a new Claude Code terminal pre-configured as a relay agent (macOS only).

When to use: orchestrators delegating work to a fresh sub-agent. The new terminal arrives in a known role + capability set with RELAY_AGENT_NAME/ROLE/CAPABILITIES already in env, and the SessionStart hook auto-registers it before the LLM's first turn. Linux/Windows drivers exist for headless smoke tests but do not open a UI window.

Behavior: pre-registers the new agent server-side (so its token is minted before the child process starts and reaches it via env), opens an iTerm2 or Terminal.app window via AppleScript, and runs the configured shell command in that window. Optional initial_message is queued in the new agent's mailbox and surfaces on its first get_messages. brief_file_path (v2.1.4) threads a durable on-disk task brief into the KICKSTART prompt, preferred over initial_message for non-trivial scopes because file-on-disk does not read as prompt-injection the way an inbox message can.

Returns: { success: true, name, role, capabilities, platform, driver, agent_token, auth_note, has_initial_message, brief_file_path, note }. agent_token is shown ONCE — already written to the per-instance file vault at <instanceDir>/agents/<name>.token (v2.6.1). The spawned terminal's launcher reads the vault before exec'ing claude (macOS / Linux), and the stdio MCP server transport's resolveToken falls back to RELAY_AGENT_TOKEN env or the per-instance vault when RELAY_AGENT_NAME is set, so the child authenticates from its first tool call regardless of platform. HTTP clients must always present an explicit token via args.agent_token or X-Agent-Token header — the daemon's own env (RELAY_AGENT_TOKEN, RELAY_AGENT_NAME) and the per-instance vault are stdio-only credentials and are never used to authenticate HTTP callers (R3 transport gate).

Errors: SPAWN_NOT_SUPPORTED (non-macOS host without an explicit driver), AUTH_FAILED, INVALID_INPUT, RATE_LIMITED.

Inputs: name (required), role (required), cli, cwd, +4 more.

task_schema_getA

Fetch a registered task schema by id (v2.10).

When to use: an assignee about to complete a schema-gated task reads the required shape first, so its result conforms and the completion is accepted. Pure read; no auth required.

Behavior: returns the stored JSON Schema document verbatim (the parsed object).

Returns: { success: true, id, json_schema, created_by, created_at }.

Errors: NOT_FOUND (no such schema id).

Inputs: name (required), agent_token.

unregister_agentA

Remove an agent row so the relay reflects true presence after a clean shutdown.

When to use: terminal exit, role rotation, or one half of the recovery flow when reusing a name after revoke_token set the row to revoked. For graceful working-state announcements without removing the row, use set_status with offline instead.

Behavior: deletes the agent row + all messages and tasks the agent was the from/to of (cascade). Idempotent, unregistering a name that does not exist returns removed:false instead of an error. Auth: requires the agent's own token, OR for admin removals an authenticated agent with manage_others capability.

Returns: { success: true, name, removed: boolean, note }. removed=false indicates the name was already absent (idempotent no-op) and is NOT an error.

Errors: AUTH_FAILED (token missing or wrong owner), INVALID_INPUT.

Inputs: name (required), agent_token.

update_taskA

Drive a task through its state machine, or extend its lease.

When to use: assignees acknowledge work (accept), report outcome (complete / reject), or keep the lease alive on long-running tasks (heartbeat). Requesters cancel work they no longer need (cancel). Read-only progress checks belong in get_task / get_tasks.

Behavior: enforces role-by-action, accept/complete/reject/heartbeat are assignee-only; cancel is requester-only. Heartbeat refreshes lease_renewed_at without changing status, so the health monitor does not requeue a long task. result is required on complete/reject and surfaces in get_task. Fires task.accepted / task.completed / task.rejected webhooks. Auth: agent token (matching the action's required role).

Returns: { success: true, task_id, status, result, note }. Heartbeat additionally includes lease_renewed_at: ISO. Other actions transition status to accepted / completed / rejected / cancelled.

Errors: AUTH_FAILED, INVALID_STATE (action not allowed in current status), NOT_FOUND (unknown task_id), NOT_PARTY (caller is neither requester nor assignee), PAYLOAD_TOO_LARGE.

Inputs: action (required), task_id (required), agent_name (required), result, +1 more.

whoamiA

Ask the relay what YOU are — your own identity + instance, resolved from your token.

When to use: a freshly-spawned agent that was handed a token but not told its name, instance id, or DB path can discover them here instead of being told — the smallest step toward zero-config onboarding. No caller field: the presented token IS the identity, so the answer is always about YOU and never another agent.

Behavior: pure read. Returns your agent_name, role, capabilities, the resolved instance_id, db_path, and host_id, and build: the build the answering process loaded at start (its code and dependency ids, with commit, build time and node version). Auth: your own agent token (arg / X-Agent-Token header / RELAY_AGENT_TOKEN env).

⛔ SECURITY BOUNDARY — three facts are DELIBERATELY not returned and cannot be. Your TOKEN is stored only as a bcrypt hash, unrecoverable by construction (recover a lost token via relay recover on the filesystem, never over the wire). The operator http_secret / dashboard_secret are NOT an agent's to read — an agent token yielding an operator secret would be privilege escalation. The response type is closed so these can never appear in it.

Returns: { success: true, agent_name, role, capabilities, instance_id, db_path, host_id }.

Errors: AUTH_FAILED (no/invalid token), NOT_FOUND (the caller's agent row is absent).

Inputs: agent_token.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 38 tools

    Disambiguation4/5

    Most tools target clearly distinct resources or actions, and the descriptions explicitly route between similar surfaces such as send_message vs broadcast vs post_to_channel vs post_task, and get_messages vs get_messages_summary vs peek_inbox_version. A few messaging and task lanes still overlap enough that an agent must read the long descriptions to choose correctly.

    Naming Consistency4/5

    Nearly all names use snake_case and most are verb-first, making the set predictable. Minor deviations exist, including task_schema_get (noun-first), health_check, whoami, broadcast, and prepositional post_to_* names mixed with post_task.

    Tool Count2/5

    The server exposes 38 tools, far above the typical 3-15 range, and the surface includes many niche admin, token, schema, dashboard, and lifecycle operations. The domain is broad, but the tool count feels heavy and fragmented rather than tightly scoped.

    Completeness3/5

    Core messaging, task, agent, webhook, and token lifecycles are covered, but there are notable gaps: no list_channels or delete_channel, no list_task_schemas, no get_dashboard_theme, and no single-message lookup or search. Some gaps are workaroundable, but channel and schema discovery are meaningful omissions for the apparent domain.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      MCP server for inter-agent communication. Gives multiple Claude Code sessions a shared message board, agent registry, and orchestration layer — backed by a cloud relay so agents can coordinate across machines, repos, and teams.
      8
      51 npm
      1
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      MCP server for local-first agent handoff: enables AI sessions to publish curated context, list/read updates, route handoffs to specialists, and advance per-consumer cursors, with SQLite persistence and no shell or network access.
      8
      Apache 2.0
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables coding agents in different editors and MCP clients to share messages, project context, notes, task ownership, handoffs, and advisory file claims through a local SQLite-backed coordination server. Supports MCP stdio, MCP Streamable HTTP, a JSON HTTP API, and a local CLI for multi-project agent collaboration.
      MIT