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.

No comments: