Friday, November 27, 2026

MERCURY AGENT AND THE MODEL CONTEXT PROTOCOL: A TWO-WAY DOOR




Mercury Agent is an open-source autonomous Agentic AI written in 2026 by myself in TypeScript. 

Install and use it via downloading its source code: https://github.com/ms1963/mercury_agent



MCP - THE CONNECTOR


Every capable agent eventually hits the same wall. It can reason beautifully, it can plan, it can hold a conversation that feels almost human, and yet it still cannot read the file on your disk, open the ticket in your tracker, or glance at the row in your database. The intelligence is real; the reach is not. The Model Context Protocol, or MCP, is the standard that Mercury Agent uses to tear that wall down, and the reason Mercury's use of it is worth a whole article is that Mercury does not treat MCP as a one-way street. Mercury walks through the door in both directions. It can be an MCP client, reaching out to grab tools and data from the wider world, and it can be an MCP server, offering its own agentic abilities to anything else that speaks the protocol. That symmetry is the red thread of everything below.


WHY A PROTOCOL AT ALL, AND WHY THIS ONE


Before MCP, connecting an agent to an external system meant writing bespoke glue for every single integration, a brittle little adapter per service that broke the moment an API shifted. MCP replaces that sprawl with one shared contract. A server advertises a small, predictable surface made of tools that can be called, resources that can be read, and prompts that can be fetched, and any client that understands the protocol can consume that surface without knowing anything about the server's internals. Mercury leans on this for a very practical reason. An agent's value grows with the number of things it can actually touch, and a standard lets that number grow without the codebase growing in lockstep. The whole MCP subsystem in Mercury lives in a single compact package, three source files that together come to well under a thousand lines, and from that small footprint Mercury gains access to the entire ecosystem of existing MCP servers while simultaneously making itself controllable by the entire ecosystem of MCP clients. The leverage is enormous precisely because the protocol does the standardising.


A compact picture of the two roles will anchor the rest of the discussion. Read the arrows as "makes calls to".


As CLIENT:   Mercury  ---->  filesystem / github / slack / your own MCP servers

As SERVER:   Claude Desktop / IDE / another agent  ---->  Mercury


In the first line Mercury is the one doing the reaching; it borrows the skills of other programs. In the second line Mercury is the one being reached; it lends its own skills out. Keep both lines in mind, because almost every design decision in Mercury's MCP code is really an answer to the question "which side of the door am I standing on right now".


PART ONE: MERCURY AS AN MCP CLIENT


When Mercury acts as a client it is a consumer of capabilities. Somewhere out there a program knows how to list the files in a directory, or search a wiki, or drive a web browser, and Mercury wants to fold those abilities into its own tool loop so that, from the model's point of view, calling a remote MCP tool feels no different from calling a built-in one. The entry point for this is a small manager class, and the first thing it must decide for any configured server is how to physically talk to it. MCP allows three transports, and Mercury supports all of them, choosing between them from plain configuration rather than code.


// From the MCP client manager: pick a transport purely from config.

// stdio launches a child process and speaks over its pipes; the two HTTP

// variants connect to an already-running network server.

private transportFor(cfg: McpServerConfig): Transport {

  if (cfg.transport === 'stdio') {

    if (!cfg.command) throw new Error('stdio MCP server needs "command"');

    // A local subprocess: Mercury spawns it and owns its lifecycle. The child's

    // own environment is merged with any extra vars the user supplied in config.

    return new StdioClientTransport({

      command: cfg.command,

      args: cfg.args,

      env: { ...getDefaultEnvironment(), ...cfg.env },

      stderr: 'pipe',

    });

  }

  // Network transports need a URL rather than a command.

  if (!cfg.url) throw new Error(`${cfg.transport} MCP server needs "url"`);

  const init = { requestInit: { headers: cfg.headers } };

  // "sse" is the older event-stream transport; anything else is modern

  // Streamable HTTP, which is the recommended default for networked servers.

  return cfg.transport === 'sse'

    ? new SSEClientTransport(new URL(cfg.url), init)

    : new StreamableHTTPClientTransport(new URL(cfg.url), init);

}


The elegance here is that the rest of the manager never again cares which transport was chosen. A local filesystem server launched as a child process and a remote corporate wiki reached over authenticated HTTPS both resolve down to the same abstract Transport object, and from that point on the code path is identical. This is clean architecture doing its quiet job: the messy differences between a spawned subprocess and a network socket are confined to one small method, and the rest of the system programs against the stable idea of a connection rather than the unstable details of a wire.


