Friday, November 27, 2026

BUILDING INTELLIGENT MULTI-AGENT SYSTEMS WITH GOOGLE'S A2A PROTOCOL



A PRACTICAL GUIDE TO AGENT-TO-AGENT COMMUNICATION

The landscape of artificial intelligence has evolved dramatically from single, monolithic models to sophisticated ecosystems of specialized agents working in concert. While individual language models have become remarkably capable, the real power emerges when multiple agents collaborate, each bringing unique expertise to solve complex problems. However, this collaboration requires a standardized way for agents to communicate, negotiate, and coordinate their efforts. This is precisely where Google's Agent-to-Agent protocol, commonly known as A2A, enters the picture.

Imagine a software development team where each member has deep expertise in a specific domain. The frontend specialist, backend architect, database administrator, and DevOps engineer must communicate effectively to build a cohesive system. Similarly, in an agentic AI system, we need research agents, writing agents, fact-checking agents, and coordination agents to work together seamlessly. Without a common language and protocol, this coordination becomes chaotic and unreliable.

Google's A2A protocol, launched with contributions from over fifty technology partners, provides exactly this common language. It establishes a standardized framework for how agents discover each other, advertise their capabilities, negotiate tasks, exchange information, and coordinate their activities. Think of it as a combination of HTTP for message transport, JSON-RPC for remote procedure calls, and a service discovery mechanism all rolled into one, but specifically designed for the unique requirements of AI agents.

UNDERSTANDING THE A2A PROTOCOL FUNDAMENTALS

The A2A protocol is built on several core principles that distinguish it from traditional inter-process communication mechanisms. At its heart, A2A recognizes that AI agents are not just passive services waiting for requests, but active entities with goals, capabilities, constraints, and the ability to reason about their interactions.

The protocol is designed around key architectural principles that make it practical for enterprise deployment. First is agent independence, which means agents can collaborate in their natural modalities without needing to share internal logic, memory, tools, or context. Each agent remains autonomous while participating in larger collaborative workflows. Second, the protocol builds upon existing web standards like HTTP, Server-Sent Events for streaming, and JSON-RPC 2.0 for remote procedure calls. This means developers can leverage familiar tools and libraries rather than learning entirely new technologies. Third, security is built in from the ground up, supporting enterprise-grade authentication and authorization including OAuth and API keys. Fourth, the protocol handles flexible timelines, supporting tasks ranging from instant queries to multi-day workflows without requiring different communication patterns. Finally, A2A is content type agnostic, supporting various modalities including text, images, videos, audio, PDFs, and structured data.

The protocol defines several fundamental components that work together to enable agent collaboration. The A2A Client, also called the client agent, is an application, service, or AI agent that requests actions or information from a remote agent. The A2A Server, also called the remote agent, is an AI agent that exposes an HTTP endpoint, receives requests, processes tasks, and returns results. The Agent Card is a JSON metadata document that agents use to advertise their capabilities, identity, service endpoint, version, supported A2A capabilities, and authentication requirements. This allows client agents to discover and identify suitable remote agents. Tasks represent stateful, traceable units of work executed by an agent to achieve specific outcomes and generate artifacts. Messages are the basic units for exchanging information between users and agents, supporting multiple content types.

Communication in A2A occurs over HTTP and HTTPS, with JSON-RPC 2.0 serving as the payload format for all requests and responses. This choice leverages JSON-RPC's stateless, lightweight, and transport-agnostic nature, providing a standardized way for applications to invoke methods or procedures on remote systems. The Content-Type header for JSON-RPC payloads is set to application/json.

Let's examine the structure of an Agent Card to understand how agents advertise their capabilities. An Agent Card is typically made available at a well-known URI, specifically at the path /.well-known/agent.json on the agent's domain. This follows the RFC 8615 standard for well-known URIs, making agent discovery straightforward and predictable.

Here is what a real Agent Card looks like in practice:

{
  "protocolVersion": "0.2.5",
  "name": "WeatherBot",
  "description": "Provides accurate weather forecasts and historical data for any location.",
  "url": "https://weather.example.com/a2a/api",
  "provider": {
    "name": "Example Weather Services Inc.",
    "url": "https://example.com/weather"
  },
  "version": "1.0.0",
  "documentationUrl": "https://weather.example.com/a2a/docs",
  "capabilities": {
    "streaming": true,
    "pushNotifications": false,
    "stateTransitionHistory": true
  },
  "securitySchemes": {
    "bearerAuth": {
      "type": "http",
      "scheme": "bearer",
      "bearerFormat": "JWT"
    }
  },
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "defaultInputModes": [
    "text/plain",
    "application/json"
  ],
  "defaultOutputModes": [
    "text/plain",
    "application/json"
  ],
  "skills": [
    {
      "id": "getCurrentWeather",
      "name": "Get Current Weather",
      "description": "Retrieves real-time weather conditions for a specified location.",
      "tags": ["weather", "current", "real-time"],
      "examples": [
        "What's the weather like in London?",
        "Current temperature in New York City"
      ],
      "inputModes": ["text/plain"],
      "outputModes": ["application/json"]
    },
    {
      "id": "getForecast",
      "name": "Get Weather Forecast",
      "description": "Provides a weather forecast for a specified location and period.",
      "tags": ["weather", "forecast", "future"],
      "examples": [
        "5-day forecast for Paris",
        "Will it rain in Berlin tomorrow?"
      ],
      "inputModes": ["text/plain"],
      "outputModes": ["application/json"]
    }
  ]
}

In this example, the WeatherBot agent clearly identifies itself with a human-readable name and description. The protocolVersion field indicates this agent supports version 0.2.5 of the A2A protocol. The url field specifies the base endpoint for the agent's A2A service. The capabilities section indicates that this agent supports streaming responses and maintains state transition history, but does not support push notifications. The securitySchemes and security fields define that clients must authenticate using a bearer token in JWT format. The skills array is particularly important, as it lists the specific capabilities this agent offers. Each skill has a unique identifier, descriptive name, detailed description, relevant tags, example queries that would trigger this skill, and the input and output MIME types it supports.

When a client agent wants to interact with this weather agent, it first retrieves the Agent Card from the well-known URI. The client can then examine the available skills, determine which one matches its needs, check the authentication requirements, and prepare an appropriately formatted request.

TASK LIFECYCLE AND STATE MANAGEMENT

One of the most sophisticated aspects of the A2A protocol is its task management system. Tasks are the fundamental unit of work in A2A, and they progress through a well-defined lifecycle with various states indicating their current stage.

When a client agent sends a request to a remote agent, the remote agent may determine that fulfilling the request requires completing a task. Each task is assigned a unique task identifier that the client can use for future messages related to that task. The task then progresses through various states as the agent works on it.

The submitted state indicates the task has been initiated and sent to the remote agent. The working state means the remote agent is actively processing the task. The input-required state signals that the task requires additional information or action from the client agent to proceed. This is particularly important for interactive workflows where the agent needs clarification or additional context. The completed state indicates the task has been successfully finished. The canceled state means the task was terminated before completion, usually by request from the client. The failed state indicates the task encountered an error and could not be completed successfully. The unknown state is used when the current state of the task is not known. The rejected state means the task was declined by the agent, perhaps because it lacks the necessary capabilities or resources. The auth-required state indicates the task requires authentication to proceed.

For long-running tasks, clients can periodically poll for status updates until the task reaches a terminal state like completed, failed, or canceled. The protocol also supports streaming responses using Server-Sent Events, allowing the remote agent to push updates to the client as the task progresses without requiring polling.

The JSON-RPC methods that agents use to interact with tasks include message/send for sending initial requests and continuing conversations. When a client sends a message, if a task is initiated, it will have a taskId which the client can use for future messages related to that task. The tasks/get method allows clients to retrieve the current state and details of a specific task. The tasks/send and tasks/sendSubscribe methods are used to start or continue work on tasks, with the subscribe variant enabling streaming responses.

DESIGNING OUR MULTI-AGENT SYSTEM ARCHITECTURE

Now that we understand the A2A protocol fundamentals, let's design a practical multi-agent system that demonstrates these concepts in action. Our system will tackle a common real-world scenario: automated research and report generation. This task naturally decomposes into several specialized subtasks, making it perfect for a multi-agent approach.

Our system will consist of three specialized agents, each with distinct capabilities and responsibilities. The Research Agent specializes in gathering information from various sources, including web search, document analysis, and knowledge synthesis. The Writing Agent takes structured information and transforms it into coherent, well-written prose following specific style guidelines. The Coordinator Agent acts as the orchestrator, receiving high-level user requests, decomposing them into subtasks, and managing the workflow across other agents.

These agents will communicate exclusively through A2A protocol messages, demonstrating agent discovery via Agent Cards, task negotiation and lifecycle management, information exchange through messages, and result aggregation. The beauty of this architecture is that each agent can be implemented independently, potentially using different underlying language models optimized for their specific tasks, yet they all interoperate seamlessly through the standardized protocol.

For our implementation, we will use Python as the primary programming language due to its rich ecosystem of AI and machine learning libraries. We will leverage the official A2A Python SDK developed by the a2aproject organization on GitHub. This SDK provides compliance with the A2A Protocol, extensibility to support various communication protocols and database backends, asynchronous design for high performance, and optional integrations for HTTP servers using FastAPI or Starlette, gRPC, OpenTelemetry for tracing, and SQL databases including PostgreSQL, MySQL, and SQLite.

For local LLM inference with GPU support, we will use llama-cpp-python, which provides excellent support for both Apple Metal Performance Shaders on macOS and NVIDIA CUDA on systems with NVIDIA GPUs. This ensures our system can run efficiently on a wide range of hardware configurations without requiring cloud API access.

The system architecture follows a clean separation of concerns. Each agent is implemented as an independent A2A server with its own HTTP endpoint, Agent Card describing its capabilities, AgentExecutor implementing its core logic, and LLM instance for reasoning and generation. A central discovery mechanism allows agents to find each other through well-known URIs or a registry. The A2A SDK handles all the protocol details including JSON-RPC message formatting, HTTP transport, streaming via Server-Sent Events, and task state management.

SETTING UP THE DEVELOPMENT ENVIRONMENT

Before we start implementing our agents, we need to set up the development environment with all necessary dependencies. We will use uv, a fast Python package installer and manager, to streamline the setup process.

First, install uv if you do not already have it:

curl -LsSf https://astral.sh/uv/install.sh | sh

Create a project directory and set up a virtual environment:

mkdir a2a_multi_agent_research
cd a2a_multi_agent_research
uv venv
source .venv/bin/activate

On Windows, you would use .venv\Scripts\activate instead.

Now install the required packages:

uv pip install a2a-sdk uvicorn llama-cpp-python httpx

The a2a-sdk package provides the core A2A protocol implementation. The uvicorn package is an ASGI server for running our agent HTTP endpoints. The llama-cpp-python package enables local LLM inference with GPU acceleration. The httpx package provides async HTTP client capabilities for agent-to-agent communication.

If you have an NVIDIA GPU and want to use CUDA acceleration, you need to install llama-cpp-python with CUDA support:

CMAKE_ARGS="-DLLAMA_CUDA=on" uv pip install llama-cpp-python --force-reinstall --no-cache-dir

For Apple Silicon Macs with Metal Performance Shaders support:

CMAKE_ARGS="-DLLAMA_METAL=on" uv pip install llama-cpp-python --force-reinstall --no-cache-dir

You will also need a local LLM model in GGUF format. For this tutorial, I recommend downloading a quantized Mistral or Llama model from HuggingFace. For example, you could download Mistral-7B-Instruct in GGUF format from TheBloke's repository. Create a models directory in your project and place the downloaded model file there:

mkdir models
# Download your chosen model to models/model.gguf

With the environment set up, we are ready to start implementing our agents.

IMPLEMENTING THE RESEARCH AGENT

Let's begin by implementing the Research Agent, which will be responsible for gathering and synthesizing information. This agent will expose its capabilities through an Agent Card and implement the AgentExecutor interface to process incoming requests.

Create a file named research_agent.py:

import uvicorn
import asyncio
from llama_cpp import Llama
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.app import A2AStarletteApplication
from a2a.types import AgentCard, AgentCapabilities, AgentSkill, Message, TextPart, Role


class ResearchAgentExecutor(AgentExecutor):
    """
    Executes research tasks using a local LLM.
    Gathers and synthesizes information based on user queries.
    """
    
    def __init__(self, model_path: str):
        """
        Initialize the research agent executor with a local LLM.
        
        Args:
            model_path: Path to the GGUF format model file
        """
        self.llm = self._initialize_llm(model_path)
    
    def _initialize_llm(self, model_path: str) -> Llama:
        """
        Initialize the local LLM with GPU acceleration if available.
        
        Args:
            model_path: Path to the GGUF format model file
            
        Returns:
            Initialized Llama instance
        """
        try:
            import torch
            
            # Detect available GPU acceleration
            n_gpu_layers = 0
            
            if torch.cuda.is_available():
                # NVIDIA CUDA available
                n_gpu_layers = -1  # Offload all layers to GPU
                print("Research Agent: Using NVIDIA CUDA acceleration")
            elif torch.backends.mps.is_available():
                # Apple Metal Performance Shaders available
                n_gpu_layers = 1
                print("Research Agent: Using Apple Metal acceleration")
            else:
                print("Research Agent: Using CPU inference")
                
        except ImportError:
            n_gpu_layers = 0
            print("Research Agent: PyTorch not found, using CPU")
        
        # Initialize llama.cpp with appropriate settings
        llm = Llama(
            model_path=model_path,
            n_gpu_layers=n_gpu_layers,
            n_ctx=4096,  # Context window size
            n_batch=512,  # Batch size for prompt processing
            verbose=False
        )
        
        print("Research Agent: LLM initialized successfully")
        return llm
    
    def _generate_response(self, prompt: str, max_tokens: int = 1024) -> str:
        """
        Generate text using the local LLM.
        
        Args:
            prompt: Input prompt for the LLM
            max_tokens: Maximum number of tokens to generate
            
        Returns:
            Generated text response
        """
        try:
            response = self.llm(
                prompt,
                max_tokens=max_tokens,
                temperature=0.7,
                top_p=0.9,
                stop=["</s>", "Human:", "User:"],
                echo=False
            )
            
            return response['choices'][0]['text'].strip()
            
        except Exception as e:
            return f"Error generating response: {e}"
    
    async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
        """
        Execute a research task based on the incoming request.
        
        Args:
            context: The request context containing the message and task info
            event_queue: Queue for sending back messages and status updates
        """
        # Extract the user's research query from the message
        user_query = ""
        if context.request.message and context.request.message.parts:
            for part in context.request.message.parts:
                if isinstance(part, TextPart):
                    user_query += part.text + " "
        
        user_query = user_query.strip()
        print(f"\nResearch Agent: Received research query: {user_query}")
        
        # Update task status to working
        await event_queue.task_status_update(status="working")
        
        # Construct a research-focused prompt for the LLM
        research_prompt = f"""You are a research assistant with expertise in gathering and synthesizing information. Provide comprehensive, well-structured research on the following topic.

Research Query: {user_query}

Please provide:
1. Key facts and important concepts
2. Relevant background information
3. Current understanding and recent developments
4. Important considerations and nuances

Research Summary:"""
        
        # Generate research findings using the LLM
        research_result = self._generate_response(research_prompt, max_tokens=1024)
        
        print(f"Research Agent: Generated {len(research_result)} characters of research")
        
        # Send the research findings back as a message
        response_message = Message(
            kind="message",
            role=Role.AGENT,
            parts=[TextPart(text=research_result)]
        )
        await event_queue.message(response_message)
        
        # Mark the task as completed
        await event_queue.task_status_update(status="completed")
    
    async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
        """
        Handle cancellation of a research task.
        
        Args:
            context: The request context
            event_queue: Queue for sending status updates
        """
        print(f"Research Agent: Received cancel request for task {context.request.task_id}")
        
        # In a real implementation, you would stop any ongoing LLM generation
        # For this example, we simply acknowledge the cancellation
        await event_queue.task_status_update(status="canceled")


def build_research_agent_card(host: str, port: int) -> AgentCard:
    """
    Build the Agent Card for the Research Agent.
    This advertises the agent's capabilities to potential clients.
    
    Args:
        host: The hostname where the agent is running
        port: The port number where the agent is listening
        
    Returns:
        AgentCard describing the Research Agent
    """
    return AgentCard(
        protocolVersion="0.2.5",
        name="ResearchAgent",
        description="Specialized agent for information gathering and research synthesis. Uses local LLM to provide comprehensive research on various topics.",
        url=f"http://{host}:{port}",
        version="1.0.0",
        capabilities=AgentCapabilities(streaming=True),
        skills=[
            AgentSkill(
                id="research",
                name="Research",
                description="Conducts comprehensive research on a given topic, gathering facts, concepts, and relevant information.",
                tags=["research", "information-gathering", "synthesis"],
                examples=[
                    "Research the benefits of multi-agent AI systems",
                    "Gather information about renewable energy technologies",
                    "Provide background on quantum computing"
                ]
            ),
            AgentSkill(
                id="fact-gathering",
                name="Fact Gathering",
                description="Collects specific facts and data points about a topic.",
                tags=["facts", "data", "information"],
                examples=[
                    "What are the key facts about climate change?",
                    "Gather statistics on global internet usage"
                ]
            )
        ]
    )


async def main():
    """
    Main entry point for the Research Agent.
    Initializes the agent and starts the HTTP server.
    """
    # Configuration
    host = "127.0.0.1"
    port = 8001
    model_path = "models/model.gguf"  # Update this to your model path
    
    print("="*60)
    print("RESEARCH AGENT - A2A PROTOCOL")
    print("="*60)
    print()
    
    # Build the Agent Card
    agent_card = build_research_agent_card(host, port)
    
    # Initialize the executor with the LLM
    executor = ResearchAgentExecutor(model_path)
    
    # Build the A2A application
    app = A2AStarletteApplication(
        agent_card=agent_card,
        agent_executor=executor
    )
    
    # Start the server
    print(f"Starting Research Agent on {host}:{port}")
    print(f"Agent Card available at: http://{host}:{port}/.well-known/agent.json")
    print()
    
    config = uvicorn.Config(
        app.build(),
        host=host,
        port=port,
        log_level="info"
    )
    server = uvicorn.Server(config)
    await server.serve()


if __name__ == "__main__":
    asyncio.run(main())

This Research Agent implementation demonstrates several key A2A concepts. The AgentExecutor class is the core of the agent, implementing the execute method that processes incoming requests and the cancel method that handles task cancellation. The agent initializes a local LLM with automatic GPU detection, supporting both CUDA and Metal acceleration. The Agent Card clearly describes the agent's capabilities through the skills array, making it discoverable by other agents. The agent communicates task progress through the EventQueue's task_status_update method, keeping clients informed about the task lifecycle. Messages are sent back through the EventQueue using the message method, which the A2A SDK manages to ensure proper protocol compliance.

When you run this agent, it starts an HTTP server on port 8001 and automatically exposes its Agent Card at the well-known URI. Other agents can discover this agent by fetching the Agent Card and examining its capabilities.

IMPLEMENTING THE WRITING AGENT

Next, let's implement the Writing Agent, which transforms research findings into polished, well-written content. This agent will demonstrate how A2A agents can build upon the work of other agents.

Create a file named writing_agent.py:

import uvicorn
import asyncio
from llama_cpp import Llama
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.app import A2AStarletteApplication
from a2a.types import AgentCard, AgentCapabilities, AgentSkill, Message, TextPart, Role


class WritingAgentExecutor(AgentExecutor):
    """
    Executes writing tasks using a local LLM.
    Transforms information into well-structured, polished content.
    """
    
    def __init__(self, model_path: str):
        """
        Initialize the writing agent executor with a local LLM.
        
        Args:
            model_path: Path to the GGUF format model file
        """
        self.llm = self._initialize_llm(model_path)
    
    def _initialize_llm(self, model_path: str) -> Llama:
        """
        Initialize the local LLM with GPU acceleration if available.
        
        Args:
            model_path: Path to the GGUF format model file
            
        Returns:
            Initialized Llama instance
        """
        try:
            import torch
            
            n_gpu_layers = 0
            
            if torch.cuda.is_available():
                n_gpu_layers = -1
                print("Writing Agent: Using NVIDIA CUDA acceleration")
            elif torch.backends.mps.is_available():
                n_gpu_layers = 1
                print("Writing Agent: Using Apple Metal acceleration")
            else:
                print("Writing Agent: Using CPU inference")
                
        except ImportError:
            n_gpu_layers = 0
            print("Writing Agent: PyTorch not found, using CPU")
        
        llm = Llama(
            model_path=model_path,
            n_gpu_layers=n_gpu_layers,
            n_ctx=4096,
            n_batch=512,
            verbose=False
        )
        
        print("Writing Agent: LLM initialized successfully")
        return llm
    
    def _generate_response(self, prompt: str, max_tokens: int = 1024) -> str:
        """
        Generate text using the local LLM.
        
        Args:
            prompt: Input prompt for the LLM
            max_tokens: Maximum number of tokens to generate
            
        Returns:
            Generated text response
        """
        try:
            response = self.llm(
                prompt,
                max_tokens=max_tokens,
                temperature=0.7,
                top_p=0.9,
                stop=["</s>", "Human:", "User:"],
                echo=False
            )
            
            return response['choices'][0]['text'].strip()
            
        except Exception as e:
            return f"Error generating response: {e}"
    
    async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
        """
        Execute a writing task based on the incoming request.
        
        Args:
            context: The request context containing the message and task info
            event_queue: Queue for sending back messages and status updates
        """
        # Extract the user's writing request from the message
        user_request = ""
        
        if context.request.message and context.request.message.parts:
            for part in context.request.message.parts:
                if isinstance(part, TextPart):
                    user_request += part.text + " "
        
        user_request = user_request.strip()
        print(f"\nWriting Agent: Received writing request: {user_request}")
        
        # Update task status to working
        await event_queue.task_status_update(status="working")
        
        # Construct a writing-focused prompt for the LLM
        writing_prompt = f"""You are a professional writer and content creator. Your task is to create well-structured, engaging, and polished content.

Writing Task: {user_request}

Please create clear, well-organized content that:
- Has a logical structure with clear flow
- Uses professional yet accessible language
- Includes relevant details and examples
- Maintains reader engagement throughout

Written Content:"""
        
        # Generate written content using the LLM
        written_content = self._generate_response(writing_prompt, max_tokens=1536)
        
        print(f"Writing Agent: Generated {len(written_content)} characters of content")
        
        # Send the written content back as a message
        response_message = Message(
            kind="message",
            role=Role.AGENT,
            parts=[TextPart(text=written_content)]
        )
        await event_queue.message(response_message)
        
        # Mark the task as completed
        await event_queue.task_status_update(status="completed")
    
    async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
        """
        Handle cancellation of a writing task.
        
        Args:
            context: The request context
            event_queue: Queue for sending status updates
        """
        print(f"Writing Agent: Received cancel request for task {context.request.task_id}")
        
        await event_queue.task_status_update(status="canceled")


def build_writing_agent_card(host: str, port: int) -> AgentCard:
    """
    Build the Agent Card for the Writing Agent.
    
    Args:
        host: The hostname where the agent is running
        port: The port number where the agent is listening
        
    Returns:
        AgentCard describing the Writing Agent
    """
    return AgentCard(
        protocolVersion="0.2.5",
        name="WritingAgent",
        description="Specialized agent for content creation and writing. Transforms information into polished, well-structured prose.",
        url=f"http://{host}:{port}",
        version="1.0.0",
        capabilities=AgentCapabilities(streaming=True),
        skills=[
            AgentSkill(
                id="content-writing",
                name="Content Writing",
                description="Creates well-structured, engaging content on various topics.",
                tags=["writing", "content-creation", "prose"],
                examples=[
                    "Write an article about renewable energy",
                    "Create a report on market trends",
                    "Draft a blog post about AI advancements"
                ]
            ),
            AgentSkill(
                id="text-formatting",
                name="Text Formatting",
                description="Formats and structures text for readability and impact.",
                tags=["formatting", "structure", "editing"],
                examples=[
                    "Format this research into a readable article",
                    "Structure these findings into a report"
                ]
            )
        ]
    )


async def main():
    """
    Main entry point for the Writing Agent.
    """
    # Configuration
    host = "127.0.0.1"
    port = 8002
    model_path = "models/model.gguf"  # Update this to your model path
    
    print("="*60)
    print("WRITING AGENT - A2A PROTOCOL")
    print("="*60)
    print()
    
    # Build the Agent Card
    agent_card = build_writing_agent_card(host, port)
    
    # Initialize the executor with the LLM
    executor = WritingAgentExecutor(model_path)
    
    # Build the A2A application
    app = A2AStarletteApplication(
        agent_card=agent_card,
        agent_executor=executor
    )
    
    # Start the server
    print(f"Starting Writing Agent on {host}:{port}")
    print(f"Agent Card available at: http://{host}:{port}/.well-known/agent.json")
    print()
    
    config = uvicorn.Config(
        app.build(),
        host=host,
        port=port,
        log_level="info"
    )
    server = uvicorn.Server(config)
    await server.serve()


