MCP Agent Mail

repository·main·Indexed 24 days ago

https://github.com/dicklesworthstone/mcp_agent_mail

A coordinated multi-agent messaging and coordination MCP server that provides a communication layer for multi-agent coding environments. It features agent identities, asynchronous messaging via FastMCP/HTTP, and file reservation 'leases' to prevent workspace conflicts. The system maintains an auditable history using Git and SQLite and integrates with Beads Rust (br) and Beads Viewer (bv) for task planning and graph-based analysis.

Tokens
94.3K
Snippets
160
Records
461
Agent score
84%

What's inside mcp-agent-mail

  1. What is MCP Agent Mail?

    main

    MCP Agent Mail is a mail-like coordination layer for coding agents, exposed as an HTTP-only FastMCP server. It provides a shared communication fabric for multiple agents (e.g., backend, frontend, infra) to prevent conflicts and maintain context.

    Core Features:

    • Identities: Agents can register temporary-but-persistent identities (e.g., GreenCastle).
    • Messaging: Supports sending/receiving GitHub-Flavored Markdown messages with images.
    • Searchable History: Provides an inbox/outbox and searchable message archives.
    • File Leases: Allows agents to declare advisory file reservations (leases) on files or globs to signal intent and avoid overwriting each other's work.
    • Auditability: Backed by Git (for human-auditable artifacts) and SQLite (for indexing and queries).
    • Observability: Allows inspection of active agents, programs/models, and activity.
  2. Explore the Web UI routes and features

    main

    The MCP Agent Mail Web UI provides several views for managing and inspecting agent communications:

    • /mail: The unified inbox. Shows a reverse-chronological list of recent messages across all projects with excerpts, timestamps, and project badges. It also includes a project list with Related Projects Discovery suggestions.
    • /mail/projects: A dedicated index view of all projects.
    • /mail/{project}: The project overview page. Includes a rich search form, an agents panel, and quick links to File Reservations and Attachments.
    • /mail/{project}/inbox/{agent}: A specific agent's inbox within a project. Supports pagination via ?page=N&limit=M.
    • /mail/{project}/message/{id}: Detailed view of a single message, including thread history, recipients, and attachments.
    • /mail/{project}/search?q=...: A dedicated search page for the project.
    • /mail/{project}/file_reservations: List of active and historical file reservations.
    • /mail/{project}/attachments: A list of all messages in the project containing attachments.
    • /mail/unified-inbox: A cross-project view of recent activity.
  3. Use a Service Layer architecture with FastMCP

    main

    To maintain a clean separation of concerns, implement a Service Layer. The MCP server (the presentation layer) should only handle MCP-specific concerns like I/O and validation. The actual business logic should reside in a separate service class. This makes the logic testable and independent of the MCP framework.

    # services/filing_service.py - Business logic layer
    class FilingService:
        async def process_filing(self, filing_id: int) -> Filing:
            # ... complex business logic ...
    
    # servers/filings_server.py - MCP Presentation layer
    from services.filing_service import FilingService
    
    mcp = FastMCP(name="FilingServer")
    
    @mcp.tool
    async def process_filing_tool(filing_id: int):
        # Tool only handles MCP concerns (I/O, validation)
        service = FilingService(...) # Dependency injection
        result = await service.process_filing(filing_id)
        # Return a ToolResult or Pydantic model
        return result
  4. How FastMCP components work (Tools, Resources, Prompts)

    main

    FastMCP servers expose capabilities through three primary component types that follow the Model Context Protocol (MCP) standard:

    • Tools: Executable functions that perform actions or produce side effects (analogous to POST requests). LLMs invoke these to change state or trigger processes.
    • Resources: Read-only data sources identified by a unique URI (analogous to GET requests). They provide context to the LLM via idempotent information retrieval.
    • Prompts: Reusable, parameterized message templates that provide structured instructions to guide LLM behavior for specific tasks.
  5. Verify bundle signature integrity

    main

    Signature verification ensures the bundle has not been tampered with. For verification to succeed, the following must be present and intact:

    1. The original manifest.json (unmodified).
    2. The manifest.sig.json file (containing the signature and public key).
    3. All assets referenced in the manifest must have matching SHA-256 hashes.

    If verification fails, the bundle is likely corrupted or tampered with; you should re-export and re-transfer the data.

  6. Compose multiple FastMCP servers

    main

    To manage complexity, use server composition instead of complex router-level dependencies. You can create specialized FastMCP instances (e.g., for admin tools) and mount them onto a main FastMCP server using the .mount() method with a specific prefix. This allows sub-servers to have their own specific configurations, such as unique authentication providers.

    # Main server
    main_mcp = FastMCP(name="MainServer")
    
    # Create a sub-server for admin tools
    admin_mcp = FastMCP(name="AdminTools")
    # Add bearer token auth provider only to this server
    # mcp.auth = BearerAuthProvider(...)
    
    @admin_mcp.tool
    def sensitive_operation(): ...
    
    # Mount the admin server with a prefix and its own auth
    main_mcp.mount(admin_mcp, prefix="admin")
  7. Understand the Per-Pane Agent Identity Contract

    main

    The Per-Pane Agent Identity Contract defines a canonical way to map a tmux pane to a specific agent name. This allows shell scripts, hooks, and external tools to discover which agent is running in a specific pane without querying the MCP server.

    Identities are stored in a file-based system following the XDG Base Directory Specification, ensuring they persist across reboots but remain separate from configuration. The system uses a project-specific hash to ensure multi-project safety.

  8. How the MCP Request Lifecycle works in FastMCP

    main

    When a client sends a request (such as tools/call), it passes through a structured lifecycle. Understanding this flow is essential for developing middleware or debugging complex tool interactions.

    Request Flow Stages

    1. Transport Layer: Receives raw input (HTTP POST or STDIO) and deserializes the JSON-RPC message.
    2. Core Server Dispatch: The FastMCP instance determines the message type (request vs. notification) and method.
    3. Middleware Chain (Pre-processing): The request enters the middleware pipeline. Middleware can modify the context or terminate the request early.
    4. Component Manager: The request is routed to the appropriate manager (e.g., ToolManager or ResourceManager). The manager handles component lookup and checks mounted servers.
    5. Parameter Validation & Coercion: The manager uses Pydantic TypeAdapters to validate client arguments against the Python function's type hints (e.g., coercing a string to a datetime).
    6. Context Injection: If the target function's signature includes a Context object, the server injects it.
    7. Function Execution: The user's Python function is executed with validated arguments.
    8. Result Serialization: The return value is converted into ContentBlocks or structured_content. If the function doesn't return a ToolResult, one is automatically created.
    9. Middleware Chain (Post-processing): The result flows back up the middleware chain in reverse order, allowing middleware to inspect or modify the output.
    10. Transport Layer Response: The final result is serialized into a JSON-RPC response and sent to the client.
  9. Beads Rust (br) vs Beads Go (bd)

    main

    The project uses Beads Rust (br) as its primary task tracker. The installer automatically replaces the original Go-based Beads CLI (bd) with the Rust implementation.

    Key Details:

    • Maintenance: br is the actively maintained version; the Go version is no longer maintained.
    • Compatibility: The installer creates a shell alias so that bd commands redirect to br, preserving existing workflows.
    • Data Format: Both implementations use the same .beads/issues.jsonl format, ensuring existing Beads data remains compatible.
    • Agent Support: AI coding agents are provided with a bd-br-migration skill to handle CLI differences between the two versions.
  10. Macros vs Granular Tools in MCP Agent Mail

    main

    When interacting with MCP Agent Mail, choose between high-level macros for speed/simplicity or granular tools for precise control.

    Use Macros for:

    • Speed and efficiency, especially when using smaller models.
    • Common flows: macro_start_session, macro_prepare_thread, macro_file_reservation_cycle, macro_contact_handshake.

    Use Granular Tools for:

    • Precise control over the workflow.
    • Specific actions: register_agent, file_reservation_paths, send_message, fetch_inbox, acknowledge_message.
  11. Understand File Reservation Path Semantics

    main

    File reservations in Agent Mail use repo-root relative paths rather than absolute OS paths. This ensures compatibility across different worktrees and machines.

    Path Matching Rules

    • Storage: Patterns are stored exactly as provided (e.g., app/api/*.py).
    • Normalization: All paths are normalized for separators (/ vs \) and case (on case-insensitive filesystems).
    • Matching: The pre-commit guard matches staged files against reservations using Git wildmatch pathspec. It honors core.ignorecase and handles renames/moves by checking both the new path and the old path (via git diff --name-status -M).
    • Best Practice: Use narrow patterns (e.g., frontend/**) instead of broad patterns (e.g., **/*) to minimize unnecessary conflicts across teams.
  12. Integrate MCP Agent Mail with Flywheel Tools

    main

    MCP Agent Mail provides integration capabilities for various Flywheel tools:

    • NTM: Agent panes coordinate via mail; the dashboard displays the inbox.
    • BV: Task IDs are mapped to thread IDs; robot flags inform task selection.
    • CASS: Enables searching mail threads across different sessions.
    • CM: Allows extraction of procedural memory from mail archives.
    • DCG: Notifies agents when commands are blocked.
    • RU: Facilitates multi-repo updates via cross-project mail.