Once connected, the real work begins, which is discovery. Mercury asks the server what it can do, receives a list of tool definitions, and then performs the single most important translation in the whole client: it turns each foreign tool into a native Mercury tool and registers it in the same registry that holds Mercury's own built-ins.


// Connect to one server, then register each of its tools under a namespaced name.

await client.connect(this.transportFor(cfg));

const { tools } = await client.listTools();

for (const t of tools) {

  // include/exclude are glob filters: when include is non-empty a tool must match

  // one of its patterns, and any tool matching an exclude pattern is always dropped.

  // This lets an operator expose only "search_*" from a server that offers fifty tools.

  if (cfg.include.length && !cfg.include.some((p) => globMatch(p, t.name))) continue;

  if (cfg.exclude.some((p) => globMatch(p, t.name))) continue;

  const tool = this.wrapTool(name, cfg, client, t);

  this.registry.register(tool);

  status.tools.push(tool.name);

}


Notice that filtering happens at the moment of registration, not at the moment of calling. A tool that fails the include or exclude test is never registered at all, which means the model literally cannot see it and cannot be tempted to invoke it. This is a small decision with a large security payoff, and it illustrates a recurring theme in Mercury's client: the safest tool call is the one the model was never offered in the first place. The naming of what does survive the filter matters too, because dozens of servers could in principle define a tool called "search", and a flat namespace would collapse into collisions. Mercury avoids that with a deterministic naming rule.


// Build a collision-proof, model-safe tool name: mcp_<server>_<tool>,

// stripped of any character a tool name may not contain and capped at 64 chars.

export const mcpToolName = (server: string, tool: string) =>

  `mcp_${server}_${tool}`

    .replace(/[^a-zA-Z0-9_-]/g, '_')

    .slice(0, 64);


A tool named "search" on a server registered as "wiki" becomes "mcp_wiki_search", and the same tool on a "github" server becomes "mcp_github_search". The prefix carries the provenance of the capability directly in its identifier, so when the model later decides to call one, both the model and any human reading the trace can see at a glance where that power came from. The server name also becomes the tool's toolset label, written as "mcp:wiki", which lets Mercury disconnect a server later and unregister every one of its tools in a single clean sweep without hunting them down individually.


The wrapping step does more than rename, however. It is where Mercury makes a judgement about how much to trust the foreign tool, and this is one of the most thoughtful parts of the whole design. An MCP server describes its own tools, including optional hints about whether a tool merely reads data or destructively changes it. Those hints are useful, but they are also self-reported by a party Mercury may have no reason to trust, so Mercury treats them with calibrated skepticism.


// Decide the risk level and taint of a foreign tool before registering it.

private wrapTool(server, cfg, client, t): AnyTool {

  const destructive = t.annotations?.destructiveHint === true;

  // A server may CLAIM a tool is read-only, but Mercury only believes that

  // downgrade when the operator has explicitly marked the whole server 'trusted'.

  const readOnly = t.annotations?.readOnlyHint === true && cfg.trust === 'trusted';

  return {

    name: mcpToolName(server, t.name),

    description: `[MCP ${server}] ${t.description ?? t.name}`,

    toolset: `mcp:${server}`,

    parameters: (t.inputSchema as JsonSchema) ?? { type: 'object', properties: {} },

    // A self-declared destructive tool is always dangerous; a believable read-only

    // tool is safe; everything in between is treated as moderate risk.

    risk: destructive ? 'dangerous' : readOnly ? 'safe' : 'moderate',

    sensitive: !readOnly,

    // Output from any non-trusted server is marked as tainted external content,

    // so Mercury's prompt-injection defences spotlight it like any other web text.

    untrustedOutput: cfg.trust !== 'trusted',

    source: `mcp:${server}`,

    async execute(args, ctx) {

      const res = await client.callTool(

        { name: t.name, arguments: args as Record<string, unknown> },

        undefined,

        { signal: ctx.signal },  // honour cancellation from the agent loop

      );

      return {

        content: mcpContentToText(res.content),

        isError: res.isError === true,

        data: res.structuredContent,

      };

    },

  };

}


The crucial line is the one that only honours a read-only claim when the server is configured as trusted. An untrusted server can shout that its tool is perfectly harmless, and Mercury will politely decline to believe it, keeping the tool at moderate risk and, just as importantly, flagging everything the tool returns as untrusted output. That last flag feeds Mercury's taint tracking, the same machinery that treats arbitrary text fetched from the open web as potentially hostile. The reasoning is sound and worth stating plainly: content coming back from a third-party server is external input, and external input is exactly where prompt-injection attacks hide, so a row from someone else's database or a page from someone else's wiki is handled with the same wariness as a random web page. The default trust level for every server is untrusted, so safety is the state you get without doing anything, and trust is something an operator must grant deliberately.