if __name__ == "__main__":
    asyncio.run(main())

The Writing Agent follows the same structural pattern as the Research Agent but specializes in content creation. It exposes different skills in its Agent Card, specifically content-writing and text-formatting. The LLM prompt is tailored for writing tasks, emphasizing structure, clarity, and engagement. The agent runs on a different port, allowing both agents to operate simultaneously on the same machine.

IMPLEMENTING THE COORDINATOR AGENT

Now we implement the most sophisticated component: the Coordinator Agent. This agent acts as both an A2A server to receive user requests and an A2A client to communicate with the Research and Writing agents. It demonstrates the full power of multi-agent collaboration.

Create a file named coordinator_agent.py:

import uvicorn
import asyncio
import httpx
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.app import A2AStarletteApplication
from a2a.types import AgentCard, AgentCapabilities, AgentSkill, Message, TextPart, Role
from a2a.client.client import A2AClient


class CoordinatorAgentExecutor(AgentExecutor):
    """
    Coordinates multi-agent workflows by orchestrating tasks across
    specialized agents (Research and Writing agents).
    """
    
    def __init__(self, research_agent_url: str, writing_agent_url: str):
        """
        Initialize the coordinator with URLs of the agents it will coordinate.
        
        Args:
            research_agent_url: Base URL of the Research Agent
            writing_agent_url: Base URL of the Writing Agent
        """
        self.research_agent_url = research_agent_url
        self.writing_agent_url = writing_agent_url
    
    async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
        """
        Execute a coordinated multi-agent workflow.
        
        This method:
        1. Receives a high-level request from the user
        2. Delegates research to the Research Agent
        3. Passes research results to the Writing Agent
        4. Returns the final written content to the user
        
        Args:
            context: The request context containing the user's message
            event_queue: Queue for sending back messages and status updates
        """
        # Extract the user's request
        user_request = ""
        if context.request.message and context.request.message.parts:
            for part in context.request.message.parts:
                if isinstance(part, TextPart):
                    user_request += part.text + " "
        
        user_request = user_request.strip()
        print(f"\nCoordinator: Received request: {user_request}")
        
        # Update task status to working
        await event_queue.task_status_update(status="working")
        
        # Send progress update to user
        progress_message = Message(
            kind="message",
            role=Role.AGENT,
            parts=[TextPart(text="Starting multi-agent workflow. First, I'll gather research...")]
        )
        await event_queue.message(progress_message)
        
        # Step 1: Delegate to Research Agent
        research_result = await self._get_research(user_request)
        
        if research_result.startswith("Error"):
            # Research failed, report error and complete task
            error_message = Message(
                kind="message",
                role=Role.AGENT,
                parts=[TextPart(text=f"Research phase failed: {research_result}")]
            )
            await event_queue.message(error_message)
            await event_queue.task_status_update(status="failed")
            return
        
        print(f"Coordinator: Research completed, {len(research_result)} characters received")
        
        # Send progress update
        progress_message = Message(
            kind="message",
            role=Role.AGENT,
            parts=[TextPart(text="Research complete. Now creating polished content...")]
        )
        await event_queue.message(progress_message)
        
        # Step 2: Delegate to Writing Agent with research results
        writing_request = f"Based on the following research, create a comprehensive, well-structured article:\n\n{research_result}"
        written_content = await self._get_written_content(writing_request)
        
        if written_content.startswith("Error"):
            # Writing failed, report error and complete task
            error_message = Message(
                kind="message",
                role=Role.AGENT,
                parts=[TextPart(text=f"Writing phase failed: {written_content}")]
            )
            await event_queue.message(error_message)
            await event_queue.task_status_update(status="failed")
            return
        
        print(f"Coordinator: Writing completed, {len(written_content)} characters received")
        
        # Step 3: Return final result to user
        final_message = Message(
            kind="message",
            role=Role.AGENT,
            parts=[TextPart(text=f"Multi-agent workflow complete! Here is the final result:\n\n{written_content}")]
        )
        await event_queue.message(final_message)
        
        # Mark task as completed
        await event_queue.task_status_update(status="completed")
    
    async def _get_research(self, query: str) -> str:
        """
        Communicate with the Research Agent to gather information.
        
        Args:
            query: The research query to send to the Research Agent
            
        Returns:
            Research results as a string, or error message
        """
        print(f"Coordinator: Requesting research from {self.research_agent_url}")
        
        async with httpx.AsyncClient(timeout=60.0) as http_client:
            try:
                # Discover the Research Agent via its Agent Card
                research_client = await A2AClient.get_client_from_agent_card_url(
                    http_client=http_client,
                    agent_card_url=f"{self.research_agent_url}/.well-known/agent.json"
                )
                
                print("Coordinator: Successfully discovered Research Agent")
                
                # Create a message to send to the Research Agent
                research_message = Message(
                    kind="message",
                    role=Role.USER,
                    parts=[TextPart(text=query)]
                )
                
                # Send the message and collect the response
                research_result = ""
                async for event in research_client.send_message(message=research_message):
                    if isinstance(event, Message):
                        for part in event.parts:
                            if isinstance(part, TextPart):
                                research_result += part.text
                    # Task status updates are handled automatically by the SDK
                
                return research_result
                
            except httpx.ConnectError as e:
                error_msg = f"Error: Could not connect to Research Agent at {self.research_agent_url}. Is it running?"
                print(f"Coordinator: {error_msg}")
                return error_msg
            except Exception as e:
                error_msg = f"Error during research: {str(e)}"
                print(f"Coordinator: {error_msg}")
                return error_msg
    
    async def _get_written_content(self, writing_request: str) -> str:
        """
        Communicate with the Writing Agent to create polished content.
        
        Args:
            writing_request: The writing request to send to the Writing Agent
            
        Returns:
            Written content as a string, or error message
        """
        print(f"Coordinator: Requesting writing from {self.writing_agent_url}")
        
        async with httpx.AsyncClient(timeout=60.0) as http_client:
            try:
                # Discover the Writing Agent via its Agent Card
                writing_client = await A2AClient.get_client_from_agent_card_url(
                    http_client=http_client,
                    agent_card_url=f"{self.writing_agent_url}/.well-known/agent.json"
                )
                
                print("Coordinator: Successfully discovered Writing Agent")
                
                # Create a message to send to the Writing Agent
                writing_message = Message(
                    kind="message",
                    role=Role.USER,
                    parts=[TextPart(text=writing_request)]
                )
                
                # Send the message and collect the response
                written_content = ""
                async for event in writing_client.send_message(message=writing_message):
                    if isinstance(event, Message):
                        for part in event.parts:
                            if isinstance(part, TextPart):
                                written_content += part.text
                    # Task status updates are handled automatically by the SDK
                
                return written_content
                
            except httpx.ConnectError as e:
                error_msg = f"Error: Could not connect to Writing Agent at {self.writing_agent_url}. Is it running?"
                print(f"Coordinator: {error_msg}")
                return error_msg
            except Exception as e:
                error_msg = f"Error during writing: {str(e)}"
                print(f"Coordinator: {error_msg}")
                return error_msg
    
    async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
        """
        Handle cancellation of a coordination task.
        
        Args:
            context: The request context
            event_queue: Queue for sending status updates
        """
        print(f"Coordinator: Received cancel request for task {context.request.task_id}")
        
        # In a production system, you would also cancel any ongoing subtasks
        # with the Research and Writing agents
        
        await event_queue.task_status_update(status="canceled")


def build_coordinator_agent_card(host: str, port: int) -> AgentCard:
    """
    Build the Agent Card for the Coordinator Agent.
    
    Args:
        host: The hostname where the agent is running
        port: The port number where the agent is listening
        
    Returns:
        AgentCard describing the Coordinator Agent
    """
    return AgentCard(
        protocolVersion="0.2.5",
        name="CoordinatorAgent",
        description="Orchestrates multi-agent workflows by coordinating Research and Writing agents to produce comprehensive reports.",
        url=f"http://{host}:{port}",
        version="1.0.0",
        capabilities=AgentCapabilities(streaming=True),
        skills=[
            AgentSkill(
                id="create-report",
                name="Create Report",
                description="Creates comprehensive reports by coordinating research and writing tasks across multiple specialized agents.",
                tags=["coordination", "orchestration", "multi-agent", "report-generation"],
                examples=[
                    "Create a comprehensive report about renewable energy",
                    "Generate an article on the benefits of multi-agent systems",
                    "Produce a detailed analysis of quantum computing"
                ]
            )
        ]
    )


async def main():
    """
    Main entry point for the Coordinator Agent.
    """
    # Configuration
    host = "127.0.0.1"
    port = 8000
    research_agent_url = "http://127.0.0.1:8001"
    writing_agent_url = "http://127.0.0.1:8002"
    
    print("="*60)
    print("COORDINATOR AGENT - A2A PROTOCOL")
    print("="*60)
    print()
    
    # Build the Agent Card
    agent_card = build_coordinator_agent_card(host, port)
    
    # Initialize the executor
    executor = CoordinatorAgentExecutor(research_agent_url, writing_agent_url)
    
    # Build the A2A application
    app = A2AStarletteApplication(
        agent_card=agent_card,
        agent_executor=executor
    )
    
    # Start the server
    print(f"Starting Coordinator Agent on {host}:{port}")
    print(f"Agent Card available at: http://{host}:{port}/.well-known/agent.json")
    print(f"Coordinating with:")
    print(f"  - Research Agent: {research_agent_url}")
    print(f"  - Writing Agent: {writing_agent_url}")
    print()
    
    config = uvicorn.Config(
        app.build(),
        host=host,
        port=port,
        log_level="info"
    )
    server = uvicorn.Server(config)
    await server.serve()


if __name__ == "__main__":
    asyncio.run(main())

The Coordinator Agent demonstrates the full power of the A2A protocol. It acts as both a server, exposing its own capabilities through an Agent Card, and as a client, discovering and communicating with other agents. The agent uses the A2AClient class to discover other agents via their Agent Cards at well-known URIs. It sends messages to remote agents and processes streaming responses. The coordinator implements a sequential workflow where research results feed into the writing task. Progress updates keep the user informed throughout the multi-step process. Error handling ensures graceful degradation if any agent is unavailable or fails.

CREATING A CLIENT TO TEST THE SYSTEM

Now let's create a simple client application that sends requests to the Coordinator Agent and displays the results. This demonstrates how external applications can interact with A2A agents.

Create a file named client.py:

import asyncio
import httpx
from a2a.client.client import A2AClient
from a2a.types import Message, TextPart, Role


async def send_request_to_coordinator(coordinator_url: str, user_request: str):
    """
    Send a request to the Coordinator Agent and display the results.
    
    Args:
        coordinator_url: Base URL of the Coordinator Agent
        user_request: The user's request to process
    """
    print("="*60)
    print("A2A CLIENT - SENDING REQUEST TO COORDINATOR")
    print("="*60)
    print()
    print(f"Request: {user_request}")
    print()
    
    async with httpx.AsyncClient(timeout=120.0) as http_client:
        try:
            # Discover the Coordinator Agent via its Agent Card
            print(f"Discovering Coordinator Agent at {coordinator_url}...")
            coordinator_client = await A2AClient.get_client_from_agent_card_url(
                http_client=http_client,
                agent_card_url=f"{coordinator_url}/.well-known/agent.json"
            )
            print("Successfully discovered Coordinator Agent")
            print()
            
            # Create a message to send
            user_message = Message(
                kind="message",
                role=Role.USER,
                parts=[TextPart(text=user_request)]
            )
            
            # Send the message and stream the response
            print("Sending request and streaming response...")
            print("-"*60)
            
            async for event in coordinator_client.send_message(message=user_message):
                if isinstance(event, Message):
                    # Display message content
                    for part in event.parts:
                        if isinstance(part, TextPart):
                            print(f"\n{part.text}")
            
            print("-"*60)
            print("\nRequest completed successfully!")
            
        except httpx.ConnectError as e:
            print(f"Error: Could not connect to Coordinator Agent at {coordinator_url}")
            print("Make sure the Coordinator Agent is running.")
            print(f"Details: {e}")
        
        except Exception as e:
            print(f"Error during communication: {e}")


async def main():
    """
    Main entry point for the client application.
    """
    # Configuration
    coordinator_url = "http://127.0.0.1:8000"
    
    # Example request
    user_request = "Create a comprehensive report about the benefits and challenges of multi-agent AI systems"
    
    # Send the request
    await send_request_to_coordinator(coordinator_url, user_request)


if __name__ == "__main__":
    asyncio.run(main())

