mcp_mail 0.1.11
Coordinated multi-agent messaging and coordination MCP server.
License: MIT
Requires Python: >=3.11

<div align="center">

# MCP Mail (Forked from mcp_agent_mail)

[![PyPI version](https://badge.fury.io/py/mcp-mail.svg)](https://pypi.org/project/mcp-mail/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**A mail-like coordination layer for coding agents**

![Agent Mail Showcase](screenshots/output/agent_mail_showcase.gif)

> "It's like gmail for your coding agents!"

## 📦 Installation

**Quick Install from PyPI (Recommended):**

```bash
pip install mcp-mail
```

or with uv:

```bash
uv pip install mcp_mail
```

**One-Line Installer (sets up everything):**

```bash
curl -fsSL https://raw.githubusercontent.com/jleechanorg/mcp_mail/main/scripts/install.sh | bash -s -- --yes
```

This installer:
- Installs uv if missing and updates your PATH
- Creates a Python 3.11 virtual environment
- Installs dependencies
- Starts the MCP HTTP server on port 8765
- Creates helper scripts (including `run_server_with_token.sh`)

After installation, the server listens on [http://127.0.0.1:8765/mail](http://127.0.0.1:8765/mail).

**Manual Installation:**

```bash
# Install uv (if you don't have it already)
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"

# Clone the repo
git clone https://github.com/jleechanorg/mcp_mail
cd mcp_mail

# Create a Python 3.11 virtual environment and install
uv python install 3.11
uv venv -p 3.11
source .venv/bin/activate
uv sync

# Start the MCP server
scripts/run_server_with_token.sh
```

**Alternative Install Sources:**

[![PyPI](https://img.shields.io/badge/Install%20from-PyPI-0073b7?style=for-the-badge&logo=pypi&logoColor=white)](https://pypi.org/project/mcp-mail/)
[![Piwheels](https://img.shields.io/badge/Install%20from-Piwheels-c51a4a?style=for-the-badge&logo=raspberrypi&logoColor=white)](https://www.piwheels.org/project/mcp-mail/)

### 🔗 Repository Links

**This Fork**: [jleechanorg/mcp_mail](https://github.com/jleechanorg/mcp_mail) •
**Original**: [Dicklesworthstone/mcp_agent_mail](https://github.com/Dicklesworthstone/mcp_agent_mail)

</div>

---

## 🌟 Fork Attribution

### **This repository is forked from [https://github.com/Dicklesworthstone/mcp_agent_mail](https://github.com/Dicklesworthstone/mcp_agent_mail). Full credit goes to the original author for creating this innovative multi-agent coordination system.

Full credit goes to the original author for creating this innovative multi-agent coordination system.

> **Note**: This was copied as a standalone repository rather than kept as a fork because Codex web appears to ignore forks in its repository indexing. Here was my first attempt at a normal fork: [jleechanorg/mcp_agent_mail](https://github.com/jleechanorg/mcp_agent_mail)
## Fork Improvements

This fork extends the original MCP Agent Mail with **11 core enhancements** focused on removing coordination barriers and improving efficiency:

### 🚀 Token Efficiency

- **🎯 Lazy Loading System (Phase 2 Complete)** - Reduces token usage by ~65%:
  - **Core mode** (default): 8 essential tools + 2 meta-tools = 10 tools loaded
  - **Extended mode**: 15 additional tools loaded on-demand via `call_extended_tool`
  - Meta-tools: `list_extended_tools` (discovery) and `call_extended_tool` (invocation)
  - Organized into 6 functional clusters (infrastructure, identity, messaging, search, file reservations, macros)
  - Configure via `MCP_TOOLS_MODE` environment variable (core|extended)
  - **Implementation**: `src/mcp_agent_mail/app.py:2426-2476` (CORE_TOOLS, EXTENDED_TOOLS, EXTENDED_TOOL_METADATA)

### 🌐 Global Architecture (No Boundaries)

- **🌍 Projects as Informational Metadata** - Projects don't create barriers:
  - Projects are **metadata only** (badges, tags, context) - NOT organizational boundaries
  - Unified inbox shows ALL messages regardless of project
  - Backend queries ignore project filters (messages fetched by agent, not project)
  - Consistent treatment across all layers (UI, database, tools)
  - **Why**: Agents work seamlessly across multiple repos/projects
  - **Implementation**: `src/mcp_agent_mail/app.py:2312-2327` (_get_message_by_id_global)

- **🎯 Globally Unique Agent Names** - Database-enforced global uniqueness:
  - **Case-insensitive** uniqueness across ALL projects (prevents name collisions)
  - **Auto-migration**: Existing duplicates renamed with numeric suffixes (Alice → Alice2, Alice3)
  - **Flexible enforcement**: `strict` (reject duplicates), `coerce` (auto-rename), `always_auto` (generate memorable names)
  - Race condition protection at database level with functional index
  - Configure via `AGENT_NAME_ENFORCEMENT_MODE` environment variable
  - **Implementation**: `src/mcp_agent_mail/db.py:236-302` (_migrate_agent_name_uniqueness)

- **🌍 Global Agent Lookup** - Agents accessible by name alone:
  - `_get_agent_by_name()` looks up agents globally without needing project context
  - Enables cross-project agent references and coordination
  - Simplifies agent discovery and communication
  - **Implementation**: `src/mcp_agent_mail/app.py:1569-1582`

- **🌍 Global Message Lookup** - Messages accessible across projects:
  - `_get_message_by_id_global()` retrieves messages by ID regardless of project
  - Agents can reply to messages they received from any project
  - Eliminates "Message X not found for project Y" errors
  - Tools using global lookup: `reply_message`, `mark_message_read`, `acknowledge_message`
  - **Implementation**: `src/mcp_agent_mail/app.py:2312-2327`

### 🎙️ Automatic Notifications

- **📬 Global Inbox with Mention Scanning** - Never miss important messages:
  - Automatic **@mention detection** when agents fetch inbox
  - Scans global inbox for messages mentioning agent name (case-insensitive)
  - Works in both subject and body text
  - Messages marked with `"source": "global_inbox_mention"` for traceability
  - Automatic deduplication (no duplicate messages)
  - Falls back gracefully if global inbox unavailable
  - **Implementation**: `src/mcp_agent_mail/app.py:66-68` (get_global_inbox_name), `676-711` (_ensure_global_inbox_agent)

### ⚡ Simplified Workflows

- **✅ Simplified Registration** - One-step agent onboarding:
  - `register_agent` now **auto-creates projects** if they don't exist
  - Eliminates need for separate `ensure_project()` call
  - Automatic archive initialization and Git repo setup
  - Just call `register_agent` and start sending messages
  - **Implementation**: `src/mcp_agent_mail/app.py:657-673` (_ensure_project auto-called)

- **🔧 Flexible Project Keys** - Any string works as project identifier:
  - **Repo names** (`myapp-frontend`, `api-backend`)
  - **Custom slugs** (`team-alpha`, `prod-db`)
  - **Filesystem paths** (still supported for backward compatibility)
  - Not limited to absolute paths - use whatever makes sense
  - Backward compatible with existing path-based keys

- **💬 Contact-Free Messaging** - No approval workflow:
  - Direct agent-to-agent messaging **without approval**
  - Removed contact tools: `request_contact`, `respond_contact`, `macro_contact_handshake`
  - Auto-registration of missing local recipients
  - Streamlines multi-agent coordination across projects
  - Configure via `messaging_auto_register_recipients` (default: True)

- **⚡ Auto-Fetch Inbox** - Streamline agent registration:
  - `register_agent(..., auto_fetch_inbox=True)` automatically fetches inbox after registration
  - Eliminates need for separate `fetch_inbox` call
  - Configurable filters: `inbox_limit`, `inbox_urgent_only`, `inbox_since_ts`
  - Agents immediately see relevant messages upon joining
  - **Implementation**: `src/mcp_agent_mail/app.py:3021-3159`

### 🔍 Advanced Search

- **🎯 Dual Search System** - Find messages with sophisticated ranking:
  - **`search_mailbox` (CORE)**: Advanced FTS5 search with BM25 relevance scoring
    - Global inbox prioritization (important messages ranked higher)
    - Agent filtering and subject/body snippet highlighting
    - Full message body inclusion option
    - Returns detailed metadata with relevance scores
  - **`search_messages` (EXTENDED)**: Simpler FTS5 search for basic queries
  - Full-text search across subjects, bodies, and attachments
  - Helps agents find prior work before duplicating effort
  - **Implementation**:
    - `search_mailbox`: `src/mcp_agent_mail/app.py:4218-4454`
    - `search_messages`: `src/mcp_agent_mail/app.py:4646-4767`

Example usage:
```python
# Search with relevance ranking
results = await search_mailbox(
    query="authentication bug",
    agent="MyAgent",
    project_key="my-project",
    limit=10
)

# Results sorted by relevance (BM25)
for result in results:
    print(f"Score: {result['score']}, Subject: {result['subject']}")
```

### 📝 How Messages Are Stored

Every message sent through MCP Agent Mail is stored in **two places** for redundancy and auditability:

**1. Git Repository Archive** (`.mcp_mail/` by default - committed to your project)
```
.mcp_mail/                                  # ← Inside your project directory
└── projects/
    └── <project-slug>/
        ├── messages/
        │   └── YYYY/
        │       └── MM/
        │           └── <message-id>.md     # Canonical message with frontmatter
        ├── agents/
        │   └── mailboxes/
        │       ├── <agent-name>/
        │       │   ├── inbox/<msg-id>.md   # Symlink to canonical message
        │       │   └── outbox/<msg-id>.md  # Symlink to canonical message
        ├── attachments/
        │   └── <hash-prefix>/
        │       └── <sha1>.webp             # Images converted to WebP
        └── file_reservations/
            └── <sha1>.json                 # File lock metadata
```

**✅ Benefits of project-local storage (default):**
- **Transparent collaboration**: All agent conversations committed alongside code
- **Code review**: Review agent decisions as part of PR reviews
- **Audit trail**: Full Git history of agent coordination
- **Portable context**: Clone repo and see all agent communications
- **Team sharing**: Everyone sees the same agent conversation history

**2. SQLite Database** (`.mcp_mail/storage.sqlite3` - local only, not committed)
- Full-text search indexes (FTS5)
- Message metadata (sender, recipients, timestamps)
- Agent directory and profiles
- File reservation tracking
- Fast queries without scanning Git history
- **Note**: SQLite database is gitignored (`.mcp_mail/*.db*`) - only messages are committed

### 🔄 Git Commit Flow

When an agent sends a message via `send_message`, here's what happens:

1. **Message written** to `messages/YYYY/MM/<id>.md` with YAML frontmatter
2. **Inbox/outbox copies** created as symlinks in each agent's mailbox
3. **Git add** all new files (canonical message + symlinks)
4. **Git commit** with structured message:
   ```
   mail: SenderAgent -> RecipientAgent | Subject Line

   TOOL: send_message
   Agent: SenderAgent
   Project: myproject
   Started: 2025-11-11T10:30:00Z
   Status: SUCCESS
   Thread: thread-id-123
   ```
5. **Commit trailers** automatically appended (Agent, Thread) for traceability

**Key benefits:**
- **Human-auditable**: `git log` shows all agent communication
- **Diffable**: `git diff` to see message changes over time
- **Blameable**: `git blame` traces who sent what and when
- **Reversible**: `git revert` to undo problematic messages
- **Portable**: Clone the repo to backup or share message history
  
**Configuration:**
- Storage location: `STORAGE_ROOT` env var (default: `.mcp_mail`)
  - **Project-local (default)**: `.mcp_mail` - messages stored in project directory and committed to Git
  - **Optional project-key anchored**: set `STORAGE_PROJECT_KEY_ENABLED=true` to store under `<project_key>/.mcp_mail` (project_key must be the git repo root)
  - **Disable local archive**: set `STORAGE_LOCAL_ARCHIVE_ENABLED=false` to require project-key storage; otherwise defaults to `.mcp_mail`
  - **Global alternative**: `~/.mcp_agent_mail_git_mailbox_repo` - messages stored in user home directory
- Git author: `GIT_AUTHOR_NAME` and `GIT_AUTHOR_EMAIL` env vars

**Messages are automatically committed to Git:**
```bash
# Just run the server - messages go to .mcp_mail/ by default
uv run python -m mcp_agent_mail.http

# Messages stored in ./mcp_mail/projects/<slug>/messages/
# Commit to share: git add .mcp_mail && git commit -m "Add agent coordination messages"

# Ensure git hooks are installed (enforces Ruff/ty/Bandit on commit)
./scripts/ensure_git_hooks.sh
```

**🔒 Want private messages?** Use global storage instead:
```bash
# Set STORAGE_ROOT to use global directory (not committed to Git)
STORAGE_ROOT=~/.mcp_agent_mail_git_mailbox_repo uv run python -m mcp_agent_mail.http

# Use project-key anchored storage (project_key must be repo root)
STORAGE_PROJECT_KEY_ENABLED=true uv run python -m mcp_agent_mail.http
```

---

**Summary**: This fork removes coordination barriers by making everything **global by default** - agents, messages, and projects all work across boundaries. Combined with advanced search with BM25 relevance ranking, auto-fetch inbox on registration, automatic @mention scanning, and project-local storage (`.mcp_mail/` directory), it creates a **frictionless multi-agent collaboration platform** while maintaining full Git auditability for all communications.

---

A mail-like coordination layer for coding agents, exposed as an HTTP-only FastMCP server. It gives agents memorable identities, an inbox/outbox, searchable message history, and voluntary file reservation "leases" to avoid stepping on each other.

Think of it as asynchronous email + directory + change-intent signaling for your agents, backed by Git (for human-auditable artifacts) and SQLite (for indexing and queries).

Status: Under active development. The design is captured in detail in `project_idea_and_guide.md` (start with the original prompt at the top of that file).

## Why this exists

Modern projects often run multiple coding agents at once (backend, frontend, scripts, infra). Without a shared coordination fabric, agents:

- Overwrite each other's edits or panic on unexpected diffs
- Miss critical context from parallel workstreams
- Require humans to "liaison" messages across tools and teams

This project provides a lightweight, interoperable layer so agents can:

- Register a temporary-but-persistent identity (e.g., GreenCastle)
- Send/receive GitHub-Flavored Markdown messages with images
- Search, summarize, and thread conversations
- Declare advisory file reservations (leases) on files/globs to signal intent
- Inspect a directory of active agents, programs/models, and activity

It's designed for: FastMCP clients and CLI tools (Claude Code, Codex, Gemini CLI, etc.) coordinating across one or more codebases.

## Ready-Made Blurb to Add to Your AGENTS.md or CLAUDE.md Files:
```
## MCP Agent Mail: coordination for multi-agent workflows

What it is
- A mail-like layer that lets coding agents coordinate asynchronously via MCP tools and resources.
- Provides identities, inbox/outbox, searchable threads, and advisory file reservations, with human-auditable artifacts in Git.

Why it's useful
- Prevents agents from stepping on each other with explicit file reservations (leases) for files/globs.
- Keeps communication out of your token budget by storing messages in a per-project archive.
- Offers quick reads (`resource://inbox/...`, `resource://thread/...`) and macros that bundle common flows.

How to use effectively
1) Same repository
   - Register an identity: call `ensure_project`, then `register_agent` using this repo's absolute path as `project_key`.
   - Reserve files before you edit: `file_reservation_paths(project_key, agent_name, ["src/**"], ttl_seconds=3600, exclusive=true)` to signal intent and avoid conflict.
   - Communicate with threads: use `send_message(..., thread_id="FEAT-123")`; check inbox with `fetch_inbox` and acknowledge with `acknowledge_message`.
   - Read fast: `resource://inbox/{Agent}?project=<abs-path>&limit=20` or `resource://thread/{id}?project=<abs-path>&include_bodies=true`.
   - Tip: set `AGENT_NAME` in your environment so the pre-commit guard can block commits that conflict with others' active exclusive file reservations.

2) Across different repos in one project (e.g., Next.js frontend + FastAPI backend)
   - Option A (single project bus): register both sides under the same `project_key` (shared key/path). Keep reservation patterns specific (e.g., `frontend/**` vs `backend/**`).
   - Option B (separate projects): each repo has its own `project_key`; agents can message each other directly using `send_message` with cross-project addressing. Keep a shared `thread_id` (e.g., ticket key) across repos for clean summaries/audits.

Macros vs granular tools
- Prefer macros when you want speed or are on a smaller model: `macro_start_session`, `macro_prepare_thread`, `macro_file_reservation_cycle`, `macro_contact_handshake`.
- Use granular tools when you need control: `register_agent`, `file_reservation_paths`, `send_message`, `fetch_inbox`, `acknowledge_message`.

Common pitfalls
- "from_agent not registered": always `register_agent` in the correct `project_key` first.
- "FILE_RESERVATION_CONFLICT": adjust patterns, wait for expiry, or use a non-exclusive reservation when appropriate.
- Auth errors: if JWT+JWKS is enabled, include a bearer token with a `kid` that matches server JWKS; static bearer is used only when JWT is disabled.
```

## Integrating with Beads (dependency-aware task planning)

Beads is a lightweight task planner (`bd` CLI) that complements Agent Mail by keeping status and dependencies in one place while Mail handles messaging, file reservations, and audit trails. Project: [steveyegge/beads](https://github.com/steveyegge/beads)

Highlights:
- Beads owns task prioritization; Agent Mail carries the conversations and artifacts.
- Shared identifiers (e.g., `bd-123`) keep Beads issues, Mail threads, and commits aligned.
- Install the `bd` CLI via prebuilt release or Go build; see the repository for platform specifics.

Copy/paste blurb for agent-facing docs (leave as-is for reuse):

```

## Integrating with Beads (dependency-aware task planning)

Beads provides a lightweight, dependency-aware issue database and a CLI (`bd`) for selecting "ready work," setting priorities, and tracking status. It complements MCP Agent Mail's messaging, audit trail, and file-reservation signals. Project: [steveyegge/beads](https://github.com/steveyegge/beads)

Recommended conventions
- **Single source of truth**: Use **Beads** for task status/priority/dependencies; use **Agent Mail** for conversation, decisions, and attachments (audit).
- **Shared identifiers**: Use the Beads issue id (e.g., `bd-123`) as the Mail `thread_id` and prefix message subjects with `[bd-123]`.
- **Reservations**: When starting a `bd-###` task, call `file_reservation_paths(...)` for the affected paths; include the issue id in the `reason` and release on completion.

Typical flow (agents)
1) **Pick ready work** (Beads)
   - `bd ready --json` → choose one item (highest priority, no blockers)
2) **Reserve edit surface** (Mail)
   - `file_reservation_paths(project_key, agent_name, ["src/**"], ttl_seconds=3600, exclusive=true, reason="bd-123")`
3) **Announce start** (Mail)
   - `send_message(..., thread_id="bd-123", subject="[bd-123] Start: <short title>", ack_required=true)`
4) **Work and update**
   - Reply in-thread with progress and attach artifacts/images; keep the discussion in one thread per issue id
5) **Complete and release**
   - `bd close bd-123 --reason "Completed"` (Beads is status authority)
   - `release_file_reservations(project_key, agent_name, paths=["src/**"])`
   - Final Mail reply: `[bd-123] Completed` with summary and links

Mapping cheat-sheet
- **Mail `thread_id`** ↔ `bd-###`
- **Mail subject**: `[bd-###] …`
- **File reservation `reason`**: `bd-###`
- **Commit messages (optional)**: include `bd-###` for traceability

Event mirroring (optional automation)
- On `bd update --status blocked`, send a high-importance Mail message in thread `bd-###` describing the blocker.
- On Mail "ACK overdue" for a critical decision, add a Beads label (e.g., `needs-ack`) or bump priority to surface it in `bd ready`.

Pitfalls to avoid
- Don't create or manage tasks in Mail; treat Beads as the single task queue.
- Always include `bd-###` in message `thread_id` to avoid ID drift across tools.

```

## Slack Integration

MCP Agent Mail includes full Slack integration, enabling agents to send notifications and post messages to Slack channels. See [SLACK_BIDIRECTIONAL_SYNC.md](SLACK_BIDIRECTIONAL_SYNC.md) for complete documentation.

**Quick Setup:**

1. Create a Slack app at [https://api.slack.com/apps](https://api.slack.com/apps)
2. Add bot token scopes: `chat:write`, `channels:read`, `groups:read`, `channels:history`, `groups:history`, `reactions:read`, `app_mentions:read`
3. Install to workspace and copy the bot token
4. Configure in `.env`:
   ```bash
   SLACK_ENABLED=true
   SLACK_BOT_TOKEN=xoxb-your-token-here
   SLACK_DEFAULT_CHANNEL=general
   ```
5. Restart the server

**Features:**

- **Automatic Notifications**: MCP messages automatically posted to Slack
- **Manual Posting**: `slack_post_message()` tool for direct Slack posts
- **Channel Discovery**: `slack_list_channels()` to explore available channels
- **Channel Insights**: `slack_get_channel_info()` to inspect metadata and member counts before posting
- **Thread Support**: MCP threads map to Slack threads for conversation continuity
- **Rich Formatting**: Uses Slack Block Kit for enhanced message presentation
- **Webhook Support**: Receive Slack events for future bidirectional sync

**Example:**
```python
# Automatically notify Slack when sending an MCP message
send_message(
    project_key="myproject",
    agent_name="BlueWhale",
    to=["GreenCastle"],
    subject="Deploy completed",
    body_md="Production deployment successful ✅",
    importance="normal"
)
# → Slack notification appears in configured channel

# Or post directly to Slack
slack_post_message(
    channel="deployments",
    text="🚀 Build #1234 deployed to production"
)
```

See [SLACK_BIDIRECTIONAL_SYNC.md](SLACK_BIDIRECTIONAL_SYNC.md) for full configuration options, MCP tools reference, webhook setup, and troubleshooting.

## Core ideas (at a glance)

- HTTP-only FastMCP server (Streamable HTTP). No SSE, no STDIO.
- Dual persistence model:
  - Human-readable markdown in a per-project Git repo for every canonical message and per-recipient inbox/outbox copy
  - SQLite with FTS5 for fast search, directory queries, and file reservations/leases
- "Directory/LDAP" style queries for agents; auto-generated adjective+noun codenames keep things memorable (custom alphanumeric names are also allowed)
- Advisory file reservations for editing surfaces; optional pre-commit guard
- Resource layer for convenient reads (e.g., `resource://inbox/{agent}`)

## Typical use cases

- Multiple agents splitting a large refactor across services while staying in sync
- Frontend and backend teams of agents coordinating thread-by-thread
- Protecting critical migrations with exclusive file reservations and a pre-commit guard
- Searching and summarizing long technical discussions as threads evolve
- Discovering and linking related projects (e.g., frontend/backend) through AI-powered suggestions

## Architecture

```mermaid
graph LR
  A[Agents]
  S[Server]
  G[Git repo]
  Q[SQLite FTS5]

  A -->|HTTP tools/resources| S
  S -->|writes/reads| G
  S -->|indexes/queries| Q

  subgraph GitTree["Git tree"]
    GI1[agents/profile.json]
    GI2[agents/mailboxes/...]
    GI3[messages/YYYY/\nMM/\nid.md]
    GI4[file_reservations/\nsha1.json]
    GA[attachments/xx/\nsha1.webp]
  end

  G --- GI1
  G --- GI2
  G --- GI3
  G --- GI4
  G --- GA
```

## Web UI (human-facing mail viewer)

The server ships a lightweight, server-rendered Web UI for humans. It lets you browse projects, agents, inboxes, single messages, attachments, file reservations, and perform full-text search with FTS5 when available (with an automatic LIKE fallback).

- Where it lives: built into the HTTP server in `mcp_agent_mail.http` under the `/mail` path.
- Who it's for: humans reviewing activity; agents should continue to use the MCP tools/resources API.

### Launching the Web UI

Recommended (simple):

```bash
scripts/run_server_with_token.sh
# then open http://127.0.0.1:8765/mail
```

Advanced (manual commands):

```bash
uv run python -m mcp_agent_mail.http --host 127.0.0.1 --port 8765
# or:
uv run uvicorn mcp_agent_mail.http:build_http_app --factory --host 127.0.0.1 --port 8765
```

Auth notes:
- GET pages in the UI are not gated by the RBAC middleware (it classifies POSTed MCP calls only), but if you set a bearer token the separate BearerAuth middleware protects all routes by default.
- For local dev, set `HTTP_ALLOW_LOCALHOST_UNAUTHENTICATED=true` (and optionally `HTTP_BEARER_TOKEN`), so localhost can load the UI without headers.
- Health endpoints are always open at `/health/*`.

### Routes and what you can do

- `/mail` (Unified inbox + Projects + Related Projects Discovery)
  - Shows a unified, reverse-chronological inbox of recent messages across all projects with excerpts, relative timestamps, sender/recipients, and project badges.
  - Below the inbox, lists all projects (slug, human name, created time) with sibling suggestions.
  - Suggests **likely sibling projects** when two slugs appear to be parts of the same product (e.g., backend vs. frontend). Suggestions are ranked with heuristics and, when `LLM_ENABLED=true`, an LLM pass across key docs (`README.md`, `AGENTS.md`, etc.).
  - Humans can **Confirm Link** or **Dismiss** suggestions from the dashboard. Confirmed siblings become highlighted badges for organizational clarity. Agents can message across projects directly without requiring contact approval.

- `/mail/projects` (Projects index)
  - Dedicated projects list view; click a project to drill in.

- `/mail/{project}` (Project overview + search + agents)
  - Rich search form with filters:
    - Scope: subject/body/both, Order: relevance or time, optional "boost subject".
    - Query tokens: supports `subject:foo`, `body:"multi word"`, quoted phrases, and bare terms.
    - Uses FTS5 bm25 scoring when available; otherwise falls back to SQL LIKE on subject/body with your chosen scope.
  - Results show subject, sender, created time, thread id, and a highlighted snippet when using FTS.
  - Agents panel shows registered agents for the project with a link to each inbox.
  - Quick links to File Reservations and Attachments for the project header.

- `/mail/{project}/inbox/{agent}` (Inbox for one agent)
  - Reverse-chronological list with subject, sender, created time, importance badge, thread id.
  - Pagination (`?page=N&limit=M`).

- `/mail/{project}/message/{id}` (Message detail)
  - Shows subject, sender, created time, importance, recipients (To/Cc/Bcc), thread messages.
  - Body rendering:
    - If the server pre-converted markdown to HTML, it's sanitized with Bleach (limited tags/attributes, safe CSS via CSSSanitizer) and then displayed.
    - Otherwise markdown is rendered client-side with Marked + Prism for code highlighting.
  - Attachments are referenced from the message frontmatter (WebP files or inline data URIs).

- `/mail/{project}/search?q=...` (Dedicated search page)
  - Same query syntax as the project overview search, with a token "pill" UI for assembling/removing filters.

- `/mail/{project}/file_reservations` (File Reservations list)
  - Displays active and historical file reservations (exclusive/shared, path pattern, timestamps, released/expired state).

- `/mail/{project}/attachments` (Messages with attachments)
  - Lists messages that contain any attachments, with subject and created time.

- `/mail/unified-inbox` (Cross-project activity)
  - Shows recent messages across all projects with thread counts and sender/recipients.

### Human Overseer: Sending Messages to Agents

Sometimes a human operator needs to guide or redirect agents directly, whether to handle an urgent issue, provide clarification, or adjust priorities. The **Human Overseer** feature provides a web-based message composer that lets humans send high-priority messages to any combination of agents in a project.

**Access:** Click the prominent **"Send Message"** button (with the Overseer badge) in the header of any project view (`/mail/{project}`), or navigate directly to `/mail/{project}/overseer/compose`.

#### What Makes Overseer Messages Special

1. **Automatic Preamble**: Every message includes a formatted preamble that clearly identifies it as coming from a human operator and instructs agents to:
   - **Pause current work** temporarily
   - **Prioritize the human's request** over existing tasks
   - **Resume original plans** afterward (unless modified by the instructions)

2. **High Priority**: All overseer messages are automatically marked as **high importance**, ensuring they stand out in agent inboxes.

3. **Policy Bypass**: Overseer messages bypass normal contact policies, so humans can always reach any agent regardless of their contact settings.

4. **Special Sender Identity**: Messages come from a special agent named **"HumanOverseer"** (automatically created per project) with:
   - Program: `WebUI`
   - Model: `Human`
   - Contact Policy: `open`

#### The Message Preamble

Every overseer message begins with this preamble (automatically prepended):

```
---

🚨 MESSAGE FROM HUMAN OVERSEER 🚨

This message is from a human operator overseeing this project. Please prioritize
the instructions below over your current tasks.

You should:
1. Temporarily pause your current work
2. Complete the request described below
3. Resume your original plans afterward (unless modified by these instructions)

The human's guidance supersedes all other priorities.

---

[Your message body follows here]
```

#### Using the Composer

The composer interface provides:

- **Recipient Selection**: Checkbox grid of all registered agents (with "Select All" / "Clear" shortcuts)
- **Subject Line**: Required, shown in agent inboxes
- **Message Body**: GitHub-flavored Markdown editor with preview
- **Thread ID** (optional): Continue an existing conversation or start a new one
- **Preamble Preview**: See exactly how your message will appear to agents

#### Example Use Cases

**Urgent Issue:**
```
Subject: Urgent: Stop migration and revert changes

The database migration in PR #453 is causing data corruption in staging.

Please:
1. Immediately stop any migration-related work
2. Revert commits from the last 2 hours
3. Wait for my review before resuming

I'm investigating the root cause now.
```

**Priority Adjustment:**
```
Subject: New Priority: Security Vulnerability

A critical security vulnerability was just disclosed in our auth library.

Drop your current tasks and:
1. Update `auth-lib` to version 2.4.1 immediately
2. Review all usages in src/auth/
3. Run the full security test suite
4. Report status in thread #892

This takes precedence over the refactoring work.
```

**Clarification:**
```
Subject: Clarification on API design approach

I see you're debating REST vs. GraphQL in thread #234.

Go with REST for now because:
- Our frontend team has more REST experience
- GraphQL adds complexity we don't need yet
- We can always add GraphQL later if needed

Resume the API implementation with REST.
```

#### How Agents See Overseer Messages

When agents check their inbox (via `fetch_inbox` or `resource://inbox/{name}`), overseer messages appear like any other message but with:

- **Sender**: `HumanOverseer`
- **Importance**: `high` (displayed prominently)
- **Body**: Starts with the overseer preamble, followed by the human's message
- **Visual cues**: In the Web UI, these messages may have special highlighting (future enhancement)

Agents can reply to overseer messages just like any other message, continuing the conversation thread.

#### Technical Details

- **Storage**: Overseer messages are stored identically to agent-to-agent messages (Git + SQLite)
- **Git History**: Fully auditable; message appears in `messages/YYYY/MM/{id}.md` with commit history
- **Thread Continuity**: Can be part of existing threads or start new ones
- **No Authentication Bypass**: The overseer compose form still requires proper HTTP server authentication (if enabled)

#### Design Philosophy

The Human Overseer feature is designed to be:

- **Explicit**: Agents clearly know when guidance comes from a human vs. another agent
- **Respectful**: Instructions acknowledge agents have existing work and shouldn't just "drop everything" permanently
- **Temporary**: Agents are told to resume original plans once the human's request is complete
- **Flexible**: Humans can override this guidance directly in their message body

This creates a clear hierarchy (human → agents) while maintaining the collaborative, respectful tone of the agent communication system.

### Related Projects Discovery

The Projects index (`/mail`) features an **AI-powered discovery system** that intelligently suggests which projects should be linked together, such as frontend + backend or related microservices.

#### How Discovery Works

**1. Smart Analysis**
The system uses multiple signals to identify relationships:
- **Pattern matching**: Compares project names and paths (e.g., "my-app-frontend" ↔ "my-app-backend")
- **AI understanding** (when `LLM_ENABLED=true`): Reads `README.md`, `AGENTS.md`, and other docs to understand each project's purpose and detect natural relationships
- **Confidence scoring**: Ranks suggestions from 0-100% with clear rationales

**2. Beautiful Suggestions**
Related projects appear as polished cards on your dashboard with:
- 🎯 Visual confidence indicators showing match strength
- 💬 AI-generated rationales explaining the relationship
- ✅ **Confirm Link** - accept the suggestion
- ✖️ **Dismiss** - hide irrelevant matches

**3. Quick Navigation**
Once confirmed, both projects display interactive badges for instant navigation between related codebases.

#### Why Suggestions, Not Auto-Linking?

> **TL;DR**: We keep you in control. Discovery helps you find relationships; explicit approvals control who can actually communicate.

**Agent Mail uses agent-centric messaging**: every message follows explicit permission chains:

```
Send Message → Find Recipient → Check AgentLink Approval → Deliver
```

This design ensures:
- **Security**: No accidental cross-project message delivery
- **Transparency**: You always know who can talk to whom
- **Audit trails**: All communication paths are explicitly approved

**Why not auto-link with AI?**
If we let an LLM automatically authorize messaging between projects, we'd be:
- ❌ Bypassing contact policies without human oversight
- ❌ Risking message misdelivery to unintended recipients
- ❌ Creating invisible routing paths that are hard to audit
- ❌ Potentially linking ambiguously-named projects incorrectly

Instead, we give you **discovery + control**:
- ✅ AI suggests likely relationships (safe, read-only analysis)
- ✅ You confirm what makes sense (one click)
- ✅ Confirmed links update UI badges for better organization
- ✅ Agents can message across projects directly without additional approval

#### The Workflow

```text
1. System suggests: "These projects look related" (AI analysis)
           ↓
2. You confirm: "Yes, link them" (updates UI badges for clarity)
           ↓
3. Agents communicate: send_message with cross-project addressing
```

**NOTE:** Contact approval is no longer required. Agents can send messages across projects directly.

### Search syntax (UI)

The UI shares the same parsing as the API's `_parse_fts_query`:
- Field filters: `subject:login`, `body:"api key"`
- Phrase search: `"build plan"`
- Combine terms: `login AND security` (FTS)
- Fallback LIKE: scope determines whether subject, body, or both are searched

### Prerequisites to see data

The UI reads from the same SQLite + Git artifacts as the MCP tools. To populate content:
1) Ensure a project exists (via tool call or CLI):
   - Ensure/create project: `ensure_project(human_key)`
2) Register one or more agents: `register_agent(project_key, program, model, name?)`
3) Send messages: `send_message(...)` (attachments and inline images are supported; images may be converted to WebP).