There is one more client capability that elevates Mercury above a mere tool caller, and it is genuinely clever. MCP has a feature called sampling, in which a server, in the middle of doing its own work, can turn around and ask the client's language model to generate a completion for it. In effect the external server borrows Mercury's brain for a moment. Mercury supports this, but only when sampling has been explicitly allowed for that server, and it routes the request through its own LLM service so that the borrowed brain is governed by all the same rules as everything else.


// When a server is allowed to sample, Mercury answers its completion requests

// using its OWN language model ? local or remote, whichever is configured.

if (cfg.allowSampling && this.llm) {

  const llm = this.llm;

  client.setRequestHandler(CreateMessageRequestSchema, async (req) => {

    // Flatten the server's messages into Mercury's own message shape.

    const messages = req.params.messages.map((m) => ({

      role: m.role as 'user' | 'assistant',

      content: (m.content as { type: string; text?: string }).type === 'text'

        ? ((m.content as { text?: string }).text ?? '')

        : '[non-text content]',

    }));

    if (req.params.systemPrompt) {

      messages.unshift({ role: 'user', content: `System: ${req.params.systemPrompt}` });

    }

    // The completion runs under the SYSTEM principal and is tagged 'mcp-sampling',

    // so it is routed, budgeted and logged exactly like any other model call.

    const res = await llm.complete(SYSTEM_PRINCIPAL, messages, {

      maxTokens: req.params.maxTokens,

      kind: 'mcp-sampling',

    });

    return { model: res.modelId, role: 'assistant', content: { type: 'text', text: res.content } };

  });

}


What makes this important rather than merely neat is that the borrowed brain is the very same LLM service that Mercury uses for its own reasoning, which means a server asking for a completion gets routed, budgeted, rate-limited and recorded through one single path. There is no secret second channel to a model that bypasses Mercury's accounting, and the model that answers can be a tiny private model running on your laptop or a frontier model in the cloud, because the sampling bridge does not care which; it simply calls complete and lets Mercury's model routing decide. We will return to that local-or-remote freedom shortly, because it is a theme of its own.


Configuring all of this is deliberately plain. Everything the manager reads comes from a small block of the Mercury configuration file, and a representative one looks like this.


# ~/.mercury/config.yaml  ? the client half of Mercury's MCP configuration

mcp:

  servers:

    filesystem:                       # becomes the tool prefix: mcp_filesystem_*

      transport: stdio                # spawn a local child process

      command: npx

      args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/me/projects"]

      trust: untrusted                # its file contents are treated as tainted input

      enabled: true

    wiki:

      transport: http                 # modern Streamable HTTP to a running server

      url: https://wiki.internal/mcp

      headers:

        Authorization: "Bearer ${WIKI_TOKEN}"   # secret pulled from the environment

      include: ["search_*", "get_page"]          # expose only these two tools

      allowSampling: false

      enabled: true


The secret in that example is never written literally into the file; it is a placeholder that Mercury expands from the environment when it connects, so the configuration can be committed or shared without leaking a token. Typing this block by hand is optional, mind you, because Mercury ships a library of curated presets for well-known servers, each one a ready-made configuration whose only blanks are the environment variables it needs. A preset for the official filesystem server, for instance, already knows the package name and the command to run, and leaves you nothing to supply but the root directory.


// A curated preset: a safe, complete config with secrets left as ${PLACEHOLDERS}.

{

  name: 'filesystem',

  description: 'Read/write files under a sandboxed root directory',

  requiredEnv: ['MCP_FS_ROOT'],               // the one thing the user must provide

  provenance: 'official',                      // honestly recorded: first-party server

  pkg: '@modelcontextprotocol/server-filesystem',

  config: server({

    transport: 'stdio',

    command: 'npx',

    args: ['-y', '@modelcontextprotocol/server-filesystem', '${MCP_FS_ROOT}'],

    // every preset is DISABLED until the user explicitly enables it

  }),

}