This client demonstrates how external applications interact with A2A agents. It discovers the Coordinator Agent using the well-known Agent Card URI. It sends a message using the A2A protocol. It streams the response, displaying message content as it arrives. The client handles connection errors gracefully, providing helpful feedback.

RUNNING THE COMPLETE MULTI-AGENT SYSTEM

Now that we have implemented all components, let's run the complete system and observe how the agents collaborate through the A2A protocol.

You will need four terminal windows to run this example. Make sure you have activated your virtual environment in each terminal and are in the project directory.

Terminal 1: Start the Research Agent

python research_agent.py

You should see output indicating the Research Agent has started and is listening on port 8001. The agent will display its Agent Card URL.

Terminal 2: Start the Writing Agent

python writing_agent.py

You should see output indicating the Writing Agent has started and is listening on port 8002.

Terminal 3: Start the Coordinator Agent

python coordinator_agent.py

You should see output indicating the Coordinator Agent has started on port 8000 and has identified the URLs of the Research and Writing agents it will coordinate.

Terminal 4: Run the Client

python client.py

You should now see the complete multi-agent workflow in action. The client discovers the Coordinator Agent and sends the request. The Coordinator receives the request and updates its task status to working. The Coordinator discovers the Research Agent via its Agent Card. The Coordinator sends a research request to the Research Agent. The Research Agent processes the request using its local LLM and returns results. The Coordinator receives the research results. The Coordinator discovers the Writing Agent via its Agent Card. The Coordinator sends a writing request with the research results to the Writing Agent. The Writing Agent creates polished content based on the research. The Coordinator receives the written content. The Coordinator sends the final result back to the client. The client displays the complete response.

Throughout this process, you will see detailed logging in each terminal showing the A2A protocol messages being exchanged, task status updates, and the flow of information between agents.

UNDERSTANDING THE A2A MESSAGE FLOW

Let's examine what actually happens under the hood when the client sends a request. Understanding this message flow helps you appreciate how the A2A protocol orchestrates complex multi-agent interactions.

When the client calls send_message on the A2AClient, the client first performs an HTTP GET request to the Coordinator's well-known URI to retrieve its Agent Card. The client examines the Agent Card to understand the Coordinator's capabilities, endpoint URL, and authentication requirements. The client constructs a JSON-RPC 2.0 request with the method message/send and the user's message as a parameter. The client sends this as an HTTP POST request to the Coordinator's API URL. The Coordinator's A2A server receives the request and validates it against the protocol specification. The server creates a new Task with a unique task ID and sets its status to submitted. The server invokes the CoordinatorAgentExecutor's execute method, passing the request context and an event queue. The executor updates the task status to working and sends this update through the event queue. The A2A server converts the status update to a JSON-RPC notification and sends it to the client via Server-Sent Events.

The Coordinator now acts as a client to the Research Agent. It performs an HTTP GET to retrieve the Research Agent's Agent Card. It constructs a JSON-RPC request with the research query. It sends the request to the Research Agent's API URL. The Research Agent receives the request, creates a task, and invokes its executor. The Research Agent's executor uses the local LLM to generate research findings. The Research Agent sends the results back as a Message through its event queue. The A2A server converts this to a JSON-RPC response and sends it back to the Coordinator. The Coordinator receives the research results.

The Coordinator now acts as a client to the Writing Agent. It retrieves the Writing Agent's Agent Card. It constructs a JSON-RPC request with the writing task, including the research results. It sends the request to the Writing Agent's API URL. The Writing Agent receives the request, creates a task, and invokes its executor. The Writing Agent's executor uses the local LLM to create polished content. The Writing Agent sends the written content back as a Message. The Coordinator receives the written content.

Finally, the Coordinator sends the final result to the original client. It creates a Message containing the written content. It sends this through its event queue. The A2A server converts this to a JSON-RPC notification and sends it to the client via Server-Sent Events. The client receives and displays the final result. The Coordinator updates the task status to completed. The client receives the completion notification.

Throughout this entire flow, all communication follows the A2A protocol specification. Messages are formatted as JSON-RPC 2.0 requests and responses. Task lifecycle states are properly managed and communicated. Agent discovery happens through standardized Agent Cards. Authentication and security are handled at the HTTP layer. The protocol abstracts away all these details, allowing developers to focus on agent logic rather than communication mechanics.

ADVANCED A2A FEATURES AND PATTERNS

The example we have built demonstrates the core A2A protocol, but there are several advanced patterns and features worth exploring for production systems.

One important pattern is streaming responses for long-running tasks. The A2A protocol supports Server-Sent Events, which allows agents to stream partial results back to clients as they become available. This is particularly valuable for tasks that take significant time to complete, as it provides immediate feedback and allows for progressive rendering of results. To implement streaming, agents can send multiple Message events through the event queue before sending the final completion status. Each message appears to the client as it is sent, creating a real-time communication channel.

Another valuable pattern is task cancellation and cleanup. The AgentExecutor interface includes a cancel method that is invoked when a client requests task cancellation. In a production system, this method should implement proper cleanup logic, stopping any ongoing LLM generation, releasing resources, and notifying any downstream agents of the cancellation. The A2A protocol ensures that cancellation requests are properly propagated through the task lifecycle.

Error handling and recovery is crucial in production systems. The A2A protocol includes comprehensive error reporting through JSON-RPC error responses. When an agent encounters an error, it should set the task status to failed and include detailed error information in the response. Clients can then decide whether to retry the request, fall back to alternative agents, or report the error to users. Implementing retry logic with exponential backoff is a common pattern for handling transient failures.

Agent discovery and registration can be made more sophisticated by implementing a service registry pattern. Instead of hardcoding agent URLs, you can create a central registry service where agents register themselves at startup and periodically send heartbeat signals. Clients can query the registry to discover available agents with specific capabilities. This enables dynamic agent populations where new agents can join the system at runtime and failed agents can be detected and removed. The registry itself can be implemented as an A2A agent, making it part of the ecosystem rather than a separate infrastructure component.

Load balancing becomes important when multiple agents offer the same capabilities. The A2A protocol's skill-based discovery makes this straightforward. A registry or router agent can maintain a list of all agents offering a particular skill and distribute requests among them based on current load, response time, or other metrics. This allows the system to scale horizontally by adding more instances of popular agent types.

Security and authentication are essential for multi-agent systems that span trust boundaries. The A2A protocol supports various authentication schemes through the securitySchemes field in the Agent Card. Common patterns include bearer tokens where each agent is issued a JWT token that it includes in requests to other agents, API keys for simpler authentication scenarios, OAuth 2.0 for delegated authorization, and mutual TLS for high-security environments. The protocol handles authentication at the HTTP layer, keeping it separate from the JSON-RPC payload and making it compatible with standard web security practices.

Conversation context and memory enable more sophisticated agent interactions. While our example processes each request independently, production systems often need to maintain context across multiple turns. The A2A protocol supports this through the conversation context in messages. Agents can store conversation state in a database or memory store, keyed by conversation ID, and retrieve it when processing subsequent messages in the same conversation. This enables multi-turn dialogues where agents remember previous exchanges and build upon them.

PERFORMANCE CONSIDERATIONS AND OPTIMIZATION

Running multiple LLM instances simultaneously requires careful resource management, especially when using GPU acceleration. Each agent in our example loads its own model, which can quickly exhaust GPU memory. For production deployments, consider these optimization strategies.

Model sharing allows multiple agents to share a single LLM instance, reducing memory footprint significantly. This requires running a model server that agents communicate with via an API. The llama.cpp project includes a server mode that exposes an OpenAI-compatible API. You can run one llama.cpp server instance and configure all your agents to use it as their LLM backend instead of loading models directly. This dramatically reduces memory usage and allows you to run more agents on the same hardware.

Quantization reduces model size and memory requirements at the cost of some accuracy. The GGUF format supports various quantization levels from 2-bit to 8-bit. For many agent tasks, 4-bit or 5-bit quantization provides an excellent balance between quality and resource usage. Experiment with different quantization levels to find the sweet spot for your use case. Generally, research and writing tasks can tolerate more aggressive quantization than tasks requiring precise reasoning or calculation.

Batching can improve throughput when multiple agents have pending requests. Instead of processing each agent's prompt individually, batch them together and process them in parallel. This is particularly effective on GPUs where parallel processing capabilities are underutilized by single requests. However, batching introduces latency as requests wait for a batch to fill, so it works best for high-throughput scenarios rather than interactive applications.

Agent specialization through fine-tuning can improve both quality and efficiency. Rather than using a general-purpose model for all agents, fine-tune smaller, specialized models for each agent type. A research agent might use a model fine-tuned on question-answering and information retrieval tasks, while a writing agent uses one optimized for content generation and style adaptation. Smaller specialized models often outperform larger general models on specific tasks while using fewer resources.

Caching and memoization can eliminate redundant LLM calls. If multiple agents ask similar questions or process similar inputs, cache the results and reuse them. This is particularly effective for capability queries, common research topics, and frequently requested information. Implement a shared cache that all agents can access, with appropriate cache invalidation policies to ensure freshness.

Asynchronous processing is built into the A2A SDK through its use of Python's asyncio. This allows agents to handle multiple concurrent requests without blocking. When an agent is waiting for an LLM response, it can process other requests or perform other work. Make sure your agent implementations properly leverage async/await to maximize concurrency.

MONITORING AND DEBUGGING MULTI-AGENT SYSTEMS

Understanding what is happening inside a multi-agent system can be challenging since interactions are distributed and asynchronous. Implementing comprehensive monitoring and debugging capabilities is essential for development and production operation.

Message logging provides visibility into all agent communications. The A2A SDK can be configured to log all JSON-RPC messages, allowing you to see exactly what data is being exchanged between agents. Implement structured logging that captures message IDs, task IDs, timestamps, sender and recipient information, and message content. Store these logs in a searchable format like JSON Lines or send them to a log aggregation service like Elasticsearch. This makes it easy to trace complete workflows from start to finish and debug issues.

Performance metrics help identify bottlenecks and optimization opportunities. Track metrics like message processing latency measuring the time from receiving a request to sending the first response, LLM inference time tracking how long model generation takes, task completion time measuring end-to-end task duration, queue depths monitoring how many pending requests each agent has, and agent utilization rates calculating the percentage of time agents spend actively processing versus idle. Export these metrics to a monitoring system like Prometheus and create dashboards in Grafana to visualize system behavior.

Distributed tracing provides end-to-end visibility into multi-agent workflows. The A2A SDK supports OpenTelemetry integration, which allows you to trace requests as they flow through multiple agents. Each agent creates spans representing its work, and these spans are linked together to form a complete trace. Tracing tools like Jaeger or Zipkin can then visualize these traces, showing you exactly how long each step took and where bottlenecks occur.

Health checks and heartbeats ensure agents remain responsive. Implement a health endpoint on each agent that returns its current status, including whether the LLM is loaded and ready, how many active tasks it is processing, current queue depth, and resource usage like memory and CPU. A monitoring service can periodically check these endpoints and alert operators to problems. The A2A protocol itself does not define health check mechanisms, but you can add them as additional HTTP endpoints on your agent servers.

Visualization tools can make complex agent interactions comprehensible. Build a web dashboard that displays active agents and their capabilities, current tasks and their states, message flows between agents, and performance metrics in real-time. Sequence diagrams showing message exchanges help developers understand and debug complex workflows. Tools like Mermaid can generate these diagrams programmatically from log data.

EXTENDING THE SYSTEM WITH ADDITIONAL AGENTS

The multi-agent system we have built provides a solid foundation that can be extended in numerous directions. Here are some practical extensions that demonstrate the flexibility of the A2A protocol.

Adding a Verification Agent would enhance the quality of generated content. This agent would receive the written content from the Writing Agent and perform fact-checking, consistency verification, quality assessment, and source validation. It would expose skills like fact-check and quality-assurance in its Agent Card. The Coordinator would add a third step to its workflow, sending the written content to the Verification Agent before returning the final result. This demonstrates how easily new agents can be inserted into existing workflows.

Implementing a Translation Agent would enable multilingual content generation. This agent would expose skills for translating content between various languages. The Coordinator could offer a new skill that generates reports in multiple languages by coordinating the Research, Writing, and Translation agents. The Translation Agent could use a specialized translation model or call external translation APIs, demonstrating how A2A agents can wrap existing services.

Creating a Data Analysis Agent would enable agents to work with structured data. This agent would expose skills for analyzing datasets, generating visualizations, computing statistics, and identifying trends. It could integrate with libraries like pandas and matplotlib. The Research Agent could delegate quantitative research tasks to the Data Analysis Agent, demonstrating agent-to-agent delegation beyond just the Coordinator.