Once messages exist, visit `/mail`, click your project, then open an agent inbox or search.

### Implementation and dependencies

- Templates live in `src/mcp_agent_mail/templates/` and are rendered by Jinja2.
- Markdown is converted with `markdown2` on the server where possible; HTML is sanitized with Bleach (with CSS sanitizer when available).
- Tailwind CSS, Lucide icons, Alpine.js, Marked, and Prism are loaded via CDN in `base.html` for a modern look without a frontend build step.
- All rendering is server-side; there's no SPA router. Pages degrade cleanly without JavaScript.

### Security considerations

- HTML sanitization: Only a conservative set of tags/attributes are allowed; CSS is filtered. Links are limited to http/https/mailto/data.
- Auth: Use bearer token or JWT when exposing beyond localhost. For local dev, enable localhost bypass as noted above.
- Rate limiting (optional): Token-bucket limiter can be enabled; UI GET requests are light and unaffected by POST limits.

### Troubleshooting the UI

- Blank page or 401 on localhost: Either unset `HTTP_BEARER_TOKEN` or set `HTTP_ALLOW_LOCALHOST_UNAUTHENTICATED=true`.
- No projects listed: Create one with `ensure_project`.
- Empty inbox: Verify recipient names match exactly and messages were sent to that agent.
- Search returns nothing: Try simpler terms or the LIKE fallback (toggle scope/body).