Every preset carries an honest note about its provenance, distinguishing a first-party official server from a still-published but archived reference server and from a third-party community package, so that a user deciding whether to trust something with credentials is told plainly what they are about to run. Enabling a preset substitutes the environment values into the placeholders and flips a single flag from disabled to enabled, after which the ordinary connection machinery picks it up with no special casing. The design keeps a firm rule throughout, which is that a preset is a template and never a live secret, so nothing sensitive is ever baked into the shipped code. A user browses the catalogue and turns one on with a pair of commands, and the familiar discovery-and-registration flow described above does the rest.


mercury mcp presets            # browse the catalogue, see provenance and env needs

mercury mcp enable filesystem --connect   # resolve placeholders, enable, connect now


PART TWO: MERCURY AS AN MCP SERVER


Now we step through the door the other way. When Mercury acts as a server, it stops being the consumer and becomes the capability. An external application that speaks MCP, whether that is a desktop chat client, a code editor, or another autonomous agent, can connect to Mercury and drive it, and what Mercury offers is not a handful of trivial functions but its entire agentic self. The server exposes three kinds of surface, and understanding them explains why making Mercury an MCP server is so much more than exposing an API.


The richest surface is a set of meta-tools, high-level verbs that each wrap a whole slice of Mercury. The headline one runs the full agent, tool loop and memory and skills included, from a single call.


// A meta-tool exposed to MCP clients: run the complete Mercury agent on a task.

{

  name: 'run_agent',

  description: 'Run the Mercury agent on a task (full tool loop, memory, skills). '

             + 'Pass session_id to continue a conversation.',

  scope: 'agent',                          // the caller's token must carry this scope

  inputSchema: obj(

    {

      input:      s('Task or message'),

      session_id: s('Existing session id'),

      pattern:    s('react, plan-execute, reflexion, ... or auto'),

      model:      s('Model id or auto'),

    },

    ['input'],                             // only `input` is required

  ),

  async run(b, p, a) {

    const r = await b.runAgent(p, String(a.input), {

      sessionId: a.session_id as string,

      pattern:   a.pattern as string,

      model:     a.model as string,

    });

    // The reply carries the session and run ids so the caller can continue later.

    return `${r.output}\n\n[session_id: ${r.sessionId}, run_id: ${r.runId}, status: ${r.status}]`;

  },

}


Alongside run_agent sit companions for running a named multi-agent workflow, listing the available workflows, searching and adding to long-term memory, listing and reading skills, and listing and creating scheduled jobs. The practical effect is striking. A user sitting inside their favourite desktop assistant can, without leaving it, ask Mercury to remember a fact permanently, kick off a long-running workflow, or schedule a task to fire every weekday morning, because each of those abilities is a meta-tool on the server. Beyond the verbs, Mercury also publishes readable resources, which include each skill as a document at a skill address and the curated memory files at their own addresses, and it publishes one prompt per skill so a client can fetch a skill as a ready-to-use instruction block. Tools do things, resources let the client read things, and prompts hand the client reusable expertise, and together they make Mercury feel less like a service being called and more like a colleague being consulted.


None of this would be safe without a gate, and the gate is capability scopes carried by the caller's token. Every meta-tool declares the scope it needs, and the server checks that scope on every single request before it will act, using a small helper whose rules repay a careful reading.


// A principal may use a scope if it holds the wildcard, holds that exact scope,

// or holds 'admin' (which stands in for any non-admin scope).

export function hasScope(p: Principal, scope: string): boolean {

  return p.scopes.includes('*')

      || p.scopes.includes(scope)

      || (scope !== 'admin' && p.scopes.includes('admin'));

}


// Inside the server, a call is permitted only when the token carries BOTH the

// umbrella 'mcp' scope AND the specific scope the requested tool declares.

const allowed = (scope: string) => hasScope(principal, 'mcp') && hasScope(principal, scope);


The double requirement is the heart of the server's safety. A token must first prove it is allowed to use the MCP surface at all by carrying the mcp scope, and then separately prove it is allowed to use the particular capability by carrying that capability's own scope, so a token minted only for memory access can search and store memories but cannot run the agent or touch the scheduler. The same check guards the resources and the prompts, and the direct pass-through tools, the ones that expose Mercury's individual built-in tools under a mercury_ prefix, are gated behind their own tools scope so that a client is only handed that lower-level power when an operator has explicitly granted it. Because the entire server is constructed around one authenticated principal, the scope checks are not scattered guesswork but a single consistent policy applied at every entrance.


Serving happens over two transports that mirror the client side. For a desktop application that launches Mercury as a child process, Mercury serves over stdio, and the wiring is almost startlingly short because the protocol library does the heavy lifting.


// Serve Mercury over stdio (used by `mercury mcp serve`): build a server bound to