Building a Planning Agent would enable more sophisticated task decomposition. Instead of the Coordinator using simple rules or LLM prompts to break down tasks, it could delegate to a specialized Planning Agent that uses advanced planning algorithms. The Planning Agent would receive a high-level goal and return a detailed execution plan with dependencies, resource requirements, and time estimates. This demonstrates how agents can provide meta-level services to other agents.

Implementing a Memory Agent would enable persistent knowledge across sessions. This agent would maintain a knowledge graph or vector database of information gathered in previous interactions. Other agents could query the Memory Agent to retrieve relevant context before processing new requests. This demonstrates how agents can provide shared services that enhance the capabilities of the entire system.

INTEGRATING WITH EXTERNAL TOOLS AND SERVICES

While our example agents use local LLMs for all processing, production agents often need to integrate with external tools and services. The A2A protocol makes this straightforward since agents encapsulate their implementation details.

The Research Agent could integrate with real web search APIs like Google Custom Search, Bing Web Search, or DuckDuckGo. Instead of relying solely on the LLM's training data, it would perform actual web searches and synthesize the results. The agent's implementation would change, but its Agent Card and A2A interface would remain the same. Other agents would not need to know or care that the Research Agent is now using external APIs.

Database integration allows agents to work with persistent data. An agent could connect to PostgreSQL, MongoDB, or other databases to retrieve information, store results, or maintain state. The A2A protocol's task model maps naturally to database transactions, with task IDs serving as transaction identifiers.

API wrapping enables agents to expose existing services through the A2A protocol. If you have a legacy API or third-party service, you can create an A2A agent that wraps it, translating between the A2A protocol and the service's native API. This allows the service to participate in multi-agent workflows without modification.

Tool use frameworks like LangChain or the Model Context Protocol can be integrated within individual agents. An agent's AgentExecutor can use LangChain to orchestrate complex tool use internally while exposing a simple A2A interface externally. This demonstrates how A2A complements rather than replaces existing agent frameworks.

COMPARISON WITH OTHER AGENT PROTOCOLS

Understanding how the A2A protocol relates to other agent communication standards helps you choose the right tool for your use case.

The Model Context Protocol from Anthropic focuses on how AI models and agents interact with tools and resources. MCP standardizes the interface between models and tools like file systems, databases, and APIs. A2A standardizes how independent agents communicate with each other as peers. These protocols are complementary. An agentic application might use A2A for inter-agent communication while each agent internally uses MCP to interact with its specific tools and resources.

FIPA, the Foundation for Intelligent Physical Agents, is an IEEE standard that has been around since the 1990s. It defines a comprehensive agent communication language based on speech act theory. FIPA is more formal and complex than A2A, with extensive specifications for agent lifecycle management, directory services, and interaction protocols. A2A takes a more pragmatic approach, building on familiar web standards and focusing on practical interoperability. FIPA is better suited for academic research and formal multi-agent systems, while A2A targets practical enterprise deployments.

OpenAI's Swarm framework is a lightweight Python library for building multi-agent systems. Swarm focuses on handoffs and routines between agents within a single application. It is not a protocol but rather a programming framework. A2A is a protocol that enables agents from different developers, frameworks, and organizations to interoperate. You could implement Swarm-style agent coordination using the A2A protocol, but A2A also supports much broader scenarios.

AutoGen from Microsoft Research enables multi-agent conversations with support for both LLM-based and human agents. Like Swarm, AutoGen is primarily a framework rather than a protocol. It provides patterns for agent collaboration within a single application. A2A could be used to connect AutoGen-based agent systems with agents built using other frameworks, providing a standardization layer above the framework level.

LangGraph from LangChain provides stateful, graph-based agent workflows. It excels at defining complex agent interaction patterns within an application. A2A could be used to expose LangGraph workflows as agents that other systems can interact with, or to allow LangGraph-based agents to communicate with agents built using other tools.

PRODUCTION DEPLOYMENT CONSIDERATIONS

Moving from a development prototype to a production multi-agent system requires addressing several operational concerns.

Containerization makes deployment consistent and reproducible. Package each agent as a Docker container with its dependencies, model files, and configuration. Use Docker Compose or Kubernetes to orchestrate multiple agent containers. This ensures agents can be deployed consistently across development, staging, and production environments.

Service discovery in production environments typically uses tools like Consul, etcd, or Kubernetes DNS. Instead of hardcoding agent URLs, agents register themselves with the service discovery system at startup. Clients query the service discovery system to find available agents with specific capabilities. This enables dynamic scaling where new agent instances can be added without reconfiguring existing agents.

Load balancing distributes requests across multiple instances of the same agent type. Use a reverse proxy like nginx or a cloud load balancer to distribute incoming requests. The A2A protocol's stateless design makes this straightforward since any instance of an agent can handle any request for its capabilities.

Monitoring and observability are critical for production systems. Implement comprehensive logging, metrics collection, and distributed tracing as discussed earlier. Set up alerts for error rates, latency spikes, and resource exhaustion. Use tools like Prometheus, Grafana, and Jaeger to monitor system health.

Security hardening protects production systems from attacks. Implement authentication and authorization for all agent endpoints. Use TLS for all communication. Validate and sanitize all inputs. Implement rate limiting to prevent abuse. Run agents with minimal privileges. Regularly update dependencies to patch security vulnerabilities.

Disaster recovery ensures business continuity. Implement backup and restore procedures for any persistent state. Design agents to be stateless where possible, storing state in external databases that can be backed up. Test failover procedures regularly. Implement circuit breakers to prevent cascading failures when agents become unavailable.

CONCLUSION AND FUTURE DIRECTIONS

We have built a complete multi-agent system using Google's A2A protocol, demonstrating how standardized agent communication enables sophisticated collaborative AI systems. The protocol's design principles of agent independence, web standards compatibility, enterprise-grade security, flexible timelines, and content type agnosticism make it practical for real-world deployments.

The key insights from this implementation are that standardization enables interoperability, allowing agents from different developers to work together seamlessly. Capability-based discovery provides flexibility, letting systems adapt to changing agent populations and requirements. Asynchronous message passing enables scalability, allowing agents to process multiple requests concurrently. Task lifecycle management provides visibility, keeping clients informed about long-running operations. Building on web standards reduces complexity, allowing developers to leverage familiar tools and libraries.

The A2A protocol represents an important step toward a future where AI agents from different organizations, built with different tools, can collaborate to solve complex problems. Just as HTTP enabled the web by providing a common protocol for information exchange, A2A aims to enable an ecosystem of interoperable AI agents.

Future developments in this space will likely include enhanced agent reasoning capabilities, allowing agents to engage in more sophisticated negotiation and planning. Improved learning and adaptation, enabling agents to learn from past interactions and improve over time. Standardized agent marketplaces where developers can publish agents and users can discover and compose them into custom workflows. Integration with blockchain and decentralized systems for trustless agent collaboration. Advanced security and privacy mechanisms for handling sensitive data in multi-agent systems.

The multi-agent system we have built is just the beginning. With the foundation of the A2A protocol, you can create increasingly sophisticated agent ecosystems that tackle complex real-world problems through collaboration and specialization. The future of AI is not monolithic models, but ecosystems of specialized agents working together, and the A2A protocol provides the communication layer that makes this future possible.


About the Author: This comprehensive guide was created to help developers understand and implement multi-agent systems using Google's A2A protocol. The examples demonstrate production-ready patterns while remaining accessible to developers new to agent-based architectures.

Resources:

Thursday, November 26, 2026

MERCURY AGENT FOR DUMMIES



A friendly, deep, jargon-light field guide for developers, users and admins who have never touched an agentic AI platform before.


A short note before we begin


This guide is written for three kinds of reader at once. If you're a user who simply wants a clever assistant that can run errands on your own machine, you'll find plain recipes you can copy. If you're an administrator who has to keep the thing safe and running, you'll find the knobs that matter. And if you're a developer who wants to teach Mercury new tricks, you'll find the extension points and real code.

Mercury Agent can be downloaded from https://github.com/ms1963/mercury_agent


What Mercury Agent actually is


Mercury Agent is a self-hosted, extensible agentic AI platform written in TypeScript. That sentence hides three ideas worth unpacking slowly. "Self-hosted" means Mercury runs on your computer or your server, keeps its data in a hidden folder in your home directory, and sends nothing to the outside world except the messages you deliberately forward to whichever AI service you chose. "Agentic" means Mercury doesn't merely chat; it can decide to take actions - read a file, run a shell command, fetch a web page, call an external service - observe the result, and keep going until the job is done. "Platform" means it's not a single program but a small ecosystem: a command-line tool, a web interface, connectors to nineteen chat platforms, multi-agent workflows, a persistent memory, a library of more than seventy-five built-in tools, and a bridge to the Model Context Protocol that works in both directions.


The single most important thing to understand on day one is that Mercury has no brain of its own. It ships with no built-in language model. Think of Mercury as an extremely capable body - hands, eyes, memory, judgement about when to act - that needs you to plug in a brain before it can think. That brain is a Large Language Model (an LLM), and you can supply it from the cloud through providers such as OpenRouter or Abacus.AI ChatLLM, or entirely from your own machine through Ollama or LM Studio. Until you connect at least one real provider, Mercury can start up and show you its interface, but it can't answer a question.


The subsystems you'll meet as you read on fit together like this. A core agent loop decides what to do next and calls tools to do it. A model router chooses which LLM to use for each task so that a trivial question doesn't burn an expensive model. An optional typed decision engine called Jev makes the sharper judgements - which model, how risky a tool call is, whether an incoming message deserves a human - and degrades gracefully to simpler heuristics when it's absent. A gateway layer connects Mercury to Telegram, Slack, Discord, email and many more. A scheduler runs tasks on a cron or in plain English. A workflow engine coordinates several cooperating agents. A voice subsystem turns speech into text and text back into speech. A skills system lets Mercury learn reusable procedures, and a tools system lets it act. Finally, the Model Context Protocol support lets Mercury borrow tools from other programs and lend its own tools to clients such as desktop AI apps.


One honesty note that matches the project's own documentation: as of the current release the core agent loop has been exercised against real LLMs, while the Jev engine, the chat gateways and the voice features are documented and covered by the offline test suite but have not all been proven against live third-party services. Where that matters below, I say so plainly rather than pretending everything has been battle-tested in production.


1. Installing Node.js and then Mercury Agent


Mercury runs on Node.js, the free runtime that executes JavaScript and TypeScript outside a browser, and it needs version 22.5 or newer because it relies on features that only arrived in that release, including the built-in SQLite database. Before anything else, open a terminal and ask Node which version you have.



node -v



If that prints something like v22.5.0 or higher you're ready. If it prints a smaller number or an error, visit https://nodejs.org, download the large green "LTS" button, install it the way you would install any ordinary application, and then run "node -v" once more to confirm the upgrade took hold. This is the only piece of software you ever install by hand; Mercury pulls in everything else it needs on its own.


With Node in place, fetch the Mercury source, step into its folder, install its dependencies and compile it. The three commands below are meant to be run one at a time, and the middle one can take a minute or two the first time because it downloads the project's libraries.



git clone https://github.com/ms1963/mercury_agent.git mercury

cd mercury

npm install

npm run build



The clone step copies the project onto your machine, "npm install" downloads the libraries Mercury depends on, and "npm run build" turns the TypeScript source into the JavaScript that Node actually runs. After the build you can always invoke Mercury through its compiled entry point, which is handy to know when a global shortcut isn't set up.



node packages/cli/dist/bin.js setup

node packages/cli/dist/bin.js serve



Typing that long path every time is tedious, so most people make a global "mercury" command once. The project ships an installer that both builds and links the command for you, and after it runs you can simply type "mercury" from anywhere.



./install.sh

mercury --help



If you would rather not touch your system at all, Mercury runs just as well inside a container, and the data survives restarts because it lives in a named volume rather than inside the container.



docker compose up -d



The default container image is deliberately slim and leaves out the heavier offline voice engines. If you want fully offline speech inside the container you build the voice-enabled variant instead, which additionally bundles ffmpeg, Whisper and Piper at the cost of a larger image.



docker compose --profile voice up -d --build mercury-voice



However you installed it, the very first time you run Mercury you should run its interactive setup, which walks you through creating an administrator account and choosing your first LLM provider. A small but important rule applies in the web interface: the first account that registers becomes the administrator, so register yourself before you expose the interface to anyone else.



mercury setup



Mercury keeps all of its state - your configuration, your conversations, your memory, your skills - in a hidden folder called .mercury inside your home directory. You can move that somewhere else by setting the MERCURY\_HOME environment variable, which is useful when you want several isolated instances or when you keep your home directory small.