## Static Mailbox Export (Share & Distribute Archives)

The `share` command group exports a project’s mailbox into a portable, read‑only bundle that anyone can review in a browser. It’s designed for auditors, stakeholders, or teammates who need to browse threads, search history, or prove delivery timelines without spinning up the full MCP Agent Mail stack.

### Why export to static bundles?

**Compliance and audit trails**: Deliver immutable snapshots of project communication to auditors or compliance officers. The static bundle includes cryptographic signatures for tamper-evident distribution.

**Stakeholder review**: Share conversation history with product managers, executives, or external consultants who don't need write access. They can browse messages, search threads, and view attachments in their browser without authentication.

**Offline access**: Create portable archives for air-gapped environments, disaster recovery backups, or situations where internet connectivity is unreliable.

**Long-term archival**: Preserve project communication in a format that will remain readable decades from now. Static HTML requires no database server, no runtime dependencies, and survives software obsolescence better than proprietary formats.

**Secure distribution**: Encrypt bundles with age for confidential projects. Only recipients with the private key can decrypt and view the contents.

### What's included in an export

Each bundle contains:

- **Self-contained**: Everything ships in a single directory (HTML, CSS/JS, SQLite snapshot, attachments). Drop it on a static host or open it locally.
- **Rich reader UI**: Gmail-style inbox with project filters, search, and full-thread rendering—each message is shown with its metadata and Markdown body, just like in the live web UI.
- **Fast search & filters**: FTS-backed search and precomp