// one authenticated principal, then connect it to the standard stdio transport.

export async function serveStdio(backend: McpBackend, principal: Principal): Promise<Server> {

  const server = createMcpServer(backend, principal);

  await server.connect(new StdioServerTransport());

  return server;

}


For networked callers, Mercury serves the same surface over Streamable HTTP at a configurable path, and it does so in a stateless style, building a fresh server and transport for each incoming request and tearing them down when the response closes.


// Handle one Streamable HTTP request statelessly: a new server+transport per call,

// which is simple to reason about and scales horizontally with no shared state.

export async function handleMcpHttp(backend, principal, req, res, body): Promise<void> {

  const server = createMcpServer(backend, principal);

  const transport = new StreamableHTTPServerTransport({

    sessionIdGenerator: undefined,   // stateless: no server-held session

    enableJsonResponse: true,

  });

  res.on('close', () => {            // clean up when the client disconnects

    void transport.close();

    void server.close();

  });

  await server.connect(transport);

  await transport.handleRequest(req, res, body);

}


The route that invokes this first authenticates the request, requiring a bearer token with permission to access the MCP endpoint, and only then hands control to the handler with the resolved principal already in hand. The statelessness is a deliberate architectural choice rather than a shortcut, because holding no session between requests means any instance of Mercury can answer any request, which is exactly the property you want when you put several instances behind a load balancer. A short figure captures the authenticated server path.


client request --> authenticate bearer token (needs mcp.access)

               --> build MCP server bound to that principal

               --> every tool/resource/prompt call re-checked against the principal's scopes

               --> stateless response, server torn down on close


PART THREE: THE BRAIN BEHIND BOTH DOORS, LOCAL AND REMOTE


Both halves of the story quietly depend on one shared faculty, the language model itself, and Mercury is deliberately indifferent about where that model lives. The sampling bridge on the client side calls the same model service that the agent uses, and the run_agent meta-tool on the server side runs that same agent, so the question of which model answers is settled in one place for everything. Mercury's answer is that a model is just an OpenAI-compatible endpoint, and a local model on your own machine and a remote model in a data centre differ by little more than a base URL and whether a key is required. The built-in defaults make the point concisely.


// Mercury's default base URLs. Local backends point at loopback and need no key;

// remote backends point at a vendor API and authenticate with a key from the env.

export const DEFAULT_BASE_URLS: Record<string, string> = {

  openai:     'https://api.openai.com/v1',

  openrouter: 'https://openrouter.ai/api/v1',

  lmstudio:   'http://localhost:1234/v1',   // local, private

  ollama:     'http://localhost:11434/v1',  // local, private

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

};


Because all of these speak the same OpenAI-compatible dialect, Mercury drives every one of them through a single provider implementation, and the only thing that distinguishes a private Ollama model from a hosted OpenRouter model is the three values that describe the endpoint. The user asked for code that works with local and remote models together, and the honest way to show it is to write exactly the small, transport-agnostic function that mirrors how Mercury itself treats these backends. The following module talks to any OpenAI-compatible model, near or far, through one code path.


/**

 * llm-endpoints.ts ? one code path for local AND remote language models.

 *

 * This mirrors how Mercury's own OpenAICompatibleProvider treats backends:

 * a local Ollama/LM Studio server and a remote OpenRouter/OpenAI endpoint

 * differ only by base URL and whether an API key is required. Nothing else.

 */


// A backend is fully described by three values. "Local" vs "remote" is NOT a

// special case in the code; it is just a different base URL (and maybe no key).

export interface LlmEndpoint {

  readonly baseUrl: string;   // e.g. http://localhost:11434/v1  OR  https://openrouter.ai/api/v1

  readonly model: string;     // e.g. llama3.1                   OR  deepseek/deepseek-v4.1-flash-1017

  readonly apiKey?: string;   // local servers usually need none; remote ones require it

}


// The default endpoints Mercury ships with, so callers need not memorise URLs.

export const ENDPOINTS: Record<string, string> = {

  ollama:     'http://localhost:11434/v1',  // local, private, no key

  lmstudio:   'http://localhost:1234/v1',   // local, private, no key

  openrouter: 'https://openrouter.ai/api/v1',

  openai:     'https://api.openai.com/v1',

};


/**

 * Send a chat completion to any OpenAI-compatible endpoint. The SAME function

 * serves a local model and a hosted one; only the `ep` argument changes.

 */