2. Giving Mercury a brain: OpenRouter or Ollama


Mercury identifies every model with a two-part name of the form provider/model, for example openai/gpt-4o-mini or ollama/llama3.1. You pick the active one with the "mercury model" command, with the llm.defaultModel configuration key, or with the /model slash command inside a chat. A crucial separation keeps your secrets safe: API keys belong in the file ~/.mercury/.env or in the process environment and never in the configuration file, while the wiring that describes a provider belongs in ~/.mercury/config.yaml. Keeping keys out of config means you can share or back up your config without leaking a secret.


The remote route most people reach for is OpenRouter, a single service that resells hundreds of models behind one key. You drop the key into the environment file and then name an OpenRouter model. Because the key is present, Mercury auto-enables OpenRouter without any further configuration entry, and as a pleasant side effect the optional Jev decision engine becomes available too.



echo 'OPENROUTER_API_KEY=sk-or-...' >> ~/.mercury/.env

mercury model openrouter/openai/gpt-4o-mini



The full model name there reads a little oddly because it's layered: "openrouter" is the Mercury provider, and "openai/gpt-4o-mini" is the model as OpenRouter itself names it, so you can swap in "openrouter/anthropic/claude-3.5-sonnet" or any other model OpenRouter exposes simply by changing the tail.


The local route, which keeps every token on your own machine, is Ollama. You install Ollama from https://ollama.com, pull a model so it exists on disk, and then tell Mercury that the Ollama provider is enabled and which model to use. Ollama needs no API key because it runs locally, which is exactly why you must enable it explicitly: Mercury auto-enables cloud providers when it spots their key in the environment, but a keyless local provider has no key to spot, so you declare it on purpose.



ollama pull llama3.1

mercury config set llm.providers.ollama '{"type":"ollama","enabled":true}'

mercury model ollama/llama3.1



By default Mercury talks to Ollama at http://localhost:11434/v1, which is correct when Ollama runs on the same computer. If your Ollama lives on another machine on your network, add a baseUrl field that points at it, keeping the "/v1" suffix because that's the OpenAI-compatible path Mercury speaks.



mercury config set llm.providers.ollama '{"type":"ollama","baseUrl":"http://192.168.1.50:11434/v1","enabled":true}'



You're not forced to choose one brain forever. You can configure several providers at once and leave llm.defaultModel set to the special value "auto", at which point the model router picks a sensible model for each individual task instead of using a single fixed one. That's how you let cheap models handle easy questions while reserving an expensive model for the hard ones.


3. Configuring Jev, and why you might want to


Jev is Mercury's optional typed decision engine. Where an ordinary LLM writes prose, Jev answers narrow, structured questions - a choice among options, a yes or no, a numeric score - and attaches a confidence to each answer. Mercury uses those crisp judgements in several places at once: to route a task to the right model, to classify whether an incoming instruction looks like a prompt-injection attack, to decide smartly whether a tool call really needs your approval, to triage messages arriving from chat platforms, and to drive retry and reflection decisions when a step goes wrong. The model behind it is typesafe/jev-1.13, reached through OpenRouter, which is why setting your OpenRouter key quietly switches Jev on.


You control Jev with a single configuration key, decision.provider, and its four settings describe a spectrum from automatic to fully offline. The default, "auto", uses Jev only when an OpenRouter key is present and otherwise falls back first to your normal LLM and finally to a safe built-in heuristic, so it's the setting that simply does the right thing. Choosing "jev" forces Jev on and therefore requires the OpenRouter key. Choosing "llm" tells Mercury to make these decisions with your ordinary language model and never call Jev. Choosing "mock" uses only a deterministic heuristic with no network calls at all, which is what the test suite uses.



mercury config set decision.provider auto



The reason to care is partly quality and partly cost and privacy. A dedicated decision model tends to make sharper routing and risk judgements than asking a general chat model to reason about them in prose, and because those judgements are small and structured they are cheap. At the same time Mercury is explicit that it runs perfectly well without Jev - every decision degrades to the configured LLM or to the heuristic - so if you prefer to keep all traffic on a single provider, or to run entirely offline, set decision.provider to "llm" or "mock" and nothing breaks. The current release notes that the Jev engine itself has been exercised in the offline and mock paths rather than extensively against the live decision model, so treat the automatic fallback as a feature, not a disappointment.


4. Integrating external applications such as Telegram


The gateway is the part of Mercury that connects it to chat platforms, and it speaks to a long list of them: Telegram, Discord, Slack, WhatsApp through the Cloud API, Signal through a signal-cli server, Matrix, Mattermost, Microsoft Teams, IRC, email over IMAP and SMTP, SMS through Twilio, Home Assistant, RSS feeds, a generic inbound webhook, the built-in web chat and the terminal itself. The pattern is the same for all of them. You describe one adapter under gateway.adapters in the configuration file, giving its secrets through environment variables so they never sit in the config, you start the server, and the first time an unknown person messages your bot they receive a pairing code that you link to your Mercury account so conversations can follow you across platforms.


Telegram is the gentlest first integration because it uses long polling, which means Mercury reaches out to Telegram and no public URL or webhook is required. You begin inside Telegram itself by talking to the account named BotFather, which hands you a bot token. You then give that token to Mercury, either inline in the adapter config or, better, through the TELEGRAM\_BOT\_TOKEN environment variable, and you make sure the gateway is switched on.



echo 'TELEGRAM_BOT_TOKEN=123456:AA...' >> ~/.mercury/.env

mercury config set gateway.enabled true

mercury config set gateway.adapters.telegram '{"type":"telegram"}'



With the adapter declared you start the server, which runs the web interface, the REST API and the gateway together, and then you message your new bot from your own Telegram account. The bot replies with a pairing code; you claim it once from the terminal, after which your Telegram identity is mapped to your Mercury user and stays mapped.



mercury serve

mercury gateway pair 482913



A nice consequence of pairing is that the slash commands you'll meet in the next section work from Telegram too, so once paired you can type /model or /usage straight from the chat app. Voice memos you send are transcribed automatically, and any message the Jev triage is unsure about is placed in a human review queue rather than acted on blindly. Platforms that receive messages through webhooks rather than polling - Slack, Discord, WhatsApp and the generic webhook among them - additionally need their endpoint reachable from the internet, so for those you also set server.publicUrl; Telegram, being a polling adapter, needs none of that.


5. Conducting a user chat


There are three comfortable ways to talk to Mercury, and they all share the same underlying agent, so a conversation is a conversation wherever you hold it. The quickest is a one-shot question from the terminal, where you pass your message as an argument and Mercury answers once and exits, which is ideal for scripts.



mercury chat "Summarise the README in three sentences"



When you want a back-and-forth you start the interactive read-eval-print loop by running the same command with no message, which drops you into a prompt where each line you type is a new turn and Mercury keeps the context between turns.



mercury chat



For anything visual - watching tool calls happen, browsing past sessions, managing approvals - you run the server and open the web interface in a browser, which also exposes the REST API that other programs can call.



mercury serve --port 3000



Inside any of these surfaces you steer the conversation with slash commands, which behave identically in the terminal, the web chat and every paired chat platform. You begin a clean session with /new or /reset, you inspect or change the model for just this session with /model, and you switch the reasoning style with /pattern, choosing among approaches such as react, plan-execute and reflexion. You re-run your last message with /retry, remove the last exchange with /undo, and halt a long-running agent with /stop. When a session grows large you compress it with /compress, which summarises the history to save context space, and you keep an eye on spend with /usage and /insights. Approvals that are waiting for you appear with /approve and /deny, and you look under the hood with /memory, /tools, /sessions and /debug. A single example shows the shape of them all.



/model ollama/llama3.1



If you never want to memorise any of these, /help prints the list, and /help followed by a topic prints focused guidance on that topic.


6. Using scheduled tasks


Mercury can act on your behalf while you're away by scheduling tasks, and the pleasant surprise is that you can describe the timing in plain English instead of memorising cron syntax. You add a task with "mercury schedule add", giving it a time with the --when option and then the instruction itself as ordinary prose. The scheduler understands phrases such as recurring weekday mornings, fixed intervals and one-off reminders.



mercury schedule add --when "every weekday at 9am" Summarise my inbox

mercury schedule add --when "in 20 minutes" Remind me to stretch



If you prefer the precision of cron, or if a phrase is too unusual for the parser to understand, you can supply a standard five-field cron expression in exactly the same place, and Mercury treats it the same way.



mercury schedule add --when "0 */6 * * *" Check the build status



Results are delivered back to wherever the task came from - the CLI log, the web interface, or a chat platform such as Telegram - and you can redirect delivery explicitly. You manage the whole collection with a family of subcommands that list, edit, pause, resume, delete and run tasks, and editing is a first-class operation so you never have to delete and recreate a schedule just to change one field. Passing a new --when recomputes the next run time.



mercury schedule list

mercury schedule edit 7 --when "every 3 hours" --name "AI News" --task "Summarise top AI headlines"

mercury schedule edit 7 --deliver telegram:123456 --max-retries 5



The same thing is available visually in the Scheduler panel of the web interface, where an Edit button on each row opens an inline editor with the name, timing and task prefilled so you change what you need and press Save.


7. Using workflows


A workflow is how you get several agents to cooperate on one job, and you describe it declaratively in a small YAML file that names a template type and lists the agents involved. The template decides the shape of the collaboration, and Mercury ships a generous set of them: a single agent, a pipeline where each agent feeds the next, a round-robin, a coordinator with workers, a tree, a map-reduce, a router, a shared blackboard, a debate between opposing agents, and a planner paired with an executor. A pipeline is the easiest to picture because the agents simply form an assembly line, and the special token {previous} hands one agent's output to the next while {input} carries the original request.



name: research-report

type: pipeline

agents:

  - name: researcher

    role: Find facts.

    task: "Research: {input}"

  - name: writer

    role: Write clearly.

    task: "Write a report from these notes:\n{previous}"



You run that file by name, passing the topic as the input, and you can equally launch it from the Workflows panel in the web interface. Every run is bounded by budgets - how many sub-agents it may spawn, how deep it may nest, how many total runs it may make - so a misbehaving workflow can't spiral out of control.



mercury workflow run research-report "The history of the transistor"



When a simple pipeline finishes too shallowly for a genuinely hard task, the planner-executor template digs deeper. A planner first breaks the goal into several concrete, ordered steps, an executor then carries out each step in turn while feeding earlier results forward, and a synthesizer writes the final combined answer. If a step fails the planner re-plans once and continues rather than giving up, and each step emits a progress event you can watch. You tune how hard it tries with a small options block.



name: deep-dive

type: planner-executor

options:

  minSteps: 3      # always run at least this many steps

  targetSteps: 5   # how many steps the planner aims for

  maxSteps: 12     # hard cap that is never exceeded

  replanOnFailure: true

agents:

  - name: planner      # breaks the goal into ordered steps

    role: Break the goal into clear, ordered steps.

  - name: executor     # runs each step in turn

    role: Carry out one step at a time.

  - name: synthesizer  # writes the final combined answer

    role: Combine the step results into a complete answer.



The maxSteps cap together with the standard run budgets is what prevents a planner-executor from looping forever, which matters because a planning agent that can re-plan is exactly the kind of thing that could otherwise run away.


8. Configuring speech-to-text and text-to-speech


Mercury can listen and speak. It transcribes voice input - microphone recordings from the web interface, voice memos from chat platforms - and it can read its replies aloud. The design goal here is that speech-to-text and text-to-speech are independently swappable between a commercial cloud API and an open-source self-hosted engine with a single configuration change and no code edits, so you're never locked into one vendor. The fastest way to switch is a named preset, where each preset already bundles the correct provider, base URL, command and model for a known engine. You list the presets, apply one for transcription and one for speech, and inspect the result.



mercury voice presets

mercury voice use stt whisper

mercury voice use tts kokoro

mercury voice show



Those three "use" lines illustrate the whole philosophy. The speech-to-text presets range from the commercial OpenAI cloud, through a self-hosted faster-whisper server called speaches, to a fully offline local Whisper command-line tool. The text-to-speech presets range from commercial OpenAI, through self-hosted open-source servers such as openedai and Kokoro-FastAPI, to the offline local Piper engine and the free Microsoft Edge voices. Applying a preset rewrites the entire voice.stt or voice.tts block in one go, which deliberately removes any stale keys left over from the engine you used before.


If you would rather set things by hand, every underlying key remains available, and two patterns cover most needs. To stay OpenAI-compatible but point at your own server, you change only the base URL, because a self-hosted faster-whisper or Kokoro server exposes the very same routes the OpenAI client already speaks.



mercury config set voice.stt.baseUrl http://localhost:8000/v1

mercury config set voice.tts.baseUrl http://localhost:8080/v1



To go fully offline through local command-line engines you switch the provider itself, at which point Mercury shells out to Whisper for transcription and to Piper for speech rather than making any network call.



mercury config set voice.stt.provider whisper

mercury config set voice.tts.provider piper



One caveat worth stating plainly: the voice subsystem is documented and covered by the offline tests, but it has not been exhaustively proven against every live engine, so when you wire in a particular server, verify a single round trip before relying on it in production.


9. Adding skills


A skill is a reusable procedure written in plain language that teaches Mercury how to approach a certain kind of task well. Mechanically a skill is a folder containing a file named SKILL.md in the agentskills.io format, which is a small block of YAML frontmatter carrying a name and a description followed by Markdown instructions. Mercury shows only the short descriptions of your skills to the model as part of its system prompt and loads the full instructions on demand, so having many skills costs little until one is actually needed. A minimal skill looks like this.



---

name: code-review

description: Review a code change for bugs and security issues. Use when the user asks for a review.

metadata: { version: 1, tags: [code, quality] }

---

# Code review

1. Read the files - do not guess.

2. Look for bugs, missing error handling and security issues.

3. Summarise findings with file and line references.



The description line is doing real work: it's the text the model reads when deciding whether this skill is relevant to the task in front of it, so write it as a clear trigger rather than a vague label. You manage skills from the command line, listing what you have, viewing one in full, and installing a skill from a local path or straight from a git URL, and you scaffold a new one with a single command.



mercury skills list

mercury new skill my-skill

mercury skills install https://github.com/someone/a-useful-skill



Bundled skills live under the repository's skills folder and your own live under ~/.mercury/skills. Beyond hand-written skills, Mercury can distil its own from runs that went well, generalising a proven sequence of tool calls into a reusable, parameterised skill. This is switched off by default because it changes the agent's behaviour over time, and when you enable it the distilled skills start life as proposals that must be approved before the agent may reuse them, with each approved skill tracked by its success rate so that a skill which stops working is retired automatically. You turn the feature on, and optionally let good skills auto-approve, through configuration.



skills:

  distill:

    enabled: true               # master switch for distil, match and record

    autoApprove: false          # keep a human in the loop before reuse

    minToolCalls: 2             # a run needs at least this many tool calls to distil

    retireBelowSuccessRate: 0.5 # auto-retire a skill that drops below this success rate



10. Adding tools


If skills are knowledge, tools are hands. Mercury ships with around seventy-five built-in tools organised into toolsets for files, shell, web, code, memory, skills, scheduling, media and messaging, and every tool carries a risk level of safe, moderate or dangerous. The risk level drives safety: a dangerous tool requires your approval before it runs unless your policy explicitly allows it, which is how Mercury can be both capable and cautious. You survey and curate the built-in tools from the command line or from the Tools and MCP panel in the web interface.



mercury tools list

mercury tools toolsets

mercury tools disable shell



Adding your own tool doesn't require touching Mercury's source, because any folder that contains a tool.json manifest in the repository's tools directory, in ~/.mercury/tools, or in a directory you list under tools.polyglotDirs automatically becomes a tool. These are called polyglot tools because they can be written in any language: Mercury writes the tool's JSON arguments to the process's standard input and reads its standard output back as the result, treating a non-zero exit code as an error. The manifest describes the tool to the model and tells Mercury how to run it.



{

  "name": "slugify",

  "description": "Turn a title into a URL-friendly slug.",

  "toolset": "polyglot",

  "risk": "safe",

  "parameters": {

    "type": "object",

    "properties": { "text": { "type": "string" } },

    "required": ["text"]

  },

  "command": ["node", "main.mjs"],

  "requires": ["node"]

}



Two fields in that manifest deserve attention. The risk field decides whether the tool runs freely or passes through approval gating, so set it honestly - a tool that deletes files isn't "safe". The requires field lists the binaries that must be present on the PATH for the tool to work, and Mercury simply hides the tool when they are missing rather than failing at call time. The program that backs the manifest is ordinary code; a tiny Node script that reads the arguments and prints a slug completes the example.



// main.mjs - reads {"text": "..."} from stdin, prints a slug to stdout.

let input = '';

for await (const chunk of process.stdin) {

  input += chunk;

}

const { text = '' } = JSON.parse(input || '{}');

const slug = text

  .toLowerCase()

  .trim()

  .replace(/[^a-z0-9]+/g, '-')   // non-alphanumerics become single hyphens

  .replace(/^-+|-+$/g, '');      // trim leading and trailing hyphens

process.stdout.write(slug);



Rather than create the folder by hand you can scaffold a correct starter in the language of your choice, which writes the manifest and a runnable stub for you.



mercury new tool slugify --lang js



11. Connecting Mercury to external MCP servers


The Model Context Protocol, usually shortened to MCP, is an open standard that lets one program offer tools to another in a uniform way, and Mercury is an MCP client, so it can borrow tools from any MCP server you point it at. You register a server under mcp.servers in the configuration, giving either a command to launch a local stdio server or an HTTP URL for a remote one, and the server's tools then appear inside Mercury with names of the form mcp_<server>_<tool> so you can always see where a tool came from.


So that you don't have to remember exact command lines, Mercury ships curated presets for several common servers - a filesystem server, a fetch server, a GitHub server, a git server and a SQLite server. You list the presets, enable one, and check that it actually connected.



mercury mcp presets

mercury mcp enable github --name gh

mercury mcp status



The presets never contain secrets. Instead they reference placeholders such as ${GITHUB\_TOKEN}, ${MCP\_FS\_ROOT}, ${MCP\_GIT\_REPO} and ${MCP\_SQLITE\_DB}, which Mercury resolves from the environment at the moment it connects, and if a required variable is unset the enable command tells you which one so you can export it first.



export GITHUB_TOKEN=ghp_your_token_here

mercury mcp enable github --name 


A safety detail matters here: every preset server is registered as untrusted, which means the output of its tools is treated as untrusted data and remains subject to the same policy and approval engine as everything else. That's the right default, because a tool whose behaviour is defined by someone else's server should not be allowed to bypass your safety rules.


12. Calling Mercury from an MCP client


Mercury isn't only a client but also an MCP server, which means other programs - a desktop AI application, a coding assistant, your own script - can borrow Mercury's seventy-five-plus tools through the same protocol. When you run the server, Mercury exposes its tools at the /mcp endpoint over streamable HTTP. Access is token-controlled, so you first mint a token that carries the mcp scope and then present it as a bearer token on each request.



mercury serve

mercury token create claude --scopes mcp



That command prints a token beginning with mrc\_, and an MCP client reaches Mercury by sending it in the standard Authorization header against the /mcp endpoint of your running server.



Authorization: Bearer mrc_xxxxxxxxxxxxxxxxxxxxxxxx



Some desktop clients prefer to launch a local process and talk to it over standard input and output rather than over HTTP. For them Mercury offers a stdio server mode that you start with a single command, which is the form you typically put into a desktop client's configuration so the client spawns Mercury itself.



mercury mcp serve



13. Extending Mercury as a developer


When configuration isn't enough and you want to add genuine new behaviour, Mercury gives you clean extension points, and the lightest of them is a plugin. A plugin is a small JavaScript module that Mercury loads from ~/.mercury/plugins, and in its setup function it receives an API object through which it registers new capabilities. The example below registers a brand-new tool and a hook that logs every tool call, and it illustrates the shape every plugin follows.



// ~/.mercury/plugins/hello.mjs

export default {

  name: 'hello',

  version: '1.0.0',

  setup(api) {

    // Register a new tool the agent can call by name.

    api.registerTool({

      name: 'hello',

      description: 'Say hello',

      toolset: 'custom',

      risk: 'safe',

      parameters: { type: 'object', properties: { who: { type: 'string' } } },

      async execute(args) {

        return `Hello, ${args.who ?? 'world'}!`;

      },

    });


    // Hooks receive a payload and may return a patch object, or nothing.

    api.registerHook('before_tool_call', (payload) => {

      api.logger.info('tool', { tool: payload.tool });

    });

  },

};



The API handed to setup is richer than those two calls suggest. Alongside registerTool and registerHook it offers registerMemoryProvider and registerContextEngine for changing how Mercury remembers, registerLLMProvider and registerDecisionProvider for teaching it to talk to new brains, and registerPattern, registerWorkflowTemplate and registerAdapter for new reasoning styles, new workflow shapes and new chat platforms respectively. The most reliable way to start a real plugin is to let Mercury scaffold an exact, up-to-date skeleton for you rather than copying an example that may drift.



mercury new plugin my-plugin



A gateway adapter is the extension point you reach for when you want Mercury on a chat platform it doesn't yet support. An adapter implements a small, explicit interface - or extends the provided BaseAdapter to inherit the boring parts - whose methods cover the whole life cycle of a connection: starting it and pushing inbound messages into a sink, stopping it cleanly, sending outbound messages, reporting status, and optionally handling a webhook mounted at /webhooks/<name>.



interface Adapter {

  readonly name: string;

  readonly type: string;

  readonly textOnly?: boolean;

  start(sink: InboundSink): Promise<void>;   // connect and push InboundMessage objects to the sink

  stop(): Promise<void>;                      // disconnect cleanly

  send(out: OutboundMessage): Promise<void>;  // deliver a reply to the platform

  status(): AdapterStatus;                     // report health for the Integrations panel

  handleWebhook?(req: WebhookRequest): Promise<WebhookResponse>;  // optional inbound HTTP

}



A design detail that makes adapters pleasant to test is that they perform HTTP through an injected transport rather than calling fetch directly, so a test can substitute a MockTransport and assert on what the adapter would have sent without touching the network. You register an adapter factory from a plugin and then declare it in the configuration just like a built-in one.



api.registerAdapter('myplatform', (config) => new MyAdapter(config));



Two further extension points round out the developer story. A polyglot tool, covered earlier, is the right choice when your logic is easier to write in Python, Go, C++ or Java than in TypeScript. And a custom LLM or decision provider lets you bolt on a backend Mercury has never heard of: an LLMProvider implements the chat and streaming calls for a provider/model id, while a DecisionProvider answers typed questions such as a choice, a boolean or a score together with a confidence. The built-in Jev provider in the source tree is a compact reference you can read while writing your own.


Implementing a client that works with local and remote LLMs


Because so much of Mercury's power comes from the simple idea of one transport feeding many backends, it's worth building that idea yourself in a small, dependency-free client. The program below talks to both a local model server such as Ollama and a remote cloud endpoint such as Abacus.AI ChatLLM or OpenRouter through the single OpenAI "chat completions" wire format, selecting a backend purely by its base URL and an optional key. It mirrors how Mercury itself is organised, and it deliberately has no mocks and no hidden fallbacks: if a backend is unreachable, the call fails loudly. It needs Node.js 22.5 or newer and runs with "node --experimental-strip-types llm-client.ts".


We start with a tiny, explicit vocabulary that every backend shares, so that the rest of the code never has to care which backend it's really talking to. A chat message is a role and some text, a backend is a name, a base URL, a model and an optional key, and a result is normalised down to the text plus a little token accounting.



/** One turn in a conversation, in provider-neutral form. */

export interface ChatMessage {

  role: 'system' | 'user' | 'assistant';

  content: string;

}


/** Everything needed to reach exactly one backend. */

export interface BackendConfig {

  readonly name: string;      // human-readable, e.g. "ollama" or "chatllm"

  readonly baseUrl: string;   // OpenAI-compatible, ends in "/v1", no trailing slash

  readonly model: string;     // model id that backend understands, e.g. "llama3.1"

  readonly apiKey?: string;   // bearer token for remote backends; omit for local servers

}


/** Normalised result returned to the caller regardless of backend. */

export interface ChatResult {

  readonly text: string;

  readonly model: string;

  readonly inputTokens: number;

  readonly outputTokens: number;

}



A robust client has to distinguish a problem worth retrying from one that's hopeless, so we give transport failures their own error type carrying a retryable flag. A momentary 503 from an overloaded server is retryable; a 401 from a wrong key isn't, and retrying it would only waste time and quota.



/** Raised for transport-level failures; `retryable` guides the retry policy. */

export class LlmError extends Error {

  constructor(

    message: string,

    readonly status: number | undefined,

    readonly retryable: boolean,

  ) {

    super(message);

    this.name = 'LlmError';

  }

}



The client itself is one class with two transports behind a shared request builder. The private helpers assemble the headers - adding the Authorization line only when a key exists, which is exactly what lets the same code serve a keyless local Ollama and a keyed cloud endpoint - and the request body, and then POST it with a timeout, translating every HTTP or network failure into the typed error above.



export class OpenAICompatibleClient {

  constructor(private readonly config: BackendConfig) {}


  /** Add the Authorization header only when a key is present. */

  private headers(): Record<string, string> {

    const headers: Record<string, string> = { 'content-type': 'application/json' };

    if (this.config.apiKey) {

      headers.authorization = `Bearer ${this.config.apiKey}`;

    }

    return headers;

  }


  /** Assemble the body shared by the buffered and streaming paths. */

  private body(messages: ChatMessage[], options: ChatOptions, stream: boolean): string {

    return JSON.stringify({

      model: this.config.model,

      messages,

      temperature: options.temperature ?? 0.7,

      max_tokens: options.maxTokens,

      stream,

      // Ask OpenAI-compatible servers to report token usage in the final chunk.

      ...(stream ? { stream_options: { include_usage: true } } : {}),

    });

  }


  /** POST with a timeout; turn HTTP/network failures into a typed LlmError. */

  private async post(messages: ChatMessage[], options: ChatOptions, stream: boolean): Promise<Response> {

    const url = `${this.config.baseUrl}/chat/completions`;

    let response: Response;

    try {

      response = await fetch(url, {

        method: 'POST',

        headers: this.headers(),

        body: this.body(messages, options, stream),

        signal: AbortSignal.timeout(120_000),

      });

    } catch (cause) {

      // DNS failure, connection refused (local server down), or timeout.

      throw new LlmError(`network error calling ${this.config.name}: ${String(cause)}`, undefined, true);

    }

    if (!response.ok) {

      const detail = (await response.text().catch(() => '')).slice(0, 300);

      const retryable = response.status === 429 || response.status >= 500;

      throw new LlmError(`${response.status} from ${this.config.name}: ${detail}`, response.status, retryable);

    }

    return response;

  }

}



The options type the methods above refer to is small, shaping a single request with a temperature, an optional token cap, and a callback that receives streamed fragments as they arrive.



/** Options that shape a single request. */

export interface ChatOptions {

  readonly temperature?: number;             // lower is more deterministic

  readonly maxTokens?: number;               // hard cap on generated tokens

  readonly onDelta?: (fragment: string) => void;  // called with each streamed fragment

}



With the plumbing in place, the first public method asks for a complete answer in one buffered response. It reads the JSON the server returns and copies out the text and the token counts, defaulting each field defensively so a slightly different server shape can't crash the caller. These two methods belong inside the class above.



  /** Request a complete answer in one buffered JSON response. */

  async complete(messages: ChatMessage[], options: ChatOptions = {}): Promise<ChatResult> {

    const response = await this.post(messages, options, false);

    const json = (await response.json()) as {

      model?: string;

      choices?: Array<{ message?: { content?: string | null } }>;

      usage?: { prompt_tokens?: number; completion_tokens?: number };

    };

    return {

      text: json.choices?.[0]?.message?.content ?? '',

      model: json.model ?? this.config.model,

      inputTokens: json.usage?.prompt_tokens ?? 0,

      outputTokens: json.usage?.completion_tokens ?? 0,

    };

  }


  /** Stream the answer token by token, forwarding each fragment to onDelta. */

  async stream(messages: ChatMessage[], options: ChatOptions = {}): Promise<ChatResult> {

    const response = await this.post(messages, options, true);

    if (!response.body) {

      throw new LlmError(`empty stream from ${this.config.name}`, undefined, false);

    }

    const decoder = new TextDecoder();

    let buffer = '';

    let text = '';

    let inputTokens = 0;

    let outputTokens = 0;


    for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {

      buffer += decoder.decode(chunk, { stream: true });

      // Server-Sent-Events are newline-delimited; process every complete line.

      let newline: number;

      while ((newline = buffer.indexOf('\n')) >= 0) {

        const line = buffer.slice(0, newline).replace(/\r$/, '');

        buffer = buffer.slice(newline + 1);

        if (!line.startsWith('data:')) {

          continue;

        }

        const payload = line.slice('data:'.length).trimStart();

        if (payload === '[DONE]') {

          break;

        }

        const event = safeParse(payload);

        if (!event) {

          continue;

        }

        const fragment = event.choices?.[0]?.delta?.content;

        if (fragment) {

          text += fragment;

          options.onDelta?.(fragment);

        }

        if (event.usage) {

          inputTokens = event.usage.prompt_tokens ?? inputTokens;

          outputTokens = event.usage.completion_tokens ?? outputTokens;

        }

      }

    }

    return { text, model: this.config.model, inputTokens, outputTokens };

  }



The streaming parser leans on one small helper and one small type. The helper parses a single Server-Sent-Events payload and returns undefined on malformed JSON rather than throwing, because a half-received chunk must not bring the whole stream down.



/** Shape of the streaming chunk fragments we actually read. */

interface StreamChunk {

  choices?: Array<{ delta?: { content?: string } }>;

  usage?: { prompt_tokens?: number; completion_tokens?: number };

}


/** Parse one SSE payload, returning undefined on malformed JSON. */

function safeParse(payload: string): StreamChunk | undefined {

  try {

    return JSON.parse(payload) as StreamChunk;

  } catch {

    return undefined;

  }

}



The final piece turns a list of backends into a resilient call. It tries the first backend, retries a retryable failure with exponential backoff and a little jitter so that many clients don't all retry in lockstep, and only then moves on to the next backend; a non-retryable error aborts that backend immediately. Listing a local backend first and a cloud backend second gives you a system that prefers to stay offline and private but reaches for the cloud when the local model is down.



/** Sleep helper used by the backoff loop. */

function delay(ms: number): Promise<void> {

  return new Promise((resolve) => setTimeout(resolve, ms));

}


/**

 * Try each backend in order. Retry a RETRYABLE failure with backoff and jitter,

 * then fall through to the next backend. A non-retryable error (e.g. a 401 on a

 * bad key) stops that backend at once, because retrying it would only waste quota.

 */

export async function completeWithFallback(

  backends: readonly BackendConfig[],

  messages: ChatMessage[],

  options: ChatOptions & { retries?: number; backoffMs?: number; jitter?: number } = {},

): Promise<ChatResult> {

  const retries = options.retries ?? 2;

  const backoffMs = options.backoffMs ?? 500;

  const jitter = options.jitter ?? 0.5;

  let lastError: unknown;


  for (const backend of backends) {

    const client = new OpenAICompatibleClient(backend);

    for (let attempt = 0; attempt <= retries; attempt++) {

      try {

        return await client.complete(messages, options);

      } catch (error) {

        lastError = error;

        const canRetry = error instanceof LlmError && error.retryable && attempt < retries;

        if (!canRetry) {

          break;   // non-retryable, or out of attempts: move to the next backend

        }

        const base = backoffMs * 2 ** attempt;

        const sleep = base + Math.random() * base * jitter;

        await delay(sleep);

      }

    }

  }

  throw new LlmError(`all backends failed; last error: ${String(lastError)}`, undefined, false);

}



To see the whole thing work you build the backend list from the environment, always including a local Ollama and adding a remote ChatLLM only when its key is present, so the example runs fully offline against Ollama alone yet uses the cloud automatically when you have a key. A short main function streams an answer from the first backend and then demonstrates the resilient fallback helper.



/** Build the backend list from the environment: Ollama always, ChatLLM if keyed. */

function backendsFromEnv(): BackendConfig[] {

  const backends: BackendConfig[] = [

    {

      name: 'ollama',

      baseUrl: process.env.OLLAMA_BASE_URL ?? 'http://localhost:11434/v1',

      model: process.env.OLLAMA_MODEL ?? 'llama3.1',

    },

  ];

  const remoteKey = process.env.CHATLLM_API_KEY ?? process.env.ABACUS_API_KEY;

  if (remoteKey) {

    backends.push({

      name: 'chatllm',

      baseUrl: 'https://routellm.abacus.ai/v1',

      model: 'route-llm',

      apiKey: remoteKey,

    });

  }

  return backends;

}


/** Entry point: stream from the first backend, then show the fallback helper. */

async function main(): Promise<void> {

  const backends = backendsFromEnv();

  const messages: ChatMessage[] = [

    { role: 'system', content: 'You are a concise assistant.' },

    { role: 'user', content: 'In one sentence, what is an agentic AI platform?' },

  ];


  const primary = new OpenAICompatibleClient(backends[0]!);

  process.stdout.write(`[streaming from ${backends[0]!.name}]\n`);

  const streamed = await primary.stream(messages, {

    temperature: 0.2,

    onDelta: (fragment) => process.stdout.write(fragment),

  });

  process.stdout.write(`\n[tokens in=${streamed.inputTokens} out=${streamed.outputTokens}]\n`);


  const resilient = await completeWithFallback(backends, messages, { temperature: 0.2 });

  process.stdout.write(`[fallback answer] ${resilient.text}\n`);

}


// Run main() only when executed directly, not when imported as a module.

if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {

  main().catch((error) => {

    console.error(error instanceof Error ? error.message : error);

    process.exit(1);

  });

}



The lesson this program teaches is the same lesson that explains Mercury's whole provider design. Because local and remote model servers all speak the one OpenAI-compatible dialect, the only real difference between "private and offline" and "powerful and in the cloud" is a base URL and whether an Authorization header is attached, and once you accept that, switching or combining them becomes a configuration decision rather than a rewrite.


Ideas for exercises


The fastest way to make all of this stick is to use it on something small and real, so here are a handful of graded challenges. As a gentle start, install Mercury, connect Ollama with a small local model, and hold a short conversation entirely offline, noticing that no data leaves your machine. Next, add an OpenRouter key and leave llm.defaultModel on auto, then ask both a trivial question and a hard one and watch the router send them to different models. For a practical win, create a Telegram bot, pair it, and schedule a task that summarises something each morning and delivers the result to your Telegram chat. To feel the extension points, write a polyglot tool in the language you know best - a currency converter or a word counter is plenty - and watch Mercury offer it to the model. Then teach Mercury a repeatable habit by writing a SKILL.md for a task you do often, such as reviewing a pull request, and confirm the model reaches for it. For a taste of cooperation, write a two-agent pipeline workflow in which one agent researches and another writes, and compare its output to a single agent doing the same job. If you administer a shared instance, connect a read-only filesystem MCP server as a preset and verify that its tools arrive as untrusted and still pass through approval. Finally, for the ambitious, build the local-plus-remote client from the previous section and extend completeWithFallback to record which backend eventually answered, which is the first step towards your own routing policy.


Conclusions


Mercury Agent is best understood as a capable, cautious body waiting for a brain. It gives you a command line, a web interface and nineteen chat gateways through which to talk to it; a scheduler and a workflow engine through which to put it to work unattended and in teams; a voice subsystem, a skills library and a seventy-five-strong toolset through which it perceives and acts; and an MCP bridge through which it both borrows and lends abilities. The optional Jev decision engine sharpens its judgement without ever being mandatory, and the whole system is built so that the choice between local privacy and cloud power is a single base URL rather than a fork in your code. If you remember only two things, remember that Mercury needs a real LLM provider before it can answer, and that it's honest about what has and has not been proven - the core loop has run against real models, while some subsystems are so far verified mainly offline. Start small, connect one brain, hold one conversation, and build outward from there.


Addendum: contributing to Mercury through the GitHub repository


Mercury is an open project under the MIT license, and contributing follows an ordinary, friendly pull-request flow. You begin by forking the repository on GitHub and creating a topic branch from main, naming it after the change you intend to make.


git checkout -b feat/short-description



The guiding principle while you work is the smallest diff that does the job: make your change, match the surrounding code style, and resist the urge to reformat untouched code, because churn hides real changes and breeds regressions. Before you open a pull request you keep the build and the tests green and run the linter, since the project expects all three to pass.



npm run build

npm test

npx eslint .



Whenever you change behaviour you add or update tests for it; the suite runs offline against a deterministic mock provider that the test harness enables for you through MERCURY\_ENABLE\_MOCK, and production code must never enable that mock outside tests. You also update the documentation when user-facing behaviour changes, touching the README, the relevant file under docs, and STATUS.md if a subsystem's tested status moves. Commit messages are short, imperative and type-prefixed, so a new feature reads as "feat: add X", a fix as "fix: handle Y", and documentation as "docs: ...". When you open the pull request you describe what changed and why, link any related issue, keep it focused on one logical change, and - in keeping with the project's culture of honesty - you note explicitly if anything was not tested against real external services such as LLM APIs, chat platforms or the speech engines. That last habit is the heart of the project: Mercury's documentation is deliberately candid about what is proven and what isn't, and your contribution is most valuable when it's candid too.