export async function complete(ep: LlmEndpoint, prompt: string): Promise<string> {

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

  // Attach Authorization ONLY when a key exists, so loopback servers that reject

  // an unexpected auth header keep working without special-casing.

  if (ep.apiKey) headers.Authorization = `Bearer ${ep.apiKey}`;


  const res = await fetch(`${ep.baseUrl}/chat/completions`, {

    method: 'POST',

    headers,

    body: JSON.stringify({

      model: ep.model,

      messages: [{ role: 'user', content: prompt }],

    }),

  });


  // Fail loudly with the server's own message rather than returning a silent empty

  // string, so a misconfigured endpoint is diagnosable instead of mysterious.

  if (!res.ok) {

    throw new Error(`LLM ${ep.baseUrl} returned ${res.status}: ${await res.text()}`);

  }


  const data = (await res.json()) as {

    choices: Array<{ message: { content: string } }>;

  };

  return data.choices[0].message.content;

}


The single function above is the whole trick, and the payoff shows when we wire up both kinds of backend and then choose between them by policy rather than by rewriting any code. A privacy rule is a natural way to choose: anything that looks like it carries a secret stays on the machine, and everything else may go to the faster, stronger hosted model.


import { complete, ENDPOINTS, type LlmEndpoint } from './llm-endpoints.js';


// Remote backend: OpenRouter, whose key is read from the environment and never

// hardcoded. This is the strong, fast cloud option.

const remote: LlmEndpoint = {

  baseUrl: ENDPOINTS.openrouter,

  model: 'deepseek/deepseek-v4.1-flash-1017',

  apiKey: process.env.OPENROUTER_API_KEY,

};


// Local backend: Ollama on this very machine, fully offline, no key required.

// This is the private option that never lets data leave the host.

const local: LlmEndpoint = {

  baseUrl: ENDPOINTS.ollama,

  model: 'llama3.1',

};


// Route by policy: keep anything sensitive on the local model, send the rest

// to the remote one. Switching backends is a data decision, not a code change.

async function answer(userText: string): Promise<string> {

  const looksSensitive = /password|secret|api[_-]?key|ssn/i.test(userText);

  const endpoint = looksSensitive ? local : remote;

  return complete(endpoint, userText);

}


The deep point this illustrates is why the two MCP roles compose so cleanly with the model layer. When a trusted external server uses sampling to borrow Mercury's brain, the brain it borrows is whichever endpoint this routing selects, so a sensitive sampling request can be served entirely by a local model and never leave the building. When an external client calls run_agent on Mercury's server, the agent it drives reasons on that same selectable backend, so an operator can run the whole exposed agent on a private model if policy demands it. Mercury does not maintain one model path for its own thinking and a different one for MCP; there is a single gateway, and every call, whether it originates from Mercury's own loop, from a server's sampling request, or from an external client's agent run, flows through it and is routed, budgeted and logged the same way. In Mercury's real registry this is taken one step further, because a cloud provider is auto-enabled the moment its API key is found in the environment, so wiring a remote model can be as little as exporting a key, while a local model needs nothing but the local server to be running.


HOW THE WHOLE THING HANGS TOGETHER


Stepping back, the reason MCP is leveraged so heavily inside Mercury is that it answers two different needs with one coherent idea. Outbound, as a client, MCP is how Mercury grows its reach without growing its complexity, pulling in filesystems, repositories, search engines, browsers, databases and chat platforms as interchangeable, namespaced, risk-rated, taint-tracked tools that the model can call as if they were its own, with untrusted output quarantined and dangerous operations flagged. Inbound, as a server, MCP is how Mercury lends its hardest-won abilities, its full agent loop, its workflows, its memory, its skills and its scheduler, to any application the user already lives in, gated behind a precise two-part scope check and served over either a spawned pipe or a stateless HTTP endpoint. Underneath both, the model layer stays studiously neutral about whether intelligence comes from a chip on your desk or a server across the world, which means the privacy and cost trade-off is yours to make and can be made differently for different requests without touching a line of the MCP code.


The final picture is simply the two earlier arrows joined into a loop, with Mercury as the hub that both consumes and provides.


external MCP servers  ---->  [ Mercury: client side ]

                                    |

                             one shared agent + model gateway (local or remote)

                                    |

                             [ Mercury: server side ]  ---->  external MCP clients


That loop is the whole thesis of this article in one figure. Mercury is not merely connected to the MCP ecosystem; it sits inside it as a full participant, equally happy to borrow a capability or to be one, and the small, careful, security-conscious code that makes this true is a good deal more interesting than its modest size would suggest.

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: